我正在开始Android开发,现在正在学习服务 我已经创建了一个简单的服务来连续烘烤一个字符串 我拿了两个按钮开始和停止服务 当我点击开始按钮时,服务启动并且它连续地烘烤字符串 但是当我通过点击停止按钮停止服务时,它不会停止 它将继续烘烤字符串。
public class MyService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
doToast();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
public void doToast()
{
final Handler handler= new Handler();
handler.postDelayed(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(MyService.this, "hi", 0).show();
handler.postDelayed(this, 3000);
}
}, 3000);
}
}
这是启动和停止服务的代码
startservice.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startService(new Intent(getBaseContext(), MyService.class));
}
});
stopservice.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), MyService.class));
}
});
答案 0 :(得分:3)
正如MD所提到的,即使你正在停止服务,你也必须删除回调,因为runnable仍然在消息队列中,等待再次发布。那就是:
public class AwesomeService extends Service {
// other stuff
private int DELAY = 2000;
Handler mHandler = new Handler();
Runnable toastRunnable;
public void doToast() {
mHandler.postDelayed(getToastRunnable(), DELAY);
}
private Runnable getToastRunnable() {
Runnable r = new Runnable() {
@Override public void run() {
// show toast
// doToast()
}
};
toastRunnable = r;
return r;
}
...
// and to remove the callbacks,
@Override public void onDestroy() {
super.onDestroy();
mHandler.removeCallbacks(toastRunnable);
}
}