Android 停止服务“;处理程序循环代码“;不';行不通
我读了所有类似的问题并尝试了它们,但我无法解决我的问题。我创建了一个服务,该服务每5秒显示一次toast消息。但我不能停止这项服务。你能帮我修一下吗?多谢各位Android 停止服务“;处理程序循环代码“;不';行不通,android,service,Android,Service,我读了所有类似的问题并尝试了它们,但我无法解决我的问题。我创建了一个服务,该服务每5秒显示一次toast消息。但我不能停止这项服务。你能帮我修一下吗?多谢各位 public class myservice extends Service { @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent,
public class myservice extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
go2sec();
return super.onStartCommand(intent, flags, startId);
}
private void go2sec() {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
Toast.makeText(myservice.this, "hello", Toast.LENGTH_LONG).show();
go2sec();
}
}, 5000);
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
---主要活动---
我可以开始服务
startService(new Intent(this, myservice.class));
但是,我不能停止服务强>
stopService(new Intent(this, myservice.class));
你需要停止你的处理程序 您必须在
ondestory
方法中的handler
上调用removeCallbacks
这将正确停止您的服务。您需要删除服务中的处理程序回调。并在服务中调用
stopSelf()
,以停止它
代码如下:
public class Myservice extends Service {
final Handler handler = new Handler();
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
go2sec();
return super.onStartCommand(intent, flags, startId);
}
private Runnable task = new Runnable () {
public void run() {
Toast.makeText(Myservice.this, "hello", Toast.LENGTH_LONG).show();
go2sec();
}
};
private void go2sec() {
handler.postDelayed(task, 5000);
}
@Override
public void onDestroy() {
handler.removeCallbacks(task); //remove handler
stopSelf(); //stop the service
super.onDestroy();
}
}
找到解决方案:
public class VolumeService extends Service {
boolean running;
Thread t;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
Log.d("service destroyed", "destroyed");
running = false;
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
running = true;
t = new Thread(new Runnable() {
@Override
public void run() {
while (running) {
if ("check your condition when you want to start the job") {
Log.d("Service", "Service:Started");
try {
startJob();
waitForSometime();
} catch (Exception e) {
e.printStackTrace();
}
} else {
t.interrupt();
Log.d("ServiceStop", "Service:Stopped");
running = false;
}
}
}
});
t.start();
return START_STICKY;
}
private void startJob() {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
// your logic / business implementation
}
});
}
}
谢谢你,艾哈迈德,但是“stopService();”又不起作用了?你会来的……编码快乐