问题
I have two classes which are MainActivity and MyBroadcastReceiver. BroadcastReceiver detects whether phone screen is on or off. My desire is to launch my application whenever screen lock is released. I mean that I want to bring my application to the front when phone lock releases.
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 am I supposed to do in order to perform this operation in my broadcast receiver?
回答1:
Try to use FLAG_ACTIVITY_REORDER_TO_FRONT or FLAG_ACTIVITY_SINGLE_TOP
回答2:
Do the following in your onReceive method of the 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);
}
You need the flag "FLAG_ACTIVITY_NEW_TASK" for your intent otherwise there will be a fatal exception being thrown.
The flag "FLAG_ACTIVITY_SINGLE_TOP" is to bring your MainActivity to the front and you can proceed to do whatever you want from there by overriding the onNewIntent method in MainActivity.
@Override
protected void onNewIntent(Intent intent) {
// continue with your work here
}
回答3:
Do this inside your onReceive method:
Intent activityIntent = new Intent(this, MainActivity.class);
activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(activityIntent);
You might need to tweak the addFlags call for your specific needs!
来源:https://stackoverflow.com/questions/17047127/how-to-bring-application-from-background-to-foreground-via-broadcastreceiver