How to prevent Context leak in AsyncTask used by JobService

San*_*der 5 android android-asynctask firebase-job-dispatcher

I need to do some background work which requires a Context in a JobService (I'm using the Firebase JobDispatcher one because we support api 16+) I've read a lot of articles about the JobService and AsyncTasks but I'm unable to find any good articles on how to combine them if you need a Context.

My JobService

import com.firebase.jobdispatcher.JobParameters;
import com.firebase.jobdispatcher.JobService;

public class AsyncJobService extends JobService {

    @Override
    public boolean onStartJob(JobParameters job) {
        new AsyncWork(this, job).execute();
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters job) {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

My AsyncTask

import android.os.AsyncTask;
import com.firebase.jobdispatcher.JobParameters;
import com.firebase.jobdispatcher.JobService;

class AsyncWork extends AsyncTask<Void, Void, Void> {

    private JobService jobService;

    private JobParameters job;

    AsyncWork(JobService jobService, JobParameters job) {
        this.jobService = jobService;
        this.job = job;
    }

    @Override
    protected Void doInBackground(Void... voids) {
        // some work that needs context
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        // some work that needs context
        jobService.jobFinished(job, false);
    }
}
Run Code Online (Sandbox Code Playgroud)

This gives a warning that the jobService property in the AsyncWork class is leaking a context object. I understand why this is the case if you pass an Activity or Fragment but this is a JobService which should exist untill I call jobFinished(). Am I doing something wrong or can I ignore the warning?

G. *_*ike 1

您不能忽略该警告。因为AsyncWork保存了对 的引用Context,所以Context在任务完成之前无法对 进行 GC:Context内存泄漏。有两种解决方案:

  1. 使用长期存在的上下文,无论如何,应用程序上下文。
  2. 将异步任务的生命周期与其保存引用的上下文的生命周期联系起来:取消它onPause

  • 1.我无法使用应用程序上下文,因为我需要在onPostExecuted()中调用jobFinished()函数来释放唤醒锁。2. 据我所知,asynctask 与 JobService 的生命周期相关,因为我在 JobService 的 onStartJob() 中返回 true,并在 onPostExecute() 末尾调用 jobFinished()。JobService 中没有 onPause(),即使警告仍然存在,在 onStopJob() 中调用 cancel() 是否可以 100% 防止泄漏? (2认同)