Android 中的一项服务多项活动

Eli*_*ior 5 service android android-activity

我有一项服务和 3 项活动。该服务在第一个活动中启动。现在,当我转到第二个活动并按下某个按钮时,我想向服务发送数据。

因此,在第二个活动中,在单击侦听器中,我执行了以下操作:

 Intent service = new Intent(MyService.class.getName()); 
 service.putExtra("dataToSend",data.toString());
 startService(service);
Run Code Online (Sandbox Code Playgroud)

但是服务中的onStartCommand方法没有被调用..

此外,我想创建此服务以处理多个活动。我的意思是每个活动都能够向该服务发送数据并从中获取数据。

Aru*_*ney 5

嗨,您需要将正在运行的服务绑定到您需要再次访问它的活动。以下代码片段可以用作参考

@Override
protected void onStart() {
    super.onStart();
    Intent mIntent = new Intent(this, MyService.class);
    bindService(mIntent, mConnection, BIND_AUTO_CREATE);
};

ServiceConnection mConnection = new ServiceConnection() {

    public void onServiceDisconnected(ComponentName name) {
        mBounded = false;
        myService= null;
    }

    public void onServiceConnected(ComponentName name, IBinder service) {
        // Toast.makeText(context, "Service is connected", 1000).show();

        mBounded = true;
        LocalBinder mLocalBinder = (LocalBinder) service;
        myService= mLocalBinder.getServerInstance();

      //now you are able to access any method in service class 
    }
};
Run Code Online (Sandbox Code Playgroud)


Jor*_*lla 3

问题
我想创建此服务来处理多个活动。我的意思是每个活动都能够向该服务发送数据并从中获取数据。

您不必对您的Service. 如果服务没有被破坏,那么它们将保持不变,这意味着您的所有人都Activities将能够访问其数据

问题

但服务内的 onStartCommand 方法不会被调用。

为什么
只要您的服务已启动,就onStartCommand不会每次都调用:

onStartCommand

每次客户端通过调用startService (Intent)显式启动服务时由系统调用,并提供它提供的参数和表示启动请求的唯一整数标记。

startService

请求启动给定的应用程序服务。

解决方案
在方法中调用您需要的事件onRebind

当新客户端连接到服务时调用,之前已在其 onUnbind(Intent) 中通知所有客户端已断开连接。仅当 onUnbind(Intent) 的实现被重写以返回 true 时才会调用此函数。