【问题标题】:How to bring application from background to foreground via BroadcastReceiver如何通过 BroadcastReceiver 将应用程序从后台带到前台
【发布时间】:2013-06-11 14:50:18
【问题描述】:

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

这是我的活动课:

 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

        }
    }
}

我应该怎么做才能在我的广播接收器中执行这个操作?

【问题讨论】:

    标签: android broadcastreceiver intentfilter powermanager


    【解决方案1】:
    【解决方案2】:

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

    @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 方法从那里继续做任何您想做的事情。

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

    【讨论】:

    • 您好,我是新的 android 和 xamarin,我的应用程序有同样的问题,我想在接听电话时打开应用程序。我不知道我需要在“com.your.package”、“com.your.package.MainActivity”中给出什么,你能帮帮我吗?我需要在清单中设置什么?
    • 查看您的 manifest.xml 文件并查找
    【解决方案3】:

    在您的 onReceive 方法中执行此操作:

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

    您可能需要根据您的特定需求调整 addFlags 调用!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多