(1)系统广播(电量,新的照片,新的应用等等)
(2)自定义广播
AndroidManifest.xml
8.0限制静态注册(因为耗电)
静态注册系统广播 8.0+无法使用
<receiver android:name=".myBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.PACKAGE_ADDED" />
<action android:name="android.intent.action.PACKAGE_REMOVED" />
<data android:scheme="package" />
intent-filter>
receiver>
public class myBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("xxx","msg:");
if (intent!=null){
//接受的是什么广播
String action =intent.getAction();
Log.d("xxx","msg:"+action);
}
}
}
动态注册系统广播
public class myBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("xxx","msg:");
if (intent!=null){
//接受的是什么广播
String action =intent.getAction();
Log.d("xxx","msg:"+action);
}
}
}
myBroadcastReceiver myBroadcastReceiver1=new myBroadcastReceiver();
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
intentFilter.addDataScheme("package");
registerReceiver(myBroadcastReceiver1,intentFilter);
(1)onReceive() 耗时操作开线程去操作
(2)执行线程 --主线程
(3)执行限制时间 不然会anr(应用无响应) 不能做耗时操作
注册广播
@Override
protected void onStart() {
super.onStart();
IntentFilter filter=new IntentFilter("xxx");
LocalBroadcastManager
.getInstance(this)
.registerReceiver(mReceiver,filter);
}
接收方
private final BroadcastReceiver mReceiver =new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("xxx")){
final String status=intent.getStringExtra("status");
Toast
.makeText(MainActivity.this,status,Toast.LENGTH_SHORT)
.show();
}
}
};
发送方
public void onClick(View view) {
Log.d("qwe","xxx");
Intent intent=new Intent();
intent.setAction("xxx");
intent.putExtra("status","msg");
LocalBroadcastManager
.getInstance(MainActivity.this)
.sendBroadcast(intent);
}