如何将应用程序中的活动上下文传递给其他应用程序中的服务

mat*_*zin 6 service android android-context

所以我在启动服务的应用程序中有一个活动:

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");
        } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
            if (mDevice != null && mDevice.equals(device)) {
                setDevice(null);
                Log.i(TAG, "usb NO conectado");
            }
        }
Run Code Online (Sandbox Code Playgroud)

parent将是启动服务的活动.这种方法之前的工作原理是因为代码曾经在同一个应用程序中,但现在我希望它是一个服务,以便其他应用程序可以连接到它.

有没有办法将活动的上下文传递给服务?我阅读了很多关于意图和捆绑,可分割和序列化的内容,但它们都不适用于我.我需要传递上下文.

有任何想法吗?

Sam*_*Sam 9

每个服务都有自己的上下文,只需使用它.您不需要传递服务和活动的上下文.

我不明白为什么你需要一个特定的Activity的Context来调用getSystemService(),一个Service会像任何Activity一样从BroadcastReceiver接收Intent.

此外,如果在此服务运行时销毁原始活动,则上下文将无效或活动将被泄露.