能够停止位置更新,Android服务

时间:2015-06-09 04:31:04

标签: android android-location

我正在尝试创建路线追踪应用。即使应用程序在后台,它也需要跟踪位置。所以我创建了一个服务并为此服务添加代码。以下是我的代码。但有一个问题。我从我的主要活动开始服务。

public void startTracking(View view) {
    startService(new Intent(MainActivity.this, LocationIntentService.class));
}

public void stopTracking(View view) {
    stopService(new Intent(MainActivity.this, LocationIntentService.class));
}

启动服务并将位置插入本地数据库。但我不能停止这些服务。当我使用上面的代码停止服务时,它仍然跟踪位置。如何停止位置更新。

public class LocationIntentService extends IntentService implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    private static final String TAG = LocationIntentService.class.getSimpleName();
    private static final long INTERVAL = 1000 * 10;
    private static final long FASTEST_INTERVAL = 1000 * 5;
    private static int DISPLACEMENT = 10;

    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    DBAdapter dbAdapter;

    public LocationIntentService() {
        super("LocationIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.e(TAG, " ***** Service on handled");
        if (isGooglePlayServicesAvailable()) {
            createLocationRequest();
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
            mGoogleApiClient.connect();
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.e(TAG, " ***** Service on connected");
        startLocationUpdates();
        openDB();
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.e(TAG, " ***** Service on suspended");
        mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.e(TAG, "Location changed");
        mLastLocation = location;

        String latitude = String.valueOf(mLastLocation.getLatitude());
        String longitude = String.valueOf(mLastLocation.getLongitude());
        Log.e(TAG, " ##### Got new location"+ latitude+ longitude);

        Time today = new Time(Time.getCurrentTimezone());
        today.setToNow();
        String timestamp = today.format("%Y-%m-%d %H:%M:%S");

        dbAdapter.insertRow(latitude, longitude, timestamp);
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.e(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
                + connectionResult.getErrorCode());
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "Service is Destroying...");
        super.onDestroy();
        if (mGoogleApiClient.isConnected()) {
            stopLocationUpdates();
            mGoogleApiClient.disconnect();
        }
        closeDB();
    }

    protected void stopLocationUpdates() {
        Log.d(TAG, "Location update stoping...");
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);
    }

    protected void startLocationUpdates() {
        Log.d(TAG, "Location update starting...");
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);

    }

    private void openDB() {
        dbAdapter = new DBAdapter(this);
        dbAdapter.open();
    }

    private void closeDB() {
        dbAdapter = new DBAdapter(this);
        dbAdapter.close();
    }

    protected void createLocationRequest() {
        Log.e(TAG, " ***** Creating location request");
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
    }

    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            Log.e(TAG, " ***** Update google play service ");
            return false;
        }
    }
}

4 个答案:

答案 0 :(得分:3)

它不适合您的原因是您使用的是IntentService,因此调用stopService()不会导致onDestroy()被调用,大概是因为它已经被调用{ {1}}已完成。无需在onHandleIntent()stopService()致电IntentService

看起来您应该使用Service代替IntentService。这样,当您致电stopService()时,它会调用onDestroy()并取消注册位置更新,如您所愿。

您需要做的唯一其他更改是覆盖onStartCommand()而不是onHandleIntent()

您的课程将扩展Service而不是IntentService,然后移动您的代码以注册onStartCommand的位置更新:

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, " ***** Service on start command");
        if (isGooglePlayServicesAvailable()) {
            createLocationRequest();
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
            mGoogleApiClient.connect();
        }
        return Service.START_STICKY;
    }

这样您仍然可以拨打startService()stopService(),它应该可以正常运作。

答案 1 :(得分:1)

LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);

答案 2 :(得分:0)

在stopService()

中调用stopLocationUpdates()方法

答案 3 :(得分:0)

停止服务时。然后在 LocationIntentService.class

中调用此行
processing.app.debug.RunnerException
at cc.arduino.packages.uploaders.SSHUploader.uploadUsingPreferences(SSHUploader.java:102)
at processing.app.debug.Compiler.upload(Compiler.java:163)
at processing.app.Sketch.upload(Sketch.java:1220)
at processing.app.Sketch.exportApplet(Sketch.java:1194)
at processing.app.Sketch.exportApplet(Sketch.java:1166)
at processing.app.Editor$DefaultExportHandler.run(Editor.java:2487)
at java.lang.Thread.run(Thread.java:745)
Caused by: com.jcraft.jsch.JSchException: session is down
at com.jcraft.jsch.Session.openChannel(Session.java:843)
at cc.arduino.packages.ssh.SSH.execSyncCommand(SSH.java:58)
at cc.arduino.packages.uploaders.SSHUploader.runAVRDude(SSHUploader.java:130)
at cc.arduino.packages.uploaders.SSHUploader.uploadUsingPreferences(SSHUploader.java:93)
... 6 more