Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/187.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 停止线程,不扩展类_Java_Android_Multithreading - Fatal编程技术网

Java 停止线程,不扩展类

Java 停止线程,不扩展类,java,android,multithreading,Java,Android,Multithreading,我一直在寻找这里给出的一些答案,但我没有找到问题的确切解决方案:我不想创建一个新类并扩展runnable或thread 我有一个服务,创建时必须每10秒检查一次某些内容,并且无法从主线程执行所需的调用,因此onStartCommand()方法我执行以下操作: mThread = new Thread() { public void run() { while(true) { // some code

我一直在寻找这里给出的一些答案,但我没有找到问题的确切解决方案:我不想创建一个新类并扩展runnable或thread

我有一个服务,创建时必须每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():

正如我所预料的,它抛出InterruptedException,因为调用中断时线程正在休眠

有没有办法在不创建新类和从runnable或thread扩展的情况下停止线程

提前感谢

1)从
IntentService
扩展您的服务

这种类型的服务用于短粒度操作,它在后台线程上运行,所以您可以访问网络。使用方法
onHandleIntent(Intent)
而不是
onStartCommand(Intent,int,int)

2) 使用
AlarmManager
计划此服务(以下代码将在活动中起作用)

注意“不精确”这个词。这意味着时间间隔不会精确到600000毫秒。它更节能

pendingent.FLAG\u CANCEL\u CURRENT
标志用于正确重新安排

3) 当您不再需要时,请取消挂起的
pendingent
。在此之后,您的服务将不会自动运行,直到您再次启用它

Intent i = new Intent(this, Service.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, PendingIntent.FLAG_NO_CREATE);
if (pi != null) pi.cancel;
有关使用报警的更多信息:

有关
IntentService

的更多信息,如您所见,您可以在线程中使用此代码:

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

但是,一般来说,最好避免无限循环服务。当工作完成时,应考虑停止服务,并在需要新工作时重新启动它(使用<代码> AlalMasks<代码> >。我不会重复使用
IntentService
AlarmManager
的代码,因为Eugen Pechanec已经给了您一个很好的解释。

您希望如何在不创建实现Runnable或extneds线程的类的情况下启动线程(显然不可能在不创建线程的情况下停止线程)?这里的代码已经创建了一个子类-一个匿名子类。
Intent i = new Intent(this, Service.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, PendingIntent.FLAG_NO_CREATE);
if (pi != null) pi.cancel;
try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        // We've been interrupted, and returning from the run method will stop your thread.
        return;
    }