【问题标题】:android - how to remove location update IntentService automatically when app is killedandroid - 如何在应用程序被杀死时自动删除位置更新 IntentService
【发布时间】:2014-01-23 17:54:05
【问题描述】:

有一个 IntentService 用于每 10 秒更新一次位置。

mIntentService = new Intent(mActivity.getApplicationContext(), MyService.class);

mPendingIntent = PendingIntent.getService(mActivity.getApplicationContext(), 0,
                       mIntentService, PendingIntent.FLAG_UPDATE_CURRENT);

mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
            10*1000, 0, mPendingIntent);

应用程序被杀死时位置更新不会停止,它仍然每 10 秒运行一次。我无法删除 onDestroy() 方法中的位置更新,因为即使我们离开活动,该服务也必须运行。如何在应用被杀时自动取消位置更新服务?

【问题讨论】:

    标签: android location intentservice


    【解决方案1】:

    完成后,您需要删除 mLocationManager 的更新

    locationManager.removeUpdates(this);
    

    【讨论】:

      【解决方案2】:

      mLocationManager.removeUpdates(this);就足够了,但还要检查以确保您的应用程序不会崩溃。如果这对您有所帮助,请单击左侧的标记。

      @Override
      public void onDestroy() {
          super.onDestroy();
      
          removeLocationUpdates();
      }
      
      public void removeLocationUpdates(){
      
          if( mLocationManager != null && networkLocationListener != null ){
              if( mLocationManager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ){
                  mLocationManager.removeUpdates(networkLocationListener);
              }
          }
      }
      

      【讨论】:

      • 我无法删除 onDestroy() 方法中的位置更新,因为此服务即使我们离开活动也必须运行
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      • 1970-01-01
      相关资源
      最近更新 更多