我正在使用LocalBroadcastManager使用APPLICATION CONTEXT向我的活动和服务广播,如下所示:
public class CommonForApp extends Application{
public void broadcastUpdateUICommand(String[] updateFlags,
String[] flagValues) {
Intent intent = new Intent(UPDATE_UI_BROADCAST);
for (int i = 0; i < updateFlags.length; i++) {
intent.putExtra(updateFlags[i], flagValues[i]);
}
mLocalBroadcastManager = LocalBroadcastManager.getInstance(mContext);
mLocalBroadcastManager.sendBroadcast(intent);
}}
现在在我的服务中使用监听器,我正在调用broadcastUpdateUICommand(),如下所示:
public class mService extends Service {
public BuildNowPLaylistListListener buildCursorListener = new BuildNowPLaylistListListener() {
@Override
public void onServiceListReady() {
mApp.broadcastUpdateUICommand(
new String[] { CommonForApp.INIT_DRAWER},
new String[] {""});
}}}
我在我的活动中接收广播,如下:
public class mActivity extends Activity{
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
mtoast.showtext("in onreceive"); //toast to check
if (intent.hasExtra(CommonForApp.INIT_DRAWER))
initialiseDrawer();
}};
}
mApp是Application的实例。 CommonForApp是我的应用程序类。
但在我的活动中,我没有收到任何广播(广播经理使用应用程序上下文初始化)。
有人可以建议我为什么我的活动没有收到广播? ..
。提前谢谢!
答案 0 :(得分:6)
活动:
protected BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, final Intent intent) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if(intent.hasExtra("type")){
// Do some action
}
}
});
}
};
@Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("data-loaded"));
}
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
}
然后你发送广播:
public static void sendBroadcastMessageDataLoaded(Context context, String dataType){
Intent intent = new Intent("data-loaded");
intent.putExtra("type", dataType);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}