如果您只有 2 个可能处理您的广播的对象(在您的情况下是一个 Activity 和一个通知控制器),您可以仅使用 LocalBroadcastManager 实现有序广播的行为。
总体思路是:
- 设置您的服务,以便在您想要显示结果时通过特定操作向您的 Activity 广播 Intent
- 在您的 Activity 中创建一个处理您的服务结果 Intent 的 BroadcastReceiver,并使用步骤 1 中的操作在 LocalBroadcastManager 上使用 IntentFilter 注册它
- 在您的服务中,当结果可用时,尝试使用 LocalBroadcastManager.getInstance(Context).sendBroadcast(Intent) 发送结果 Intent,此方法返回一个布尔值,指示广播是否已发送到至少一个接收器。如果此布尔值为 false,则表示您的 Activity 没有处理您的广播,您应该改为显示通知。
在您的服务中:
public UnzipService extends IntentService {
public static final String ACTION_SHOWRESULT = UnzipService.class.getCanonicalName() + ".ACTION_SHOWRESULT";
@Override
protected void onHandleIntent(Intent intent) {
Thread.sleep(500); // Do the hard work
// Then try to notify the Activity about the results
Intent activityIntent = new Intent(this, YourActivity.class);
activityIntent.setAction(ACTION_SHOWRESULT);
activityIntent.putExtra(SOME_KEY, SOME_RESULTVALUE); // Put the result into extras
boolean broadcastEnqueued = LocalBroadcastManager.getInstance(this).sendBroadcast(activityIntent);
if (!broadcastEnqueued) { // Fallback to notification!
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE))
.notify(SOME_ID, new NotificationCompat.Builder(this)
.setContentIntent(pendingIntent)
.setTicker("results available")
.setContentText("results")
.build());
}
}
}
在您的活动中:
public YourActivity extends Activity {
private BroadcastReceiver resultReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
processResult(intent); // Results Intent received through local broadcast
}
}
private IntentFilter resultFilter = new IntentFilter(UnzipService.ACTION_SHOWRESULT);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate();
Intent intent = getIntent();
if (UnzipService.ACTION_SHOWRESULT.equals(intent.getAction())) {
// The Activity has been launched with a tap on the notification
processResult(intent); // Results Intent contained in the notification PendingIntent
}
}
@Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this)
.registerReceiver(resultReceiver, resultFilter);
}
@Override
protected void onPause() {
LocalBroadcastManager.getInstance(this)
.unregisterReceiver(resultReceiver);
super.onPause();
}
private void processResult(Intent intent) {
// Show the results from Intent extras
}
}
这应该是一个完整的工作示例。
我希望这对尝试使用支持库中的 LocalBroadcastManager 实现有序广播的人有所帮助!