Android make the application autorun after unlocking the screen even if the application is not running

671 Views Asked by At

I'm trying to create an autorun service: so that the application launches every time after unlocking the screen, after entering the graphic key or password if it exists (on Android 7,8,9,10). I wrote the code dynamically through the borocast receiver (ACTION_SCREEN_OFF) but it works while the application is on the stack (running) and I want it to always start. The method through registering in the manifest in android 9 already does not work the listeners. How to implement this?

public class WordsBase extends AppCompatActivity {
    ScreenReceiver resiverStart;

 @Override
 protected void onPause() {
        super.onPause();

        resiverStart= new ScreenReceiver();
        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
        registerReceiver(resiverStart,filter);
    }
}
public class ScreenReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            Intent intent1 = new Intent(context, WordsBase.class);
            intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent1);
        }
        throw new UnsupportedOperationException("Not yet implemented");
    }
}
1

There are 1 best solutions below

2
BBB On

I understand that you want to do the following: If the user unlocks the device, you want to start your app.

Why don't you do the following:

  1. Use the USER_PRESENT receiver (android.intent.action.USER_PRESENT). Please not that you have to register explicitly to this receiver, just registering it in the manifest is not enough
  2. If the respective broadcast is fired, start your app and make sure you are still registered to the broadcast (to have your app started again the next time the user unlocks the device).