现在的位置: 首页 > 综合 > 正文

android监听sd卡挂载状态,onReceive无法被调用问题

2014年01月20日 ⁄ 综合 ⁄ 共 2078字 ⁄ 字号 评论关闭

MyExternalStorageReceiver

package com.rishiqing.receiver;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;

import com.rishiqing.activity.LuncherActivity;
import com.rishiqing.utils.LogUtil;

public class MyExternalStorageReceiver extends BroadcastReceiver {

	private static String TAG = MyExternalStorageReceiver.class.getName();
	private Context mContext;

	public MyExternalStorageReceiver(Context c) {
		LogUtil.e(TAG, "MyExternalStorageReceiver~~~~");
		this.mContext = c;
		IntentFilter intentFilter = new IntentFilter(
				Intent.ACTION_MEDIA_MOUNTED);
		intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
		intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
		intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
		intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
		intentFilter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
		mContext.registerReceiver(this, intentFilter);
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		LogUtil.e(TAG, "onReceive~~~~");
		ifSDStateFalse();
	}

	public void ifSDStateFalse() {
		AlertDialog mAlertDialog = null;
		// TODO Auto-generated method stub
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED) == true) {
			 mAlertDialog = new AlertDialog.Builder(mContext)
					.setMessage("系统未检测到sd卡,将强制退出").show();
			mAlertDialog.setOnDismissListener(new OnDismissListener() {
				@Override
				public void onDismiss(DialogInterface dialog) {
					Intent i = new Intent();
					i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					i.setClass(mContext, LuncherActivity.class);
					i.putExtra("isFinish", 1);
					mContext.startActivity(i);
				}
			});
		}
		else if(Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED) == true){
			if(mAlertDialog!=null && mAlertDialog.isShowing())
				mAlertDialog.dismiss();
		}
	}

	public void unregister() {
		Log.d(TAG, "unregister()");
		mContext.unregisterReceiver(this);
	}
}

以上代码看起来,感觉已经很完整了,但是onReceive怎么都无法被调用。

最后发现在intentFilter中加上了intentFilter.addDataScheme("file");这样才起作用(line 30)

【上篇】
【下篇】

抱歉!评论已关闭.