2017-03-09 6 views
1

私が取り組むAndroidアプリケーションでは、15分ごとにGPSの場所を記録する必要があります。 GPSの使用状況を最小限に抑えてバッテリ寿命を延ばすには、ScheduledExecutorServiceを使用して位置の更新を要求し、位置の変更が発生したら要求をオフにします。私の現在の実装では、エラーが発生したため、これを許可しない:私はLocationManagerは、バックグラウンドスレッドで呼び出しを行うことができないので、私は知っているスケジュールされたスレッドでの位置更新をリクエストする

Can't create handler inside thread that has not called Looper.prepare() 

が発生しました。

私のコードは、スケジューラを起動します。

locationFinder = new LocationFinder(context); 
final Runnable gpsBeeper = new Runnable() 
    { 
     public void run() 
     { 
      try { 
       locationFinder.getLocation();; 
      } 
      catch (Exception e) 
      { 
       Log.e(TAG,"error in executing: It will no longer be run!: " + e.getMessage()); 
       e.printStackTrace(); 
      } 
     } 
    }; 

    gpsHandle = scheduler.scheduleAtFixedRate(gpsBeeper, 0, 15, MINUTES); 

LocationFinderクラス:

public LocationFinder(Context context) 
{ 
    this.mContext = context; 
} 

public void getLocation() 
{ 

    locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE); 
    isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
    if (isGPSEnabled) 
    { 
     try 
     { 
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, updateInterval, distance, this); 
     } 
     catch (SecurityException s) 
     { 
      s.printStackTrace(); 
     } 
    } 
} 

public void stopUpdates(){ 
    locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE); 
    locationManager.removeUpdates(this); 
} 

@Override 
public void onLocationChanged(Location location) 
{ 
    latitude = location.getLatitude(); 
    longitude = location.getLongitude(); 
    isGPSUpdated = true; 
    stopUpdates(); 
} 

がどのように私はメインスレッドでrequestLocationUpdatesを呼び出すに頼ることなくこれを行うことができますか?

答えて

1

あなたの設定で問題が発生するのは、アプリがOSによって殺された場合、またはユーザーがアプリをスワイプして閉じると、その場所のアップデートの記録が停止されることです。実際には、アプリの状態にかかわらず、時間指定された場所の更新間隔を持つ2つの方法を取ることができます(アプリが強制終了された場合を除く)。

  1. リスナーへの参照を保持することなく、更新を受信継続を保証するために代わりLocationListenerPendingIntentを使用して、15分の更新間隔を設定するLocationManagerrequestLocationUpdates()方法を使用。すでに更新をリクエストしているかどうかを知る必要がある場合は、SharedPreferencesを使用してブール値フラグを保持してください。

  2. 他のGPSの更新を取得するLocationManagerrequestSingleUpdate()メソッドを呼び出す(フォアグラウンドで実行されているため)IntentService(バックグラウンドで実行されている場合)またはBroadcastReceiverを呼び出す更新をスケジュールするAlarmManagerを使用しています。

関連する問題