当前位置: 移动技术网 > 移动技术>移动开发>Android > Android 注册广播的两种方式对比

Android 注册广播的两种方式对比

2019年07月24日  | 移动技术网移动技术  | 我要评论

android 注册广播的两种方式对比

 1.常驻型广播

  常驻型广播,当你的应用程序关闭了,如果有广播信息来,你写的广播接收器同样的能接受到,

  他的注册方式就是在你的应用程序中的androidmanifast.xml进行注册。通常说这种方式是静态注册

  下面是配置例子

 <!-- 桌面 --> 
<receiver android:name=".widget.deskwidgeweather"> 
<meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_weather_provider" /> 
<intent-filter> 
 <action android:name="android.appwidget.action.appwidget_update"/> 
 <action android:name="action_weather"/> 
</intent-filter> 
lt;/receiver> 

  2.非常驻型广播

   当应用程序结束了,广播自然就没有了,比如你在activity中的oncreate或者onresume中注册广播接收器

   在ondestory中卸载广播接收器。这样你的广播接收器就一个非常驻型的了。这种也叫动态注册。

   比如写一个监听sdcard状态的广播接收器

sdcardstatechanagereceiver sdcardstatereceiver; 
@override 
protected void oncreate(bundle savedinstancestate) 
{ 
 super.oncreate(savedinstancestate); 
 intentfilter filter = new intentfilter(); 
 filter.addaction(intent.action_media_removed); 
 filter.addaction(intent.action_media_eject); 
 filter.addaction(intent.action_media_mounted); 
 filter.adddatascheme("file"); 
 sdcardstatereceiver = new sdcardstatechanagereceiver();  
 registerreceiver(sdcardstatereceiver,filter); 
} 
@override 
protected void ondestroy(){ 
 unregisterreceiver(sdcardstatereceiver); 
} 
class sdcardstatechanagereceiver extends broadcastreceiver{ 
 
 @override 
 public void onreceive(context context, intent intent) 
 { 
 string state=android.os.environment.getexternalstoragestate(); 
 system.out.println("sdcard 发生改变! 状态:"+state); 
 //checksdcard(); 
 } 
 public void checksdcard(){ 
 string state=android.os.environment.getexternalstoragestate(); 
 system.out.println(state); 
 if(state.equals(android.os.environment.media_removed ) || state .equals(android.os.environment.media_unmounted)){ 
  system.out.println("sdcard 已卸载!"); 
 } 
 } 
} 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网