【发布时间】: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