android 广播的使用(静态/动态注册/系统广播/自定义广播)

广播的类型

(1)系统广播(电量,新的照片,新的应用等等)
(2)自定义广播

1.静态注册系统广播

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);
        }
    }
}

2.动态注册系统广播

动态注册系统广播

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(应用无响应) 不能做耗时操作

3.自定义广播

注册广播

    @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);

            }

你可能感兴趣的:(android基础)