首先,有几个与此类似的问题包含了很多有用的知识:question1 和 question2。也许你的问题甚至与这些相似。
最简单的方法是在你的MyOwnJobIntentService extends JobIntentService
中获取JobIntentService的作业队列。
在androidx.core.app.JobIntentService.java
中,存在以下内容:
final ArrayList<CompatWorkItem> mCompatQueue;
在你的 MyOwnJobIntentService extends JobIntentService
中:
if(mCompatQueue.isEmpty()){
}
可惜的是mCompatQueue
不是公共字段。
10分钟后,我们找到了一个可行的解决方案-使用SingleJobIntentService
,它是一种JobIntentService,如果已经在运行,则不会排队作业。
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.JobIntentService;
import android.util.Log;
public class SingleJobIntentService extends JobIntentService {
private static final String TAG = "SingleJobIntentService";
private Intent theOnlyJobIhave = null;
public static void enqueue(Context context, Intent work) {
Log.d(TAG, "enqueue: someone tries to add me work " + work.hashCode());
JobIntentService.enqueueWork(
context,
SingleJobIntentService.class,
SingleJobIntentService.class.hashCode(),
work);
}
@Override
protected void onHandleWork(@NonNull final Intent theWorkIgot) {
Log.d(TAG, "onHandleWork: " + this.hashCode());
if (theOnlyJobIhave == null) {
theOnlyJobIhave = theWorkIgot;
final int extraValue = theOnlyJobIhave.getIntExtra(MainActivity.KEY, -500);
Log.d(TAG, "onHandleWork: " + extraValue);
try {
Thread.sleep(7000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
Log.d(TAG, "onHandleWork I'm already busy, refuse to work >:(");
}
Log.d(TAG, "onHandleWork end");
}
}
您可以通过简单的按钮活动来测试它:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends AppCompatActivity {
public static final String KEY = "KEYKEY";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button).setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
final Intent theIntent = new Intent();
theIntent.putExtra(KEY, 666);
SingleJobIntentService.enqueue(MainActivity.this, theIntent);
}
});
}
}
注意:你必须小心使用线程,因为我提供的解决方案不是线程安全的。例如,在androidx.core.app.JobIntentService.java
中触摸mCompatQueue
是同步的。 编辑:经过思考——>由于onHandleWork
从单个线程中调用JobIntentService,所以没有线程问题,解决方案是线程安全的!
enqueueWork
内部,我们检查列表中是否包含新的任务,如果包含,则不进行enqueueWork
(例如,我们可以为意图添加1个属性来检查是否包含)。在onHandleWork
中,当任务完成后,我们将其从待处理意图列表中移除。 - Linh