Question

I have a requirement that whenever an app is opened by user, an event should be generated based on which I have to do some processing in my app. I realize that android do not broadcast that event. Hence, I am stuck and looking for a work around.

I have also come across some apps that do the similar thing such as:

Avast Mobile Security: Scans the app when it is opened.

Vault: Shows password keypad when a locked app is opened.

Can anyone tell me how these apps are detecting the app opening event or point me in right direction to do.

I have previously done some Windows API Hooking and not sure if I could use this technique in android also. I have come across some runtime code injection frameworks like "Cydia Substrate" and "Xposed". Can these things solve my problems?

Était-ce utile?

La solution 2

I have solved the problem by taking a workaround. It is not the exact solution but my problem has been solved. What I have done is that I have used AlarmManager to launch a repeated service (say After 10 seconds) which checks for new application top of the activity stack every time. If the Application is different from the last application (already saved) this is the new app that has been opened. The major drawback of this approach is that it eats up battery but you can select a suitable period and do not wake up the device.

This service launching code is given below:

//Start a Service that is started every 5 seconds
AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(MyActivity.this, MyService.class);
PendingIntent pintent = PendingIntent.getService(context, 0, intoo, 0);
alarm.setRepeating(AlarmManager.RTC, cal.getTimeInMillis(), 5*1000, pintent);

In MyService.java you should check for new application on top of the activity stack.

Autres conseils

It is handled within each Activity's onStart() or onCreate() method. I would put your check inside onStart().

@Override
    protected void onStart()  { 
        super.onStart();
//..Do processing.
}

You can save certain items inside onStop or onPause methods so that data persists after the user leaves the App.

If it's a Fragment, then u have to do it in onAttach:

    @Override
    public void onAttach(Activity activity) {
//..Do Processing.
        super.onAttach(activity);    
    }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top