android中如何發送一個廣播


1.首先要聲明廣播

 

[java]  view plain  copy
  1. private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver()  
  2. {  
  3.     @Override  
  4.     public void onReceive(Context context, Intent intent) //onReceive函數不能做耗時的事情,參考值:10s以內  
  5.     {  
  6.         Log.d("scott", "on receive action="+intent.getAction());  
  7.         String action = intent.getAction();  
  8.         if (action.equals("com.scott.sayhi"))  
  9.         {  
  10.             showDialog("on receive action="+intent.getAction());  
  11.         }  
  12.     }  
  13. };  

 

 

2.其次要注冊廣播,有兩種方式:xml注冊和代碼注冊

 

xml注冊:

<receiver Android:name="com.scott.sayhi.MyBroadcastReceiver" >
<intent-filter>
<action android:name="com.scott.sayhi" />
</intent-filter>
</receiver>

 

代碼注冊:

IntentFilter filter = new IntentFilter();
filter.addAction("com.scott.sayhi");
MyActivity.this.registerReceiver(mBroadcastReceiver, filter);

上述2個步驟就可以了。

 

3.發送廣播

 

[java]  view plain  copy
  1. Intent intent = new Intent();  
  2. intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  3. intent.setAction("com.scott.sayhi");  
  4. MyActivity.this.sendBroadcast(intent);  

 

 

4.收聽開機廣播

intent-filter設置如下即可

<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM