Android Broadcast广播机制

1、写一个Broadcast广播类
   利用button按钮的监听器来进行广播,在监听方法中的onClick中添加Intent对象进行广播。
       onClick(View v){
             Intent intent = new Intent();
             intent.setAction(Intent.ACTION_EDIT);
             当前类.this.setBroadcast(intent);
       }

2、在AndroidManifest.xml中进行注册【无论应用程序开还是关,都能接受广播,始终处于活动                                   状态】  例如:监听电池的耗电量
 
   <receiver android:name=".接受广播的类">
       <intent-filter>
            <action android:name="android:intent.action.EDIT"/>
       </intent-filter>
   </receiver>

   有时需要加上Android的版本
   <user-sdk android:minSdkVersion="7"></user-sdk>

3、写一个接受Broadcast的类TestReceiver extends BroadcastReceiver{
                  //写构造方法
                  public TestReceiver(){
                      System.out.println("TestReceiver"); 
                  }
               
                   //override onReceive方法
                   public void onReceiver(Context context,Intent intent){
                   System.out.println("onReceive");
                   }
               }

....................................................................................
                                深入了解Broadcast
------------------------------------------------------------------------------------
1、更新UI,那么在应用程序中注册。在Activity启动时注册BroadcastReceiver,在Activity
   不可见以后取消注册
 
   //注册BroastcastReceiver
   registerReceiver(receiver,filter);

   //取消注册BroadcastReceiver
   unregisterReceiver(receiver);

相关推荐