2016-08-09 5 views
0

でclass.this私はGPS座標を処理し、1時間のための新しいオブジェクトをAtomicReferenceを設定し、いくつかのAndroidのサービスコードを読んでいる:第二に新しいオブジェクトが= AtomicReference

public class SingleLocationUpdateService extends ServicePart { 
private final AtomicReference<GPSUpdater> currentUpdater = new AtomicReference<>(); 
@Override 
protected boolean onStart() { 
    lastSaverModeOn = mService.getSettings().getRootSettings().isSaverModeOn(); 
    if (mService.getSettings().getRootSettings().isStopMileageInWorkOn()) { 
     if (lastSaverModeOn) { 
      return false; 
     } 
    } 

    singleUpdateSeconds = mService.getSettings().getRootSettings().getGpsRareUpdateSeconds(); 
    ***currentUpdater.set(new GPSUpdater());*** 
    mService.getExecutor().schedule(currentUpdater.get(), 10, TimeUnit.SECONDS); 
    return true; 
} 

その後shedulerはこれを実行

private class GPSUpdater implements Runnable, LocationListener { 

@Override 
    public void run() { 
     if (!isCurrentRunning()) { 
      return; 
     } 
     Log.d(TAG, "Requesting single location update"); 
     final LocationManager lm = (LocationManager) mService.getSystemService(Context.LOCATION_SERVICE); 
     try { 
      lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this, Looper.getMainLooper()); 
     } catch (Throwable t) { 
      Log.e(TAG, "Failed to request single location update", t); 
     } 
     reschedule(); 
    } 

    private boolean isCurrentRunning() { 
     return isStarted() && currentUpdater.get() == GPSUpdater.this; 
    } 

    private void reschedule() { 
     final LocationManager lm = (LocationManager) mService.getSystemService(Context.LOCATION_SERVICE); 
     lm.removeUpdates(this); 

     final GPSUpdater next = new GPSUpdater(); 

     if (isStarted() && currentUpdater.compareAndSet(GPSUpdater.this, next)) { 
      Log.d(TAG, "Rescheduling single location updater"); 
      mService.getExecutor().schedule(next, 10, TimeUnit.SECONDS); 
     } 
    } 

currentUpdater.compareAndSet(GPSUpdater.this、next)を1回実行するとデバッガでtrueを返します。つまり、新しいGPSUpdater(onStart()に設定されています)== GPSUpdater.thisです。次にAtomicReferenceがnextに設定されます。しかし、次は新しいGPSUpdaterです。 uはcurrentUpdater.compareAndSet(GPSUpdater.this、次の)2時間をeveluate場合しかし、それはfalseを返します。だから2回新しいGPSUpdater!= GPSUpdater.this。どのように正しく説明できますか?私は2つの新しいオブジェクト参照を作成した場合 - のみ最初の1は、そのクラスのリファレンスに等しくなりますか?どうして?あらかじめThx。

+0

質問を絞り込んで[mcve]読んでいる/理解している* –

答えて

0

Class GPSUpdaterの2つの異なるオブジェクトは、それぞれnew GPSUpdater()を呼び出して作成しています。したがって、2つのオブジェクトを比較する場合は、equals()メソッドを使用してください。また、GPSUpdateクラスを自分で作成した場合は、適切な結果を得るためにequals()メソッドを上書きする必要があります。これにより、2つのオブジェクトが等しいと定義すると、equalsはtrueを返すはずです。 オペレーター==を使用して2つのオブジェクトが同じであるかどうかを確認する場合は、オブジェクトの実際の「コンテンツ」ではなくチェックされます

関連する問題