如何通过BroadcastReceiver将应用程序从后台带到前台 [英] How to bring application from background to foreground via BroadcastReceiver

查看:206
本文介绍了如何通过BroadcastReceiver将应用程序从后台带到前台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类,分别是MainActivity和MyBroadcastReceiver。 BroadcastReceiver检测电话屏幕是打开还是关闭。我的愿望是在释放屏幕锁时启动我的应用程序。我的意思是我想在释放手机锁时将我的应用程序放在首位。

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.

这是我的活动类别:

 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);
    }
}

这是我的广播接收器:

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?

推荐答案

在BroadcastReceiver的onReceive方法中执行以下操作

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);
}

您的意图需要标记 FLAG_ACTIVITY_NEW_TASK,否则将导致致命事故引发异常。


标志 FLAG_ACTIVITY_SINGLE_TOP将MainActivity带到最前面,您可以通过重写MainActivity中的onNewIntent方法来继续执行您想做的事情。

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
}

这篇关于如何通过BroadcastReceiver将应用程序从后台带到前台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆