简体   繁体   English

调用stopService()时,Android服务不会停止

[英]Android service not stopping when stopService() is called

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. 这是一个Android服务,通过HTML按钮通过JavaScript界面​​调用。

Here is my Main Class which contains the methods for starting and stopping the service: 这是我的Main Class,它包含启动和停止服务的方法:

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. 开始工作完美,但是当我退出时,应用程序继续显示字符和long的消息意味着对stopService()的调用要么不起作用要么不被调用。

Can anyone see where my mistake is or what is going wrong? 任何人都可以看到我的错误在哪里或出了什么问题?

Any help would be greatly appreciated! 任何帮助将不胜感激!

FIXED Adding handler.removeCallbacksAndMessages(null); FIXED添加handler.removeCallbacksAndMessages(null); in the onDestroy() method of MyService fixed it for me. MyServiceonDestroy()方法中为我修复了它。

Can anyone see where my mistake is or what is going wrong? 任何人都可以看到我的错误在哪里或出了什么问题?

You have an empty onDestroy() method. 你有一个空的onDestroy()方法。 You need to call removeCallbacks() on your Handler there. 你需要在那里的Handler上调用removeCallbacks()

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. 它对我有用。

Here's what I would suggest 1) Put more log statements in calls leading to stopService. 以下是我的建议1)在调用导致stopService的过程中放入更多日志语句。 2) Implement On ServiceConnection interface and see what's happening in OServiceConnected and onServiceDisconnected. 2)实现On ServiceConnection接口,查看OServiceConnected和onServiceDisconnected中发生的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM