【问题标题】:Communicate from Service to Activity via bound service通过绑定服务从 Service 到 Activity 通信
【发布时间】:2012-08-15 18:59:09
【问题描述】:

我已经按照本教程将活动绑定到我的服务。 http://developer.android.com/guide/components/bound-services.html

我可以调用服务功能,但是如果我想更改我的一些文本视图或禁用一些切换按钮,因为在服务上(和从服务)完成的工作。有没有简单的方法可以做到这一点?

【问题讨论】:

  • 我可能正在考虑在主要活动中创建一个静态类并调用各种函数。这会有效吗?

标签: java android service android-activity


【解决方案1】:

您可以使用消息在活动和服务之间发送信息。这是发送简单数据的一种简单方法,但如果您需要非常频繁地发送数据或发送复杂数据,则可能不是最佳选择。这是我的一个应用程序中的一些代码示例,其中包含一个服务和一个通信活动:

活动中的代码:

//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();
    }
};



服务中的代码: 在服务中,您需要有代码(与活动中的代码非常相似)来接收消息并将msg.replyTo 字段保存为Messenger 对象。有一个例子可以让你创建一个对象,然后像这样使用 IncomingHandler:

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);
        }
    }
}

这可以让您的服务一次跟踪多个客户端并将消息发送到指定的客户端。要发送消息,只需使用以下内容:

mClients.get(1).send(Message.obtain(null, 3, new Random().nextInt(), 0));
//sends a message to the first client saved in the list

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 2014-01-02
    • 1970-01-01
    • 2017-10-30
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多