Android: Getting a variable from my running servic

2019-07-15 17:50发布

问题:

My activity starts a Service, and when I close my app, the service continues to run. OK, that's right. But when I open my application again, in the activity, I need to know the value of a public variable defined on the running Service(class) that I've started previously.

How can I do that?

Thanks

回答1:

If you are binding your Activity to the Service, you should have an implementation of the Binder interface in your Service, e.g.

public class ServiceBinder extends Binder {
    public MyService getService() {
        return MyService.this;
    }
}

In your Activity, create a new ServiceConnection class which will be used to give you access to your Service:

private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
        mMyService = ((MyService.ServiceBinder)service).getService();
    }

    public void onServiceDisconnected(ComponentName className) {
        mMyService = null;
    }
};

Here the member variable mMyService will give you access to all public members of your Service class.

To create the connection, implement doBindService and doUnbindService in your Activity:

void doBindService() {
    bindService(new Intent(this, MyService.class), mConnection, Context.BIND_AUTO_CREATE);
}

void doUnbindService() {
    // Detach our existing connection.
    unbindService(mConnection);
}

Hope this helps!



回答2:

If you don't call unbindService, your activity still have connection to service and you can simply check the variable through the service's method.



回答3:

You could use messenger. As per android website

A messenger is reference to a Handler, which others can use to send messages to it. This allows for the implementation of message-based communication across processes, by creating a Messenger pointing to a Handler in one process, and handing that Messenger to another process.