目标:当SD卡拔出时,返回首页,栈中的activity都要清楚,只留下首页的activity
我在清单中注册了一个静态广播:
<receiver android:name="com.panocean.kepler.application.UsbBroadCastReceiver" >
<intent-filter android:priority="1000" >
<action android:name="android.intent.action.MEDIA_MOUNTED" />
<action android:name="android.intent.action.MEDIA_EJECT" />
<data android:scheme="file" />
</intent-filter>
</receiver>
public class UsbBroadCastReceiver extends BroadcastReceiver {
public UsbBroadCastReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
Toast.makeText(context, "SD卡异常", Toast.LENGTH_LONG).show();
Intent intent2 = new Intent(context, FileExplorerActivity.class);
intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent2);
}
}
}
当sd卡拔出时,系统发出广播,我注册的BroadCastReceiver会接收到这个广播,
做出处理。intent设置flag,系统要求flag必须要有Intent.FLAG_ACTIVITY_NEW_TASK,
否则会报错。Intent.FLAG_ACTIVITY_CLEAR_TOP清除栈中所有activity,重新绘制首页
activity;