我正在编写一个检查外部存储状态的应用。为了监视状态,我使用BroadcastReceiver并且我注意到,onReceive被多次调用(例如:3x用于卸载,1x用于mount)用于一个事件(例如:拔掉usb)。
这是我的代码:
public class MainActivity extends ActionBarActivity {
final static String TAG = "BroadcastReceiverDemo";
private IntentFilter filter;
private BroadcastReceiver receiver;
private void registerReceiver() {
filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
filter.addAction(Intent.ACTION_MEDIA_SHARED);
filter.addDataScheme("file");
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String broadcast;
String state = Environment.getExternalStorageState();
Log.d(TAG, "State: " + state);
if (Environment.MEDIA_MOUNTED.equals(state) && !Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
broadcast = "External storage aviable";
} else {
broadcast = "External storage NOT aviable";
}
String msg = intent.getAction() + " received broadcast: " + broadcast;
Log.d(TAG, msg);
}
};
this.registerReceiver(receiver, filter);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver();
}
@Override
protected void finalize() throws Throwable {
if (receiver != null) {
this.unregisterReceiver(receiver);
}
super.finalize();
}
}
问:为什么onReceive被调用了这么多次以及如何只调用一次?
感谢您的帮助。