我更喜歡使用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
添加任何附加數據或使用多個操作來區分廣播消息。
我知道我可以在onPause/onResume中的服務中添加/刪除Activity的Handler,但我想知道是否有更好的API我錯過了 – alberthier 2013-03-14 15:46:50