简体   繁体   English

停止线程,不扩展类

[英]Stop thread, not extending class

I've been looking around some anwers given here but i don't get exactly the solution to my problem: I don't want to create a new class and extends runnable or thread. 我一直在寻找这里给出的一些答案,但是我没有确切解决我的问题的方法:我不想创建一个新类并扩展可运行或线程。

I have a service that when created must check every 10 secs some stuff and the calls needed can't be done from the main thread, so onStartCommand() method I do the following: 我有一项服务,该服务在创建时必须每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());
                    }
                }

Now, when i call onStopService() i want to stop this thread. 现在,当我调用onStopService()时,我想停止该线程。 The method stop() is deprecated so I'm using interrupt(): 不建议使用stop()方法,因此我正在使用interrupt():

@Override
public void onDestroy(){
    mDelete.interrupt();
    mDownload.interrupt();
    super.onDestroy();
}

As I expected, it throws InterruptedException because the thread is sleeping when calling interrupt. 如我所料,它会引发InterruptedException,因为调用中断时线程正在休眠。

Is there any way to stop the thread without creating a new class and extend from runnable or thread? 有没有什么方法可以在不创建新类的情况下停止线程,并从可运行或线程扩展?

Thanks in advance 提前致谢

As you can see here , you can use this code inside your thread: 如您在这里看到的,您可以在线程内使用以下代码:

try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        // We've been interrupted, and returning from the run method will stop your thread.
        return;
    }

However, in general it is better avoid infinite loop service. 但是,通常最好避免无限循环服务。 You should consider to stop your service when the work is done, and restart it (using an AlarmManager ) when a new work is required. 您应该考虑在工作完成后停止服务,并在需要进行新工作时重新启动服务(使用AlarmManager )。 I will not repeat the code for use IntentService and AlarmManager , since Eugen Pechanec has given you a good explanation. 我不会重复使用IntentServiceAlarmManager的代码,因为Eugen Pechanec给了您很好的解释。

1) Extend your service from IntentService . 1)从IntentService扩展您的服务。

This type of service is used for short granular operations and it runs on a background thread so you can access network. 此类服务用于短粒度操作,它在后台线程上运行,因此您可以访问网络。 Do your work in method onHandleIntent(Intent) instead of onStartCommand(Intent, int, int) . 在方法onHandleIntent(Intent)而不是onStartCommand(Intent, int, int)

2) Schedule this service using AlarmManager (the following code will work in an activity). 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);

Notice the word "inexact". 注意单词“ inexact”。 That means that the interval won't be exactly 600000 milliseconds. 这意味着间隔将不完全是600000毫秒。 It is more energy effective. 更节能。

The PendingIntent.FLAG_CANCEL_CURRENT flag is for proper rescheduling. PendingIntent.FLAG_CANCEL_CURRENT标志用于正确的重新计划。

3) Cancel the PendingIntent when you don't need it anymore. 3)当您不再需要PendingIntent时,请取消它。 After this your service will not run automatically until you enable it again. 此后,您的服务将不会自动运行,直到您再次启用它。

Intent i = new Intent(this, Service.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, PendingIntent.FLAG_NO_CREATE);
if (pi != null) pi.cancel;

More about using alarms: https://developer.android.com/training/scheduling/alarms.html 有关使用警报的更多信息: https : //developer.android.com/training/scheduling/alarms.html

More about IntentService : http://developer.android.com/reference/android/app/IntentService.html 有关IntentService更多信息: http : //developer.android.com/reference/android/app/IntentService.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM