如何通过BroadcastReciver把应用从后台前台 [英] How to bring application from background to foreground via BroadcastReciver

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

问题描述

我有两个班这是MainActivity和MyBroadcastReceiver。广播接收器检测手机屏幕是否打开或关闭。我的愿望是,每当屏幕锁被释放启动我的申请。我的意思是我要带上我的应用程序到前台时,手机锁版本。

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

这是我的广播接收器:

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?

先谢谢了。

推荐答案

不要在你的广播接收器的方法的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
}

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

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