So, I have activity in the application that starts the service:
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()");
}
}
The action starts as follows:
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
The service then registers and connects to this user USB device. To do this, he needs an activity context:
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");
}
}
parent will be the activity that starts the service. This approach was used because this code was used in one application, but now I want it to be a service so that other applications can connect to it.
Is there a way to pass an activity context to a service? I read a lot about intentions and bundles, disassembled and serialized, but none of this works for me. I need to convey context.
Any ideas?
source
share