Communicate from Service to Activity via bound ser

2019-04-10 22:20发布

I've already bound an activity to my service following this tutorial. http://developer.android.com/guide/components/bound-services.html

I'm able to call service functions, but what if I want to for example, change some of my textviews or disable some of the toggle buttons because of work done on the service (and from the service). Would there be an easy to way to do this?

1条回答
欢心
2楼-- · 2019-04-10 22:47

You can use messages to send information between activities and services. This is an easy way to send simple data, but may not be the best option if you need to send data very frequently, or send complicated data. This is an example of some code I have in one of my apps with a service and an activity which communicate:

Code in the activity:

//this is where you set what you want to happen
class IncomingHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            //this switch reads the information in the message (usually just 
            //an integer) and will do something depending on which integer is sent
            case 1: do_something();
            case 2: do_something_2(); //etc.
            default:
                super.handleMessage(msg);
        }
    }
}

final Messenger myMessenger = new Messenger(new IncomingHandler());

private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className,
            IBinder service) {
        myService = new Messenger(service);
        myCallbackText = (TextView)findViewById(R.id.tv01); //This is a text view which will display status information as needed
        myCallbackText.setText("Attached.");

        try {
            Message msg = Message.obtain(null,
                    1);
            msg.replyTo = mMessenger; //here we send an instance of our messenger implementation as the replyTo address
            mService.send(msg);

            msg = Message.obtain(null,
                    3, this.hashCode(), 0);
            mService.send(msg); //send a message with the value "3"
        } catch (RemoteException e) {
          //nothing you can do if the server isn't active
        }

        Toast.makeText(Service_testActivity.this, R.string.remote_service_connected,
                Toast.LENGTH_SHORT).show();//confirmation that the connection happened successfully
    }

    public void onServiceDisconnected(ComponentName className) {
        // This is called when the connection with the service has been
        // unexpectedly disconnected -- that is, its process crashed.
        mService = null;
        mCallbackText = (TextView)findViewById(R.id.tv01);//same textview as before
        mCallbackText.setText("Disconnected.");

        Toast.makeText(Service_testActivity.this, R.string.remote_service_disconnected,
                Toast.LENGTH_SHORT).show();
    }
};



Code in the service: In the service, you will want to have code (very similar to the code in the activity) to receive a message and save the msg.replyTo field as a Messenger object. There is an example somewhere which will have you make an object and then use an IncomingHandler like this:

ArrayList<Messenger> mClients = new ArrayList<Messenger>();
class IncomingHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_REGISTER_CLIENT:
                mClients.add(msg.replyTo);
                break;
            case MSG_UNREGISTER_CLIENT:
                mClients.remove(msg.replyTo);
                break;
            default:
                super.handleMessage(msg);
        }
    }
}

This can allow your service to keep track of multiple clients at once and send messages to specified clients. To send a message simply use something like this:

mClients.get(1).send(Message.obtain(null, 3, new Random().nextInt(), 0));
//sends a message to the first client saved in the list
查看更多
登录 后发表回答