温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-10-18 12:00:44 来源:脚本之家 阅读:155 作者:lqh 栏目:移动开发

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 已卸载!"); 
 } 
 } 
} 

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI