Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to pass an activity context in an application to a service in an other application
    primarykey
    data
    text
    <p>So I have an activity in an application that starts a service:</p> <pre><code>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()"); } } </code></pre> <p>The activity is launched by the following intent:</p> <pre><code>&lt;intent-filter&gt; &lt;action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" /&gt; &lt;/intent-filter&gt; </code></pre> <p>The service then does the logging and connects with this custom usb device. In order to do that, it needs the activity context:</p> <pre><code> mUsbManager = (UsbManager) parent.getSystemService(Context.USB_SERVICE); HashMap&lt;String, UsbDevice&gt; deviceList = mUsbManager.getDeviceList(); Iterator&lt;UsbDevice&gt; 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 &amp;&amp; mDevice.equals(device)) { setDevice(null); Log.i(TAG, "usb NO conectado"); } } </code></pre> <p>parent would be the activity that starts the service. This approach used to work because that code used to be in the same application, but now I want it to be a service so that others applications can connect to it.</p> <p>Is there a way to pass the context of the activity to the service? I read a lot about intents and bundles, parcelable and serialization, but none of it works for me. I need to pass the context.</p> <p>Any ideas? </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload