简单的问题,是否可以通过send/receive
在同一个班级中LocalBroadcastReceiver
进行意图?如果是,你能告诉我一个例子吗?
答案 0 :(得分:2)
是的,LocalBroadcastReceiver无处不在。以下是Activity
的示例:
BroadcastReceiver localBroadcastReciever = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
Log.d("BroadcastReceiver", "Message received " + intent.getAction());
}
};
@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);
}
某处,无论是在同一个Activity
还是应用程序的其他位置(无所谓):
final LocalBroadcastManager localBroadcastManager =
LocalBroadcastManager.getInstance(context);
localBroadcastManager.sendBroadcast(new Intent("com.my.package.intent.ACTION_NAME_HERE"));
当然,您可以使用intent.putExtra
添加任何其他数据或使用多个操作来区分广播消息。