【问题标题】:Can able to stop location update, Android service可以停止位置更新,Android服务
【发布时间】:2015-08-23 17:46:23
【问题描述】:

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

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

【问题讨论】:

  • 如何从我的 MainActivity 调用 stopLocationUpdates()。我认为连接到 mGoogleApiClient 后该服务已停止。

标签: android android-location


【解决方案1】:

它对您不起作用的原因是您使用的是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(),它应该可以正常工作。

【讨论】:

  • 谢谢。是的,我认为 Service() 类是一个更好的解决方案。将尝试使用 Service()
  • 我需要将存储在本地数据库中的位置发送到服务器(经过一段时间或网络可用)。你能推荐一些教程或起点吗?
  • @bolt123 为此你使用timerTask
  • @Daniel Nugent 使用 IntentService 存在一个问题。当我停止使用意图操作“stoplocationupdates”时,mGoogleApiClient 始终为空。解决方案选项 2 - 坚持 IntentService 不起作用。有什么想法吗?
  • @bolt123 它还在那个时候给你位置更新吗?
【解决方案2】:
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);

【讨论】:

  • 如何从我的 MainActivity 调用 stopLocationUpdates()。我认为连接到 mGoogleApiClient 后该服务已停止。
【解决方案3】:

在stopService()中调用stopLocationUpdates()方法

【讨论】:

  • 如何从我的 MainActivity 调用 stopLocationUpdates()。我认为连接到 mGoogleApiClient 后该服务已停止。
【解决方案4】:

当您停止服务时。然后在 LocationIntentService.class 中调用这一行。

locationManager.removeUpdates(this);

【讨论】:

  • 如何从我的 MainActivity 调用 stopLocationUpdates()。我认为连接到 mGoogleApiClient 后该服务已停止。
猜你喜欢
  • 2020-01-28
  • 1970-01-01
  • 2017-11-05
  • 1970-01-01
  • 1970-01-01
  • 2017-01-24
  • 2013-09-25
  • 2023-03-10
  • 1970-01-01
相关资源
最近更新 更多