How to bring an application from the background to the foreground through BroadcastReceiver

I have two classes that MainActivity and MyBroadcastReceiver. BroadcastReceiver determines if the phone screen is on. My desire is to launch my application whenever the screen lock is released. I mean, I want to bring my application to the forefront when it unlocks the phone.

Here is my activity class:

public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); registerReceiver(); } private void registerReceiver(){ IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); BroadcastReceiver mReceiver = new MyPhoneReceiver(); registerReceiver(mReceiver, filter); } } 

And here is my broadcast receiver:

 public class MyPhoneReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); if(pm.isScreenOn()){ //Bring application front } } } 

What should I do to perform this operation in my broadcast receiver?

+2
source share
3 answers

Do the following in the onReceive method for BroadcastReceiver

 @Override public void onReceive(Context context, Intent intent) { Intent newIntent = new Intent(); newIntent.setClassName("com.your.package", "com.your.package.MainActivity"); newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); context.startActivity(newIntent); } 

For your purposes, you need the flag "FLAG_ACTIVITY_NEW_TASK", otherwise a fatal exception will be thrown.

The flag "FLAG_ACTIVITY_SINGLE_TOP" is intended to bring your MainActivity to the fore, and you can continue to do what is required of you by overriding the onNewIntent method in MainActivity.

 @Override protected void onNewIntent(Intent intent) { // continue with your work here } 
+1
source

Do this inside the onReceive method:

 Intent activityIntent = new Intent(this, MainActivity.class); activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(activityIntent); 

You may need to customize the addFlags call for your specific needs!

0
source

All Articles