How to bring application from background to foreground via BroadcastReceiver

狂风中的少年 提交于 2019-12-08 01:38:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!