注册广播的两种方式

静态注册:

当你的应用程序关闭了,如果有广播信息来,你写的广播接收器同样的能接收到,在应用程序的AndroidManifast.xml 中进行注册。示例代码如下:

<pre name="code" class="html"><receiver android:name=". ShortMessageReceiver" 
    android:enabled="true"> 
    <intent-filter> 
        <!--  指定可以接收的 Broadcast Action  --> 
        <action android:name="android.provider.Telephony.SMS_RECEIVED"/> 
    </intent-filter> 
</receiver> 

 

动态注册:

当应用程序结束了,广播自然就没有了,比如在 Activity 中的 onCreate 或者 onResume 中注册广播接收者,在 onDestory 中注销广播接收者。这种方式可以理解为通过代码注册的广播是和注册者关联在一起的。比如监听 SDcard 状态的广播接收者,示例代码ruxi

package cn.sunzn.mosecurity.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;

public class SDcard extends Activity {
   SdcardStateChanageReceiver sdcardStateReceiver;

   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       sdcardStateReceiver = new SdcardStateChanageReceiver();
       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");
       registerReceiver(sdcardStateReceiver, filter);
   }

   protected void onDestroy() {
       unregisterReceiver(sdcardStateReceiver);
   }

   class SdcardStateChanageReceiver extends BroadcastReceiver {
       public void onReceive(Context context, Intent intent) {
           checkSDCard();
       }

       public void checkSDCard() {
           String state = Environment.getExternalStorageState();
           System.out.println(state);
           if (state.equals(Environment.MEDIA_REMOVED) || state.equals(Environment.MEDIA_UNMOUNTED)) {
               System.out.println("SDCard 已卸载!");
           }
       }
   }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值