【问题标题】:how to stop infinite loop threads from android service?如何从android服务停止无限循环线程?
【发布时间】:2011-10-01 05:32:29
【问题描述】:

我正在使用示例应用程序中的线程。在我的应用程序中,我使用了 3 个线程在无限循环中运行。这 3 个线程用于 android 服务类。当我启动这些线程时,线程正在运行并且 UI 是直到无限循环完成才允许。但是如何停止线程以及如何处理 UI?

我写了一个服务类如下:

ServiceApp.java

    public class ServiceApp extends Service
    {
  @Override
  public IBinder onBind(Intent arg0) {
    return null;
  }

@Override
public void onCreate() {
    super.onCreate();

    while(true)
    {
    Thread child1=new Thread(new Runnable() {

        @Override
        public void run() {

            try {

                function1();

            } catch (InterruptedException e) {

                e.printStackTrace();
            }

        }
    });

    child1.start();

    Thread child2=new Thread(new Runnable() {

        @Override
        public void run() {

            try {


                function2();



            } 
            catch (InterruptedException e) {

                e.printStackTrace();
            }
        }
    });

    child2.start();


    Thread child3=new Thread(new Runnable() {

        @Override
        public void run() {

            try {


                function3();


            } catch (InterruptedException e) {

                e.printStackTrace();
            }       
        }
    });

    child3.start();

Toast.makeText(ServiceApp.this, "All threads started", Toast.LENGTH_SHORT).show();

}
}

public void function1() throws InterruptedException
{
    Generic generic=new Generic(); //this for connect to web services

    String add=generic.getAdd(10,20);

    Log.v("function1", "addition from service"+add); 

    Thread.sleep(1000);

}

public void function2() throws InterruptedException
{

    Generic generic=new Generic(); //this for connect to web services

    String sub=generic.getSub(34,20);

    Log.v("function2", "subtraction from service"+sub); 

    Thread.sleep(1000);
}

public void function3() throws InterruptedException
{

    Generic generic=new Generic(); //this for connect to web services

    String mul=generic.getMul(4, 6);

    Log.v("function3", "multipicationn from service"+mul); 

    Thread.sleep(1000);
}

}

如何从活动类中停止 child1、child2、child3 线程?

请任何人帮助我?

【问题讨论】:

    标签: android multithreading service


    【解决方案1】:

    Service.onCreate() 在 UI 线程内执行。你有一个无限循环,不断创建越来越多的线程,所以 UI 没有机会响应用户的操作。如果你真的打算有这么多线程,你需要创建另一个线程来启动原来的三个。

    Activity 可以通过 Binder 与服务通信(您需要返回一个实际的实现而不是那里的 null)或发送意图,您可以在 Service.onStart() 中捕获和处理它

    【讨论】:

      猜你喜欢
      • 2014-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      • 2015-02-07
      • 2018-11-19
      相关资源
      最近更新 更多