我的MainActivity中有一个选中的按钮。如果选中该按钮,它应该启动服务,但如果用户取消选中该按钮,我想停止该服务。
所以在取消检查条件下我写了stopService(intentname);
,但问题是服务没有停止。这是我的代码片段:
服务类
public class SimpleService extends Service
{
String selectedAudioPath = "";
private MyThread myythread;
public Intent intent;
public boolean isRunning = false;
long interval=30000;
@Override
public IBinder onBind(Intent arg0)
{
return null;
}
@Override
public void onCreate()
{
super.onCreate();
myythread = new MyThread(interval);
}
@Override
public synchronized void onDestroy()
{
super.onDestroy();
if(!isRunning)
{
myythread.interrupt();
myythread.stop();
isRunning = false;
}
}
@Override
public synchronized void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
if(!isRunning)
{
//this.intent = intent;
//System.out.println("the intent is" + intent);
myythread.start();
isRunning = true;
}
}
class MyThread extends Thread
{
long interval;
public MyThread(long interval)
{
this.interval=interval;
}
@Override
public void run()
{
while(isRunning)
{
System.out.println("Service running");
try
{
String myString = intent.getStringExtra("name");
if(myString == null)
Log.d("Service","null");
else
{
Log.d("Service","not null");
if(myString.equalsIgnoreCase("image"))
{
uploadImages();
Thread.sleep(interval);
}
else if(myString.equalsIgnoreCase("audio"))
{
uploadAudio();
Thread.sleep(interval);
}
}
}
catch (InterruptedException e)
{
isRunning = false;
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
您无法阻止具有此类
运行不可阻挡循环的线程while(true)
{
}
要停止该线程,请声明一个布尔变量并在while循环条件下使用它。
public class MyService extends Service {
...
private Thread mythread;
private boolean running;
@Override
public void onDestroy()
{
running = false;
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startid) {
running = true;
mythread = new Thread() {
@Override
public void run() {
while(running) {
MY CODE TO RUN;
}
}
};
};
mythread.start();
}
答案 1 :(得分:0)
不要使用线程。请改用AsyncTask。
public class MyService extends Service {
private AsyncTask<Void,Void,Void> myTask;
@Override
public void onDestroy(){
super.onDestroy();
myTask.cancel(true);
}
@Override
public void onStart(Intent intent, int startid) {
myTask = new AsyncTask<Void,Void,Void>(){
@Override
public void doInBackground(Void aVoid[]){
doYourWorkHere();
}
}
myTask.execute();
}
}