gpt4 book ai didi

android - JobSchedule 和静态匿名 AsyncTask

转载 作者:行者123 更新时间:2023-11-30 00:01:26 26 4
gpt4 key购买 nike

我正在学习如何在 Android 中结合使用 JobScheduleAsyncTasks。按照一些指南,我有以下 JobService 实现:

@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;
}
}

在我的 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);
}
}

我在 JobService-class 中收到可能发生泄漏的警告:

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.

问题是,即使我转到 MainActivity2,我也希望 Task 继续。

是否像我一样调用jobFinished?还是更需要避免内存泄漏?

最佳答案

当您创建一个非静态内部类时,它持有对包含类的引用。在您的情况下 WaitTask 是内部匿名类,它可能比您的 TaskJobService 存在时间更长,因为 WaitTask 隐式引用了您的服务类。这将防止您的 TaskJobService 被垃圾收集,从而导致内存泄漏。

解决方案是创建静态嵌套类或直接使用顶级类。

关于android - JobSchedule 和静态匿名 AsyncTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49846227/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com