我更喜欢使用LocalBroadcastManager
这是您的代码示例Activity
:
BroadcastReceiver localBroadcastReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
Log.d("BroadcastReceiver", "Message received " + intent.getAction());
Log.d("BroadcaseReceiver", "Received data " + intent.getStringExtra("com.my.package.intent.EXTRA_DATA"));
}
};
@Override
protected void onStart()
{
super.onStart();
final LocalBroadcastManager localBroadcastManager =
LocalBroadcastManager.getInstance(this);
final IntentFilter localFilter = new IntentFilter();
localFilter.addAction("com.my.package.intent.ACTION_NAME_HERE");
localBroadcastManager.registerReceiver(localBroadcastReceiver, localFilter);
}
@Override
protected void onStop()
{
super.onStop();
final LocalBroadcastManager localBroadcastManager =
LocalBroadcastManager.getInstance(this);
// Make sure to unregister!!
localBroadcastManager.unregisterReceiver(localBroadcastReceiver);
}
代码库中的任何其他地方(例如在后台线程的完成中):
final LocalBroadcastManager localBroadcastManager =
LocalBroadcastManager.getInstance(context);
final Intent intent = new Intent("com.my.package.intent.ACTION_NAME_HERE")
intent.putExtra("com.my.package.intent.EXTRA_DATA", yourBackgroundData);
localBroadcastManager.sendBroadcast(intent);
当然,您可以使用intent.putExtra
添加任何附加数据或使用多个操作来区分广播消息。