2013-06-25 4 views
8

ユーザーの所在地を取得するだけで済みます。好ましくは正確な場所ですが、それが不可能な場合は、大まかな場所が良いでしょう。ドキュメントによればLocationManagerとLocationClientを合わせてユーザーの場所を取得する

LocationClient.getLastLocation()

Returns the best most recent location currently available.

LocationManager.getLastKnownLocation(String)

Returns a Location indicating the data from the last known location fix obtained from the given provider.

私の理解が正しいとすれば、前者は私に非常に良い結果(または時にはヌル)を与えますが、後者はまれではない結果を私に与えるでしょう。

これは私のコードでは(簡体字)

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
locationClient = new LocationClient(this, this, this); 

@Override 
public void onConnected(Bundle dataBundle) { 
    setUserLocation(); 
} 

private void setUserLocation() { 
    myLocation = locationClient.getLastLocation(); 

    if (myLocation == null) { 
     myLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(new Criteria(), false)); 
     if (myLocation == null) { 
      //I give up, just set the map somewhere and warn the user. 
      myLocation = new Location(""); 
      myLocation.setLatitude(-22.624152); 
      myLocation.setLongitude(-44.385624); 
      Toast.makeText(this, R.string.location_not_found, Toast.LENGTH_LONG).show(); 
     } 
    } else { 
     isMyLocationOK = true; 
    } 
} 

それが動作しているようだが、私の質問は以下のとおりです。

  1. getLastLocationgetLastKnownLocation正しいの私の理解ですか?
  2. これは良いアプローチですか?
  3. 同じアクティビティで両方を使用して問題が発生する可能性はありますか?位置フィックスが決定することは不可能である場合

おかげ

答えて

7

LocationClient.getLastLocation()のみnullを返します。 getLastLocation()で、よりもgetLastKnownLocation()であり、通常ははるかに優れています。私はそれがgetLastKnownLocation()に "転倒"する価値はないと思います。

両方で問題を解決することはできませんが、過剰です。

はもちろん、あなたがLocationClientは、Googleがサービスを再生の一部であることを覚えておく必要があり、それは、そのプラットフォームGoogleのPlayストアを含む、デバイス上でのみ利用可能です。一部の端末でAndroidの非標準バージョンを使用している可能性があります。LocationClientにアクセスすることはできません。

Google Playサービスのドキュメントで詳しく説明しています。

+0

お役立ち情報Google Playの可用性を処理するコードは既に用意されています(実際にはアプリがなくても機能しない可能性があります)。最初はLocationServicesだけを使用しましたが、何度も私はそこから奇妙な結果を得ました。 LocationClientに切り替えると、より良い結果が得られましたが、再現できなかった多くの場合nullが返されます。私はAndroidシステムがLocationServiceクラスにしかアクセスできない場所の最後の既知の場所を記録している可能性があると考えました。そうでない場合は、LocationClientだけに頼る方が良いでしょうか? – Androiderson

+0

[公式の開発者向けWeb](http://developer.android.com/guide/topics/)の[flow](http://developer.android.com/images/location/getting-location.png)を参照してください。 location/strateg.html) – Aiapaec

関連する問題