返回顶部

收藏

动态注册BroadcastReceiver

更多
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");
            }

        }    

    }    
}
//该片段来自于http://outofmemory.cn

标签:java,手机开发

收藏

0人收藏

支持

0

反对

0

发表评论