android 广播详解与实例(Broad Receiver)

      

  • 系统全局广播

       以下3个例子属于系统全局广播,是一种可以跨进程的通信方式,从自己的应用程序发出的广播,其他的应用程序也是可以收到的。


一、接收系统广播(接收系统网络状态变化广播,需要在AndroidManifest.xml添加权限)

public void networkChangeReceiver()
{
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //ConnectivityManager是一个系统服务类,专门用于管理网络连接
                    ConnectivityManager connectivityManager = (ConnectivityManager)
                            getSystemService(Context.CONNECTIVITY_SERVICE);//获取ConnectivityManager实例
                    //获取NetworkInfo实例
                    assert connectivityManager != null;
                    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                    if (networkInfo != null && networkInfo.isAvailable()) {
                        Toast.makeText(MainActivity.this, "network is available", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(MainActivity.this, "network is unavailable", Toast.LENGTH_LONG).show();

                    }
                }
            });

        }
    };

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
    registerReceiver(broadcastReceiver, intentFilter);
}

二、发送自定义标准广播标准广播异步执行,所有广播器接收到广播信息,但无法被截断

     1. 创建MyBroadcastReceiver类


public class MyBroadcastReceiver extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO 自动生成的方法存根
		Toast.makeText(MyApplication.getContext(), 
				"received in mybroadcastReceiver", Toast.LENGTH_LONG).show();
	}


}

     2. 在AndroidManifestexml对广播接收器进行修改

   
    ...
             android:name="com.example.BroadcastReceiver.MyBroadcastReceiver"
            android:enabled="true"
            android:exported="true">
           
               
           

       
   


      3. 在activity里发送广播(可利用Intent传送数据)

        Intent intent = new Intent("com.example.BroadcastReceiver.MY_BROADCAST");
        sendBroadcast(intent);


三、发送自定义有序广播标准广播同步执行,广播器接收广播信息有先后顺序,优先级搞定广播接收器可截断信息


     1. 在AndroidManifestexml对广播接收器进行修改


     
      ...
                        android:name="com.example.BroadcastReceiver.MyBroadcastReceiver"
              android:enabled="true"
              android:exported="true">
              //把 MyBroadcastReceiver的优先级设成100,优先级高的广播接收器先收到广播
              android:priority="100">  
                 
             

         
     


      2. 在activity里发送广播


        Intent intent = new Intent("com.example.BroadcastReceiver.MY_BROADCAST");
        //用 sendOrderedBroadcast就发送有序广播
        sendOrderedBroadcast(intent,null);  //第一个参数是Intent,第二个参数是一个与权限相关的字符串

     3. 修改MyBroadcastReceiver类

public class MyBroadcastReceiver extends BroadcastReceiver{

        @Override
         public void onReceive(Context context, Intent intent) {
                 // TODO 自动生成的方法存根
                Toast.makeText(MyApplication.getContext(), "received in mybroadcastReceiver", Toast.LENGTH_LONG).show();
                 abortBroadcast();   //用abortBroadcast();将广播截断
}

}


  • 本地广播
      只能在应用程序内部传递的广播,安全性高(LocalBroadcastManager)。

例子:
       本地广播注册与接收的函数:
/**
	 * 本地广播
	 */
		public void LocalBroadcastReceiver()
		{
			localReceiver = new BroadcastReceiver()
			{
				@Override
				public void onReceive(Context context, Intent intent)
				{
					runOnUiThread(new Runnable()
					{			
						@Override
						public void run()
						{
							Toast.makeText(MyApplication.getContext(), "received local broadcast", Toast.LENGTH_LONG).show();
						}
					});
					
				}
			};
			
			IntentFilter intentFilter = new IntentFilter();
			intentFilter.addAction("com.example.BroadcastReceiver.MY_BROADCAST");
			localBroadcastManager.registerReceiver(localReceiver, intentFilter);
		}

       函数的应用:
empty

       取消注册:
/**
 * 销毁activity		
 */
	@Override
	protected void onDestroy(){
		super.onDestroy();
//		if(broadcastReceiver != null){
//			unregisterReceiver(broadcastReceiver);//取消注册广播
//		}
		localBroadcastManager.unregisterReceiver(localReceiver);//取消注册本地广播
		
	}














你可能感兴趣的:(android,开发笔记)