Chinaunix首页 | 论坛 | 博客
  • 博客访问: 386173
  • 博文数量: 284
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1707
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-14 16:38
文章分类

全部博文(284)

文章存档

2015年(6)

2014年(278)

我的朋友

分类: Android平台

2014-06-24 14:54:59

1. [代码][Java]代码     
package com.zjt.innerreceiver;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;

public class ServiceTest extends Service{

public final static String TAG = "ServiceTest";
private Receiver mReceiver;
@Override()
public IBinder onBind(Intent arg0) {
return null;
}

@Override
public void onCreate() {
super.onCreate();
//注册Receiver
mReceiver = new Receiver(this);  
mReceiver.registerActionAndScheme(Intent.ACTION_MEDIA_EJECT, "file"); 
mReceiver.registerActionAndScheme(Intent.ACTION_MEDIA_REMOVED, "file"); 
mReceiver.registerActionAndScheme(Intent.ACTION_MEDIA_MOUNTED, "file"); 
mReceiver.registerActionAndScheme(Intent.ACTION_PACKAGE_REMOVED, "package"); 
                mReceiver.registerActionAndScheme(Intent.ACTION_PACKAGE_ADDED, "package");
}
@Override
public void onDestroy() {
super.onDestroy();
//注销Receiver
unregisterReceiver(mReceiver);  
}



class Receiver extends BroadcastReceiver {    
        
Context mContext;    
  
        public Receiver(Context context){    
            mContext = context;    
        }    
            
        //动态注册  
        public void registerAction(String action){    
            IntentFilter filter = new IntentFilter();    
            filter.addAction(action);        
            mContext.registerReceiver(this, filter);    
        }  
        
        public void registerActionAndScheme(String action, String dataScheme){    
            IntentFilter filter = new IntentFilter();  
            filter.addAction(action);        
            filter.addDataScheme(dataScheme);
            mContext.registerReceiver(this, filter);    
        } 
            
        @Override    
        public void onReceive(Context context, Intent intent) {    
         String action = intent.getAction();
         Log.d(TAG, "action:" + action);
        
         if(action.equals(Intent.ACTION_MEDIA_EJECT)) {
         Log.d(TAG , "sdcard has been ejected");
         } else if (action.equals(Intent.ACTION_MEDIA_REMOVED)) {
         Log.d(TAG , "sdcard has been removed");
         } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
         Log.d(TAG , "sdcard has been mounted");
         } else if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) {
         Log.d(TAG, "Intent.ACTION_PACKAGE_REMOVED");
         } else if (action.equals(Intent.ACTION_PACKAGE_ADDED)) {
         Log.d(TAG, "Intent.ACTION_PACKAGE_ADDED");
         }
             
        }    
            
    }    
}
阅读(601) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~