したがって、サービスを開始するアプリケーションにアクティビティがあります。
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()");
}
}
このアクティビティは、次の目的で開始されます。
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
次に、サービスはロギングを実行し、このカスタム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");
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
if (mDevice != null && mDevice.equals(device)) {
setDevice(null);
Log.i(TAG, "usb NO conectado");
}
}
親は、サービスを開始するアクティビティになります。このアプローチは、以前は同じアプリケーションにコードが含まれていたため機能していましたが、他のアプリケーションが接続できるように、サービスにしたいと考えています。
アクティビティのコンテキストをサービスに渡す方法はありますか?インテントとバンドル、パーセル可能とシリアル化についてたくさん読みましたが、どれもうまくいきません。コンテキストを渡す必要があります。
何か案は?