猿问

为什么不能弹出提醒信息

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"?

道可道非常道
浏览 1763回答 1
1回答

FINE_Android

难道你没有发现Intent intent = new Intent("com.example.broadcasttest.LOCAL_BROADCAST")和intentFilter.addAction("com.example.broadcasttest.LOCAL-BROADCAST")这两句话中的字符串不一样么?我跑了你的代码,-和_的问题,一般而言,需要用一个字符串作为成员变量表示,就是防止写错
随时随地看视频慕课网APP

相关分类

Android
Java
我要回答