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