Android 四大组件Broadcast

广播

广播作用:接受其他进程发送的消息
广播分为发送者和接受者
发送者有两种注册方式:动态注册,xml文件注册,也是静态注册
接受者(BroadcastReceiver):自定义一个类继承android.content.BroadcastReceiver 类,重写onReceive()获取传递过来的参数

直接在AndroidManifest.xml文件中进行注册。规则如下:

   android:permission  
   android:process=":CIA" //进程broadcastReceiver运行所处的进程。默认为app的进程。可以指定独立的进程(Android四大基本组件都可以通过此属性指定自己的独立进程
   android:exported="true"—//此broadcastReceiver能否接收其他App的发出的广播,这个属性默认值有点意思,其默认值是由receiver中有无intent-filter决定的,如果有intent-filter,默认值为true,否则为false。
  <receiver android:name=".BroadcastReceiver" >
   <intent-filter>
     <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
   intent-filter>
   <intent-filter>
     <action android:name="android.intent.action.BOOT_COMPLETED" />
   intent-filter>
   receiver>

动态注册

public class BroadcastActivity extends Activity {

    private  String BROADCAST_ACTION ="WER";
    private  BroadcastReceiver mBroadcasrReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

       //动态注册
        mBroadcasrReceiver = new BroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(RESTRICTIONS_SERVICE);
        registerReceiver(mBroadcasrReceiver, intentFilter);

        //广播的发送
        Intent intent = new Intent();
        intent.setAction(BROADCAST_ACTION);
        intent.putExtra("name","ni hao a ");
        sendBroadcast(intent);
    }
 }

你可能感兴趣的:(Android)