应用程序停止后 BroadcastReceiver 不工作

BroadcastReceiver doesn't work after app stops

我有一个前台服务使用 intent 和动作上传图像和广播状态 "myAction"。

我的应用程序需要对广播做出反应,例如在收到成功消息后发送服务器请求或在收到失败消息后弹出通知。我正在关注这个 https://developer.android.com/training/run-background-service/report-status.html

Sending an broadcast Intent doesn't start or resume an Activity. The BroadcastReceiver for an Activity receives and processes Intent objects even when your app is in the background, but doesn't force your app to the foreground. If you want to notify the user about an event that happened in the background while your app was not visible, use a Notification. Never start an Activity in response to an incoming broadcast Intent.

我首先尝试在清单中静态注册我的广播接收器。它不起作用。然后,我按照此说明 Keep broadcast receiver running after application is closed 启动服务来注册我的广播接收器。当我滑出或关闭 app.To 时,两者都不起作用(没有日志显示),我可以看到 "HAHAHAHA" 和 "HEHEHEHE" 日志在前台时出现。从应用列表中将其滑出或单击返回退出应用后,它不会出现。

这是我的代码。我错过了哪里?

在我的清单中

<application...>
  <receiver android:name=".MyBroadcastReceiver"
      android:enabled="true"
      android:exported="false">
    <intent-filter android:priority="0">
      <action android:name="myAction"/>
    </intent-filter>
  </receiver>
  <service
      android:name=".MyService"
      android:exported="false"/>
</application>

MyBroadcastReceive.java

public class MyBroadcastReceiver extends BroadcastReceiver{
  @Override
  public void onReceive(Context context, Intent intent) {
    Log.d("HAHAHAHA", "Broadcast received.");
  }
}

MyService.java

public class MyService extends Service {
  BroadcastReceiver mReceiver;

  // use this as an inner class like here or as a top-level class
  public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
      // do something
      Log.d("HEHEHEHE", "Broadcast received.");
    }
  }

  @Override
  public void onCreate() {
    // get an instance of the receiver in your service
    IntentFilter filter = new IntentFilter();
    filter.addAction("myAction");
    mReceiver = new MyReceiver();
    registerReceiver(mReceiver, filter);
  }

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }


  @Override
  public void onDestroy() {
    Log.d("HEHEHEHE", "onDestroy");
    super.onDestroy();
  }
}

MainActivity.java

onStart() {
  Intent intent = new Intent(this, MyService.class);
  startService(intent);
}

广播调用如下:

LocalBroadcastManager.getInstance(service).sendBroadcast(intent);

I first try to register my broadcast receiver statically in Manifest. It doesn't work.

您不能将清单注册接收器与 LocalBroadcastManager 一起使用。只有通过 LocalBroadcastManager.getInstance().registerReceiver() 注册的接收者才会响应本地广播。

My app needs to react on the broadcast, like send a server request after receiving success message or pop up a notification after receiving failure message.

摆脱广播并在服务中完成这项工作。