Java 调用 stopService() 时,Android 服务不会停止
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20907670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android service not stopping when stopService() is called
提问by MrJR
I'm having an issue stopping a service that I have started.
我在停止已启动的服务时遇到问题。
The service is called when the user logs in, and starts to track the user's location. This is working fine. The service is meant to stop when the user presses the logout button and is successfully logged out.
该服务在用户登录时被调用,并开始跟踪用户的位置。这工作正常。该服务旨在在用户按下注销按钮并成功注销时停止。
It's an android service that is being called through a JavaScript interface by a HTML button.
这是一个由 HTML 按钮通过 JavaScript 界面调用的 android 服务。
Here is my Main Class which contains the methods for starting and stopping the service:
这是我的主类,其中包含启动和停止服务的方法:
public class CasesMain extends DroidGap {
Intent gpsTracking;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
appView.addJavascriptInterface(this, "StartGPS");
super.loadUrl(Config.getStartUrl());
}
public void startGPS(){
gpsTracking = new Intent(this, MyService.class);
startService(gpsTracking);
}
public void stopGPS(){
stopService( gpsTracking );
}
}
}
Here is the MyService class:
这是 MyService 类:
public class MyService extends Service {
private LocationManager locManager;
private LocationListener locListener = new myLocationListener();
private boolean gps_enabled = false;
private boolean network_enabled = false;
private Handler handler = new Handler();
Thread t;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
}
@Override
public void onDestroy() {
}
@Override
public void onStart(Intent intent, int startid) {
}
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getBaseContext(), "Service Started", Toast.LENGTH_SHORT)
.show();
final Runnable r = new Runnable() {
public void run() {
location();
handler.postDelayed(this, 10000);
}
};
handler.postDelayed(r, 10000);
return START_STICKY;
}
public void location() {
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = locManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locListener);
}
if (network_enabled) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
0, 0, locListener);
}
}
private class myLocationListener implements LocationListener {
double lat_old = 0.0;
double lon_old = 0.0;
double lat_new;
double lon_new;
@Override
public void onLocationChanged(Location location) {
if (location != null) {
locManager.removeUpdates(locListener);
lon_new = location.getLongitude();
lat_new = location.getLatitude();
String longitude = "Longitude: " + location.getLongitude();
String latitude = "Latitude: " + location.getLatitude();
Log.v("Debug", "Latt: " + latitude + " Long: " + longitude);
Toast.makeText(getApplicationContext(),
longitude + "\n" + latitude, Toast.LENGTH_SHORT).show();
lat_old = lat_new;
lon_old = lon_new;
}
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
}
And here is my call to stop the service: window.StartGPS.stopGPS();
这是我停止服务的呼吁: window.StartGPS.stopGPS();
The start works perfectly, but when I log out, the app continues to show messages of the latt and long meaning the call to stopService()
either didn't work or is not called.
开始工作正常,但是当我注销时,该应用程序继续显示 latt 和 long 的消息,这意味着调用stopService()
要么不起作用,要么没有被调用。
Can anyone see where my mistake is or what is going wrong?
谁能看到我的错误在哪里或出了什么问题?
Any help would be greatly appreciated!
任何帮助将不胜感激!
FIXEDAdding handler.removeCallbacksAndMessages(null);
in the onDestroy()
method of MyService
fixed it for me.
FIXED添加为我修复它handler.removeCallbacksAndMessages(null);
的onDestroy()
方法MyService
。
采纳答案by CommonsWare
Can anyone see where my mistake is or what is going wrong?
谁能看到我的错误在哪里或出了什么问题?
You have an empty onDestroy()
method. You need to call removeCallbacks()
on your Handler
there.
你有一个空的onDestroy()
方法。你需要打电话removeCallbacks()
给你Handler
那里。
回答by Sathya
Here's what I would suggest 1) Put more log statements in calls leading to stopService. 2) Implement On ServiceConnection interface and see what's happening in OServiceConnected and onServiceDisconnected.
这是我的建议 1) 在导致 stopService 的调用中放置更多日志语句。2) 实现 On ServiceConnection 接口并查看 OServiceConnected 和 onServiceDisconnected 中发生了什么。
回答by AlexA
If you are using any android.os.Handler in the service remember to call removeCallbacksAndMessages like this:
如果您在服务中使用任何 android.os.Handler 记得像这样调用 removeCallbacksAndMessages:
@Override
public void onDestroy() {
Toast.makeText(this, "service onDestroy", Toast.LENGTH_LONG).show();
Utils.cancelNotification(this);
customHandler.removeCallbacksAndMessages(null);
}
And the service will destroy successfully. It worked for me.
并且服务将成功销毁。它对我有用。