android 8.0 移除静态大部分注册广播
官方地址
动态注册广播,然后发送广播
效果
MainActivity.java (注册广播,和注册点击事件)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyReceiver myReceiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.MY_RECEIVER");
registerReceiver(myReceiver,filter);
}
// 发送广播
public void send(View view) {
Intent intent = new Intent("android.intent.action.MY_RECEIVER");
intent.putExtra("broadcastmsg","你好,世界");
sendBroadcast(intent);
}
MyReceiver.java(接受并弹出吐司)
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String strMsg = intent.getStringExtra("broadcastmsg");
Toast.makeText(context, strMsg, Toast.LENGTH_SHORT).show();
Log.i("MyReceiver","接受到了");
}
}
发送有序广播
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 2. 动态注册
MyReceiver myReceiver = new MyReceiver();
MyReceiver2 myReceiver2 = new MyReceiver2();
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.MY_RECEIVER");
registerReceiver(myReceiver, filter);
registerReceiver(myReceiver2, filter);
}
// 发送广播
public void send(View view) {
Intent intent = new Intent(action);
intent.putExtra("broadcastmsg", "你好,世界");
sendOrderedBroadcast(intent, null);
}
MyReciver1.java
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("MyReceiver","接受到了1");
abortBroadcast(); // 禁止向下广播
}
}
MyReciver2.java
public class MyReceiver2 extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
Log.i("MyReceiver2","接受到了2");
}
}
解除注册:
unregisterReceiver(receiver);
未解决事件
动态设置广播优先级