所以我在启动服务的应用程序中有一个活动:
private void startService() {
if (started) {
Toast.makeText(Main.this, "Service already started",
Toast.LENGTH_SHORT).show();
} else {
Intent i = new Intent();
i.setClassName("com.enorbitas.daemon.service",
"com.enorbitas.daemon.service.DaemonService");
startService(i);
started = true;
updateServiceStatus();
Log.d(getClass().getSimpleName(), "startService()");
}
}
Run Code Online (Sandbox Code Playgroud)
该活动由以下意图启动:
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
Run Code Online (Sandbox Code Playgroud)
然后,该服务执行日志记录并与此自定义USB设备连接.为此,它需要活动上下文:
mUsbManager = (UsbManager) parent.getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while(deviceIterator.hasNext()){
UsbDevice device = deviceIterator.next();
}
Intent intent = parent.getIntent();
String action = intent.getAction();
UsbDevice device = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
setDevice(device);
Log.i(TAG, "usb conectado");
} …Run Code Online (Sandbox Code Playgroud)