Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an activity context in an application to a service in an other application

So I have an activity in an application that starts a 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 activity is launched by the following intent:

<intent-filter>
            <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
        </intent-filter>

The service then does the logging and connects with this custom usb device. In order to do that, it needs the 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 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.

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.

Any ideas?

like image 253
matiaslezin Avatar asked Sep 20 '12 21:09

matiaslezin


1 Answers

Every Service has its own Context, just use that. You don't need to pass a Service an Activity's Context.

I don't see why you need a specific Activity's Context to call getSystemService() and a Service will receive Intents from a BroadcastReceiver as readily as any Activity.

Also, if the originating Activity is destroyed while this Service is running, the Context will be invalid or the Activity will be leaked.

like image 148
Sam Avatar answered Nov 01 '22 12:11

Sam