我有来自官方文档的 JobIntentService:
public class SimpleJobIntentService extends JobIntentService {
static final int JOB_ID = 1000;
static void enqueueWork(Context context, Intent work) {
enqueueWork(context, SimpleJobIntentService.class, JOB_ID, work);
}
@Override
protected void onHandleWork(Intent intent) {
// We have received work to do. The system or framework is already
// holding a wake lock for us at this point, so we can just go.
Log.i("SimpleJobIntentService", "Executing work: " + intent);
String label = intent.getStringExtra("label");
if (label == null) {
label = intent.toString();
}
toast("Executing: " + label);
for (int i = 0; i < 5; i++) {
Log.i("SimpleJobIntentService", "Running service " + (i + 1)
+ "/5 @ " + SystemClock.elapsedRealtime());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
Log.i("SimpleJobIntentService", "Completed service @ " + SystemClock.elapsedRealtime());
}
@Override
public void onDestroy() {
super.onDestroy();
toast("All work complete");
}
final Handler mHandler = new Handler();
// Helper for showing tests
void toast(final CharSequence text) {
mHandler.post(new Runnable() {
@Override public void run() {
Toast.makeText(SimpleJobIntentService.this, text, Toast.LENGTH_SHORT).show();
}
});
}
}
在运行此服务之前,调用后Thread.activeCount()
我得到了 33 号。结束第一次运行的服务后,我得到了 34,接下来是 35,依此类推。
为什么 ?有人可以解释一下吗?结束后如何杀死这个线程?这是 JobIntentService 的正常行为吗?IntentService 完美运行,结束后总是杀死一个线程。
我使用以下片段从片段启动此服务:
Intent intent = new Intent(getActivity(), SimpleJobIntentService.class);
SimpleJobIntentService.enqueueWork(getActivity(), intent);
无论如何,如果我以这种方式启动服务:
getActivity().startService(new Intent(getActivity(), SimpleJobIntentService.class));
JobIntentService 也没有删除线程