1
我正在使用示例應用程序中的線程。在我的應用程序中,我使用了3個線程在無限循環中運行。這3個線程用於android服務類。當我啓動這些線程時,線程正在運行並且UI不是允許直到完成無限循環。但我怎樣才能停止線程,我如何處理UI?如何從android服務停止無限循環線程?
我寫了一個服務類,如下所示:
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線程?
請任何身體幫我嗎?