[英]Stop thread, not extending class
我一直在寻找这里给出的一些答案,但是我没有确切解决我的问题的方法:我不想创建一个新类并扩展可运行或线程。
我有一项服务,该服务在创建时必须每10秒检查一些内容,并且无法从主线程完成所需的调用,因此onStartCommand()方法将执行以下操作:
mThread = new Thread() {
public void run() {
while(true) {
// some code
try {
Thread.sleep(10000);
}
catch (Exception e){
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
Log.i("Exception", errors.toString());
}
}
现在,当我调用onStopService()时,我想停止该线程。 不建议使用stop()方法,因此我正在使用interrupt():
@Override
public void onDestroy(){
mDelete.interrupt();
mDownload.interrupt();
super.onDestroy();
}
如我所料,它会引发InterruptedException,因为调用中断时线程正在休眠。
有没有什么方法可以在不创建新类的情况下停止线程,并从可运行或线程扩展?
提前致谢
如您在这里看到的,您可以在线程内使用以下代码:
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// We've been interrupted, and returning from the run method will stop your thread.
return;
}
但是,通常最好避免无限循环服务。 您应该考虑在工作完成后停止服务,并在需要进行新工作时重新启动服务(使用AlarmManager
)。 我不会重复使用IntentService
和AlarmManager
的代码,因为Eugen Pechanec给了您很好的解释。
1)从IntentService
扩展您的服务。
此类服务用于短粒度操作,它在后台线程上运行,因此您可以访问网络。 在方法onHandleIntent(Intent)
而不是onStartCommand(Intent, int, int)
。
2)使用AlarmManager
安排此服务(以下代码将在活动中工作)。
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(this, Service.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
long nowElapsed = SystemClock.elapsedRealtime();
long tenMinutes = 10 * 60 * 1000;
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, nowElapsed, tenMinutes, pi);
注意单词“ inexact”。 这意味着间隔将不完全是600000毫秒。 更节能。
PendingIntent.FLAG_CANCEL_CURRENT
标志用于正确的重新计划。
3)当您不再需要PendingIntent
时,请取消它。 此后,您的服务将不会自动运行,直到您再次启用它。
Intent i = new Intent(this, Service.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, PendingIntent.FLAG_NO_CREATE);
if (pi != null) pi.cancel;
有关使用警报的更多信息: https : //developer.android.com/training/scheduling/alarms.html
有关IntentService
更多信息: http : //developer.android.com/reference/android/app/IntentService.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.