从Intentservcie回调到JobService [英] Callback to jobservice from intentservcie

查看:94
本文介绍了从Intentservcie回调到JobService的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JobScheduler,它触发Jobservice的onStartjob.在onStartJob中,我启动了一个intentservice来完成这项工作.工作完成后,我希望intentservice对jobservice进行回调,以便可以调用onjobfinished.我该如何回调JobService?

I have a jobscheduler that triggers onStartjob of Jobservice. In onStartJob, I start an intentservice to do the work. After the work is done, I want intentservice to do a callback to jobservice so that onjobfinished can be called. How can I do a callback to JobService?

推荐答案

您可以使用某些ACTION常量(例如ACTION_DOWNLOAD_FINISHED)创建BroadcastReceiver并将其注册到Jobservice中的onStartJob()方法中.该接收方会将所有工作委托给onJobFinished()方法:

You can create BroadcastReceiver and register it in your Jobservice, in onStartJob() method, using some ACTION constant (for example ACTION_DOWNLOAD_FINISHED). This receiver will delegate all work to onJobFinished() method:

public static final String ACTION_DOWLOAD_FINISHED = "actionDownloadFinished";

private BroadcastReceiver downloadFinishedReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) { 
        context.unregisterReceiver(this); //Unregister receiver to avoid receiver leaks exception
        onJobFinished();
    }
};

public void onStartJob() {
    IntentFilter filter = new IntentFilter(ACTION_DOWNLOAD_FINISHED);        
    //Use LocalBroadcastManager to catch the intents only from your app
    LocalBroadcastManager.getInstance(this).registerReceiver(downloadFinishedReceiver , filter);

    //other job starting stuff...
}

然后,在意图服务终止其工作之后,您可以通过其中的ACTION_DOWNLOAD_FINISHED操作发送广播意图:

Then, after the intent service has ended it's work, you can send broadcasting intent with ACTION_DOWNLOAD_FINISHED action from it:

// ...downloading stuff
Intent downloadFinishedIntent = new Intent(Jobservice.ACTION_DOWNLOAD_FINISHED);
//Use LocalBroadcastManager to broadcast intent only within your app
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

当意图服务的作业完成时,它将发送由注册在Jobservice中的接收方捕获的广播意图.然后Receiver调用onJobFinished()方法.

When the job of the intent service is finished, it sends broadcasting intent that is catched by the receiver registered in the Jobservice. Receiver then invokes the onJobFinished() method.

您可以在此处找到详细信息: https://developer .android.com/training/run-background-service/report-status.html

You can find the details there: https://developer.android.com/training/run-background-service/report-status.html

这篇关于从Intentservcie回调到JobService的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆