从广播接收器开始活动接收器

2023-09-06 17:09:32 作者:转身,却未离开

我得为Android以下情形:我有一个应用程序,启动时启动的服务。该服务检查的URL每次30分钟。如果它获得特定的响应,它发送的广播哪些应用程序接收并处理。这种情况对我来说是伟大的工作。

我也想用户已经停止运行该应用程序后,我的服务继续运行(应用了前景。),我得工作,以及

这是我现在面临的问题是,的当活动收到广播消息,我无法搬回前台的活动。我试过意图的各种组合,但还没有计算出来。我在做什么错了?

我的BroadcastReceiver code是这样的:

 私人广播接收器广播接收器=新的广播接收器(){    @覆盖    公共无效的onReceive(上下文的背景下,意图意图){        launchApp();    }};私人无效launchApp(){    意图vukaniActivity =新意图(这一点,Vukani.class);    //我试过多种不同的标志无济于事。    vukaniActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);    startActivity(vukaniActivity);} 

解决方案 网络114

您想要的标志是:

  vukaniActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK                       | Intent.FLAG_ACTIVITY_CLEAR_TOP                       | Intent.FLAG_ACTIVITY_SINGLE_TOP); 

此外,还要确保你在UI线程运行。

  runOnUiThread(新的Runnable(){  @覆盖  公共无效的run(){    launchApp();  }}); 

I've got the following scenario for Android: I have an app that when launched starts a service. That service checks a url every 30 minutes. If it gets a specific response, it sends a Broadcast which the app receives and processes. That scenario is working great for me.

I'd also like my service to continue running after the user has stopped running the application (app out of foreground.) Which I've got working as well.

The problem that I'm facing is that when the Activity receives the Broadcast message, I can't get the Activity to move back to the foreground. I've tried various combinations of intents, but haven't figured it out. What am I doing wrong?

My BroadcastReceiver code looks like this:

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        launchApp();
    }
};

private void launchApp() {
    Intent vukaniActivity = new Intent(this, Vukani.class);

    // I've tried multiple different flags to no avail.
    vukaniActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(vukaniActivity);
}

解决方案

The flags you want are:

vukaniActivity.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK
                       | Intent.FLAG_ACTIVITY_CLEAR_TOP
                       | Intent.FLAG_ACTIVITY_SINGLE_TOP);

Also, make sure you're running on the UI Thread.

runOnUiThread(new Runnable(){
  @Override
  public void run(){
    launchApp();
  }
});

 
精彩推荐
图片推荐