为什么我的广播接收器不工作?我做错了什么以及如何解决?
有类似的问题:
Broadcast Receivers not working in Android 6.0 Marshmallow
Android Broadcast receiver for call not working? (Marshmallow)
这些问题与运行时权限问题有关。在我的情况下,它不是权限问题(我猜),因为我没有使用任何权限相关的服务。我只是想创建一个简单的广播接收器 - 发送消息并将消息显示为Toast。
min SDK:21
最大SDK:25
测试设备:注4(N910U)运行6.0.1
清单
<receiver android:name="package.MyBroadcastReceiver">
<intent-filter>
<action
android:name="MyBroadcastReceiver">
</action>
</intent-filter>
</receiver>
MyBroadcastReceiver
public class MyBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "foo";
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, intent.getExtras().getString("mgs"), Toast.LENGTH_LONG).show();
}
}
MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btnSend;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//MyBroadcastReceiver br = new MyBroadcastReceiver();
//IntentFilter intentFilter = new IntentFilter();
//intentFilter.addAction("MyBroadcastReceiver");
//registerReceiver(br, intentFilter); // local BR
btnSend = (Button) findViewById(R.id.btn_send);
btnSend.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:
Intent intent = new Intent();
intent.setAction("MyBroadcastReceiver");
intent.putExtra("mgs","Just a test message");
this.sendBroadcast(intent);
break;
}
}
}