Android如何接收外部broadcast

给出一个接收SD插拔的广播demo,相信依样画葫芦可以成功。

创建一个内部广播接收类

private SdcardStateChanageReceiver 
sdcardStateReceiver
 
;

在onCreate加入你感兴趣的事件:

IntentFilter filter = new IntentFilter(); 
filter.addAction(Intent. ACTION_MEDIA_REMOVED );
filter.addAction(Intent. ACTION_MEDIA_EJECT );//SD卡弹出 
filter.addAction(Intent. ACTION_MEDIA_MOUNTED ); 
filter.addDataScheme( "file" );
sdcardStateReceiver = new SdcardStateChanageReceiver();  
registerReceiver( sdcardStateReceiver ,filter);//注册广播

onDestroy里记得取消注册。

unregisterReceiver( 
sdcardStateReceiver 
);

以下才是对外部广播事件的真正处理

class SdcardStateChanageReceiver extends BroadcastReceiver{ 
             
             @Override
             public void onReceive(Context context, Intent intent) {
                   // TODO Auto-generated method stub
                  String action = intent.getAction();
              if (action.equals(Intent. ACTION_MEDIA_EJECT)){
                  Log. i( TAG, "sd removed" );
                  //SD卡移除处理语句
              } else if (action.equals(Intent. ACTION_MEDIA_MOUNTED)){
                   System.out.println("ACTION_MEDIA_MOUNTED");
              }
                  
            }
      }

 

    原文作者:缥缈孤鸿影_love
    原文地址: https://blog.csdn.net/tung214/article/details/24024829
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞