Search code examples
classandroid-activitybroadcastreceiver

Bring activity in front on receiving Broadcast signal from another class


I have main activity that just registers the broadcast receiver for ACTION_USER_RESENT. I have written the code for receiving the broadcast signal in another class as follows.

 public class ReceiverScreen extends BroadcastReceiver{
      @Override
      public void onReceive(Context context, Intent intent) {
           // TODO Auto-generated method stub
           if(intent.getAction().equals(Intent.ACTION_USER_PRESENT))
           {
                //?
           }
      }
 }

Scenario: When I run the program it runs and I am not exiting the program and just pressing the home button on device i.e. the app remains running.

Question: When I lock and unlock back the mobile it shows the home screen of the mobile. But I want my app to show after unlocking the mobile. What should I write inside the if condition above so that my app is visible first.

Please help...


Solution

  • You can write below code in your onReceive().

    public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(Intent.ACTION_USER_PRESENT))
            {
    
                Intent intent = new Intent(context,YourActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
        }
    

    So, when screen is unlocked, your app will receive ACTION_USER_PRESENT broadcast and from there you can start your Application's Activity.

    The Flag FLAG_ACTIVITY_NEW_TASK is required otherwise your app will crash with java.lang.RuntimeException because, Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag.