通过广播检测sdcard插拔操作


public class TestSdcard extends Activity {

@Override
protected void onDestroy() {
super.onDestroy();
//退出的时候需要取消广播接收
this.unregisterReceiver(in);
}

DetectSdcard in;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
in = new DetectSdcard();
IntentFilter intentf = new IntentFilter();
intentf.addAction(Intent.ACTION_MEDIA_MOUNTED);
intentf.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
//隐式intent需要加上下面这句作匹配,否则接收不到广播
intentf.addDataScheme("file");
this.registerReceiver(in, intentf);
}

// 检测sdcard是否在机器中
public class DetectSdcard extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED))
{
//挂载的...
}
else if(intent.getAction().equals(Intent.ACTION_MEDIA_UNMOUNTED))
{
//非挂载...
}
}

}


}

你可能感兴趣的:(其他相关,Android,Tips,Android)