Android:如何在onBind()之前强制调用onStartCommand()?

pst*_*cki 7 android android-service

我正在尝试创建一个可绑定的粘性服务(我需要在后台运行服务所持有的某些数据的异步操作).为此,我需要确保onBind始终在onStartCommand之后运行.有什么方法可以保证吗?

Mau*_*ker 8

根据您的要求,您可能不需要绑定到您的Service.然后使用一个IntentService就足够了,因为这项服务将在完成工作后自行停止.

取自文档:

IntentService是服务的基类,可根据需要处理异步请求(表示为Intents).客户端通过startService(Intent)调用发送请求; 根据需要启动服务,使用工作线程依次处理每个Intent,并在工作失败时自行停止.

一个例子IntentService:

public class MyService extends IntentService {

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            // Do some work here, get Intent extras if any, etc.
            // ...
            // Once this method ends, the IntentService will stop itself.
        }
    }   
}
Run Code Online (Sandbox Code Playgroud)

关于如何创建更多信息IntentService,可以发现在这里.

这可以处理您的异步操作.如果您需要任何反馈,这将"打破"需求的异步部分,您可以使用LocalBroadcastManager或如您所说,您可以绑定到此Service.然后,这取决于你想要做什么.

从文档中,您有两种类型的服务.

入门

当应用程序组件(例如活动)通过调用startService()启动它时,服务"启动".一旦启动,服务可以无限期地在后台运行,即使启动它的组件被销毁.通常,已启动的服务执行单个操作,并且不会将结果返回给调用者.例如,它可能通过网络下载或上载文件.操作完成后,服务应自行停止.

当应用程序组件通过调用bindService()绑定到它时,服务被"绑定".绑定服务提供客户端 - 服务器接口,允许组件与服务交互,发送请求,获取结果,甚至跨进程间通信(IPC)进行交互.只要绑定了另一个应用程序组件,绑定服务就会运行.多个组件可以立即绑定到服务,但是当所有组件解除绑定时,服务将被销毁.

提醒:您可以启动一个Service直通startService()"无限期"运行并通过onBind()稍后调用绑定到它.

Intent it = new Intent(this, MyService.class);
startService(it); // Start the service.
bindService(it, this, 0); // Bind to it.
Run Code Online (Sandbox Code Playgroud)

如果您只想在运行时运行此服务,Activity则可以直接调用onBind().

Intent it = new Intent(this, MyService.class);
bindService(it, this, 0); // This will create the service and bind to it.
Run Code Online (Sandbox Code Playgroud)

有关"默认"的更多信息Service,如何使用它并实现它可以在这里找到.

只需选择最适合您用例的方法,就可以了.


ver*_*loc 0

根据文档

服务本质上可以采用两种形式:

已启动
当应用程序组件(例如活动)通过调用 startService() 启动服务时,服务即被“启动”。
绑定
当应用程序组件通过调用bindService() 与服务绑定时,服务就被“绑定”了。[..] 绑定服务仅在另一个应用程序组件绑定到它时才运行。多个组件可以同时绑定到服务,但是当所有组件都解除绑定时,服务就会被销毁。

为了确保onStartCommand()始终在 before 之前执行onBind(),请在您想要绑定到服务时随时向该服务发送新意图。这是因为对服务的任何新意图都会触发 onStartCommand(),然后调用bindService()将执行onBind().

  • 问题是,当我调用“startService()”,然后几乎立即调用“bindService()”时,Android 有时会在“onStartCommand()”之前安排“onBind()”。 (2认同)