我终于找到了要走的路。我在清单中添加了一个新的接收器:
<receiver android:name=".content.UsbReceiver">
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<meta-data
android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="@xml/device_filter" />
</receiver>
它以这种方式处理事件:
public class UsbReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (!CustomApplication.resumed) {
Context applicationContext = context.getApplicationContext();
Intent startIntent = new Intent(applicationContext, MyActivity.class);
startIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
applicationContext.startActivity(startIntent);
}
}
}
我的自定义类resumed
中的静态字段在哪里:Application
public class CustomApplication extends Application {
public static boolean resumed = false;
}
我在所有活动的父类中设置了该字段的值:
public abstract class AbstractActivity extends Activity {
@Override
protected void onResume() {
super.onResume();
CustomApplication.resumed = true;
}
@Override
protected void onPause() {
CustomApplication.resumed = false;
super.onPause();
}
}
通过这种方式,只有在我的所有活动都没有在前台时,我才会真正启动 MyActivity。