其他分享
首页 > 其他分享> > 可以停止位置更新,Android服务

可以停止位置更新,Android服务

作者:互联网

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

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;
        }
    }
}

解决方法:

它对您不起作用的原因是您正在使用IntentService,因此调用stopService()不会导致调用onDestroy(),大概是因为在onHandleIntent()完成之后已经调用了它.无需在IntentService上调用stopService(),请参见here.

看来您应该只使用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(),它应该可以按预期工作.

标签:android-location,android
来源: https://codeday.me/bug/20191028/1950846.html