我正在创建一个在Oncreate中创建线程的服务。这个帖子是一个无限循环播放一个MP3文件,可以睡30秒。
我想要在onDestroy methed中找出如何阻止它
码
public void onCreate(){ Toast.makeText(this," Service Created",Toast.LENGTH_LONG).show();
mediaPlayer = MediaPlayer.create(this, R.raw.nysound);
mThread=new myThread();
mThread.start();
}
public class myThread extends Thread {
public void run() {
do{
mediaPlayer.start();
try
{
Thread.sleep(1000*20);
} catch(Exception e)
{
ted++;
}
} while(true);
} // end methed
} // end class
@Override
public void onDestroy() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
答案 0 :(得分:2)
您可以使用boolean
标志
public class myThread extends Thread {
private volatile boolean running = true;
public void run() {
do{
mediaPlayer.start();
try
{
Thread.sleep(1000*20);
} catch(Exception e)
{
ted++;
}
} while(running);
} // end methed
public void setRunning(boolean newValue) {
this.running = newValue;
}
} //
然后在主线程中执行以下操作
@Override
public void onDestroy() {
mThread.setRunning(false);
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
答案 1 :(得分:0)
stopSelf();
Intent i = new Intent(this,ServiceName.class); stopService(ⅰ);
这两项都将停止您的服务。
答案 2 :(得分:0)
您应该考虑使用高级对象ScheduledExecutorService来处理线程执行:
public void onCreate() { Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
mediaPlayer = MediaPlayer.create(this, R.raw.nysound);
ScheduledExecutorService ses =
Executors.newScheduledThreadPool(1);
scheduledFuture = ses.scheduleWithFixedDelay(new MyThread(), 0, 20, TimeUnit.SECONDS);
}
public class myThread extends Thread {
public void run() {
mediaPlayer.start();
} // end methed
} // end class
@Override
public void onDestroy() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
scheduledFuture.cancel(true);
}