public class MainActivity extends Activity { private IntentFilter intentFilter; private LocalReceiver localReceiver; private LocalBroadcastManager localBroadcastManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); localBroadcastManager = LocalBroadcastManager.getInstance(this);//获取实例 Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent("com.example.broadcasttest.LOCAL_BROADCAST"); localBroadcastManager.sendBroadcast(intent);//发送本地广播 } }); intentFilter = new IntentFilter(); intentFilter.addAction("com.example.broadcasttest.LOCAL-BROADCAST"); localReceiver = new LocalReceiver(); localBroadcastManager.registerReceiver(localReceiver, intentFilter); //注册本地广播器 } @Override protected void onDestroy() { super.onDestroy(); localBroadcastManager.unregisterReceiver(localReceiver); } class LocalReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "received local broadcast", Toast.LENGTH_SHORT).show(); } }}请问上面代码哪里有问题?为什么点击按钮之后没有弹出提示文本"received local broadcast"?
1 回答
已采纳
FINE_Android
TA贡献24条经验 获得超6个赞
难道你没有发现Intent intent = new Intent("com.example.broadcasttest.LOCAL_BROADCAST")和intentFilter.addAction("com.example.broadcasttest.LOCAL-BROADCAST")这两句话中的字符串不一样么?我跑了你的代码,-和_的问题,一般而言,需要用一个字符串作为成员变量表示,就是防止写错
添加回答
举报
0/150
提交
取消