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

前端之家收集整理的这篇文章主要介绍了Android:如何在onBind()之前强制调用onStartCommand()?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试创建一个可绑定的粘性服务(我需要在后台运行服务所持有的某些数据的异步操作).为此,我需要确保onBind始终在onStartCommand之后运行.有什么方法可以保证吗?

解决方法

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

取自文档:

IntentService is a base class for Services that handle asynchronous
requests (expressed as Intents) on demand. Clients send requests
through startService(Intent) calls; the service is started as needed,
handles each Intent in turn using a worker thread,and stops itself
when it runs out of work.

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.
        }
    }   
}

有关如何创建IntentService的更多信息,请参见here.

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

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

入门

A service is “started” when an application component (such as an
activity) starts it by calling startService(). Once started,a service
can run in the background indefinitely,even if the component that
started it is destroyed. Usually,a started service performs a single
operation and does not return a result to the caller. For example,it
might download or upload a file over the network. When the operation
is done,the service should stop itself.

A service is “bound” when an application component binds to it by
calling bindService(). A bound service offers a client-server
interface that allows components to interact with the service,send
requests,get results,and even do so across processes with
interprocess communication (IPC). A bound service runs only as long as
another application component is bound to it. Multiple components can
bind to the service at once,but when all of them unbind,the service
is destroyed.

提醒:您可以通过startService()启动服务以使其“无限期”运行并通过稍后调用onBind()绑定到它.

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

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

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

有关“默认”服务的更多信息,如何使用它并实现它可以在here找到.

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

猜你在找的Android相关文章