Issue
I am learning how to use JobSchedule
in Android in combination with AsyncTasks
. Following some guides I have the following JobService
implementation:
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
public class TaskJobService extends JobService {
private WaitTask mWaitTask = null;
@Override
public boolean onStartJob(final JobParameters params) {
mWaitTask = new WaitTask(){
@Override
protected void onPostExecute(Boolean result){
super.onPostExecute(result);
jobFinished(params, !result);
}
};
mWaitTask.execute();
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
if (mWaitTask != null){
mWaitTask.cancel(true);
}
return true;
}
}
and in my MainActivity:
public class MainActivity extends AppCompatActivity {
int JOB_ID = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// WaitTask waitTask = new WaitTask();
// waitTask.execute();
ComponentName componentName = new ComponentName(this, TaskJobService.class);
JobScheduler jobScheduler = (JobScheduler)getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(new JobInfo.Builder(JOB_ID,componentName).setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).build());
}
public void startMain2(View v){
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
}
}
I get the warning in my JobService-class
that leaks might occur:
This AsyncTask class should be static or leaks might occur
A static field will leak contexts. Non-static inner classes have an implicit reference to their outer class. If that outer class is for example a Fragment or Activity, then this reference means that the long-running handler/loader/task will hold a reference to the activity which prevents it from getting garbage collected. Similarly, direct field references to activities and fragments from these longer running instances can cause leaks. ViewModel classes should never point to Views or non-application Contexts.
The thing is that I want to Task
to continue even though I go to MainActivity2
.
Is it enough to call jobFinished
as I do? Or is more needed to avoid memory leaks?
Solution
When you create a non-static inner class, it holds a reference to containing class. In your case WaitTask
is inner anonymous class which might live longer than your TaskJobService
since WaitTask
has implicit reference to your service class. This will prevent your TaskJobService
from being garbage collected which would lead to memory leak.
The solution would be to either create a static nested class or use top-level class directly.
Answered By - Sagar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.