Why is my broadcast receiver not working? What did I do wrong and how to solve?
There are similar questions:
Broadcast Receivers not working in Android 6.0 Marshmallow
Android Broadcast receiver for call not working? (Marshmallow)
These questions are related to runtime permission issue. In my case, it is not permission issue (I guess), because I am not using any permission related service. I just want to create a simple Broadcast Receiver - sending a message and showing the message as Toast.
min SDK : 21
max SDK : 25
test device : Note 4 (N910U) running 6.0.1
Manifest
<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;
}
}
}