2016-07-15 80 views
2

我是Android新手,我正在開發一個顯示用戶當前位置的Android應用程序。我正在使用Genymotion。現在我正在使用在Android中查找用戶的當前位置

mLocation=LocationServices.FusedLocationApi.getLastLocation(mGoogleClient); 

獲取設備的最後位置。事情是我想獲得當前的位置,但與此我得到mlocation不爲null這很好。但在地圖中顯示設備的最後位置始終不是當前位置。

代碼段

@Override 
public void onConnected(Bundle bundle) { 
    Log.i(TAG, "inside onconnected Location services connected"); 
    Location mLocation=null; 
    mLocationRequest= new LocationRequest(); 
    mLocationRequest.setInterval(10 * 1000) ; 
    mLocationRequest.setFastestInterval(1 * 1000);mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != 
     PackageManager.PERMISSION_GRANTED && 
     ActivityCompat.checkSelfPermission(this, 
     Manifest.permission.ACCESS_COARSE_LOCATION) != 
     PackageManager.PERMISSION_GRANTED) { 

    } 
       mLocation=LocationServices.FusedLocationApi.getLastLocation(mGoogleClient); 
    if(mLocation==null) 
    { 
     Log.d("***Inside mlocation***", "***mlocation is null here"); 
    } 

    if (mLocation != null) { 
     onLocationChanged(mLocation); 
    } 
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleClient, mLocationRequest, this); 
} 

@Override 
public void onLocationChanged(Location location) { 
    double currentLatitude = location.getLatitude(); 
    double currentLongitude = location.getLongitude(); 
    LatLng latLng = new LatLng(currentLatitude,currentLongitude); 
    MarkerOptions options = new MarkerOptions() 
      .position(latLng) 
      .title("Im here!"); 

    mMap.addMarker(options); 
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
} 

onstart()我稱爲googleapi.connect()和予適當地使用setUpMapIfNeeded()

請告訴我這段代碼有什麼問題。我正在嘗試這個3天。

+0

在代碼中沒有提及GPS打開/關閉。 你應該在app forground打開gps。 –

+0

嗨傑伊,我的模擬器中的gps已打開,但是我從您的聲明中瞭解到的是我需要檢查gps的可用性是否正確。但後來它也沒有改變我的想法。 – Navi

+0

查看我的回答@Navi –

回答

0

對於地圖服務,它需要Google Play服務。確保您的Genymotion已安裝PlayService(如果沒有)從Here獲取幫助在Genymotion中安裝Google Play服務。 快樂編碼.. !!!

+0

hi raj,谷歌播放服務安裝正確。 – Navi

+0

谷歌地圖API與Android官方文檔在這裏 - > https://developers.google.com/maps/documentation/android-api/ –

0
 LocationListener locationListener; 
     LocationManager locationManager; 
     double latitude; 
     double longitude; 


     locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 


     locationListener = new LocationListener() 
     { 
      @Override 


      public void onLocationChanged(Location location) { 

    longitude = location.getLongitude(); 
    latitude = location.getLatitude(); 
    } 

      @Override 
      public void onStatusChanged(String provider, int status, Bundle extras) { 
      } 

      @Override 
      public void onProviderEnabled(String provider) { 
      } 

      @Override 
      public void onProviderDisabled(String provider) { 
      } 
     }; 
     if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      // TODO: Consider calling 
      // ActivityCompat#requestPermissions 
      // here to request the missing permissions, and then overriding 
      // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
      //           int[] grantResults) 
      // to handle the case where the user grants the permission. See the documentation 
      // for ActivityCompat#requestPermissions for more details. 

      ; 
     } 
     locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000, 0, locationListener); 



     Log.e("location", longitude + " " + latitude); 
+0

試試這個代碼...這應該工作正常 – nandish

+0

嗨Nandish我添加了相同的代碼,並改變因此,但我仍然得到相同的舊位置。在上面的代碼中,我有一個疑問,當onLocationChanged()被調用時,位置對象爲null。因爲我們沒有給它任何價值..並請建議我.. – Navi

1

發佈帶代碼的簡單解決方案。

裏面添加的AndroidManifest.xml權限文件

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

,如果你的應用程序是兼容的棉花糖然後檢查運行時間許可。

添加gradle這個文件裏面的依賴:

compile 'com.google.android.gms:play-services:9.2.0' 

實現此兩種接口在你活動

GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener 

在OnCreate中創建googleapiclient對象是這樣的:

mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 

,使這個在啓動活動

mGoogleApiClient.connect(); 

在這裏,我們去的位置的結果,回調在此重寫方法。

public void onConnected(@Nullable Bundle bundle) { 
    Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
    if (mLastLocation != null) { 
     Log.e(TAG, "onConnected: " + String.valueOf(mLastLocation.getLatitude()) + ":" + String.valueOf(mLastLocation.getLongitude())); 
    } else { 
     Toast.makeText(getApplicationContext(), "Your Location Not Found", Toast.LENGTH_LONG).show(); 
    } 
} 

活動的完整的代碼是類似的東西:

public class LocationActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { 

private static final String TAG = LocationActivity.class.getSimpleName(); 

private GoogleApiClient mGoogleApiClient; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_location); 


    // Create an instance of GoogleAPIClient. 
    if (mGoogleApiClient == null) { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
    } 
} 

@Override 
protected void onStart() { 
// connect googleapiclient 
    mGoogleApiClient.connect(); 
    super.onStart(); 
} 

@Override 
protected void onStop() { 
// disconnect googleapiclient 
    mGoogleApiClient.disconnect(); 
    super.onStop(); 
} 

@Override 
public void onConnected(@Nullable Bundle bundle) { 
    Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
    if (mLastLocation != null) { 
    // here we go you can see current lat long. 
     Log.e(TAG, "onConnected: " + String.valueOf(mLastLocation.getLatitude()) + ":" + String.valueOf(mLastLocation.getLongitude())); 
    } 
} 

@Override 
public void onConnectionSuspended(int i) { 

} 

@Override 
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

}} 

附:如果沒有播放服務,Googleapiclient無法在模擬器中工作,因此您必須在真實設備上進行測試。 請確保gps在該設備上啓用。

如果您想使用傳統方法獲取位置,請嘗試本教程。 http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/

------ UPDATE 6月15日---------

爲最新的API 檢查谷歌Android後: https://android-developers.googleblog.com/2017/06/reduce-friction-with-new-location-apis.html

+0

傑伊我已經寫了與上面相同的代碼。完全相同的一些額外的標記多數民衆贊成在..但沒有得到什麼問題。 – Navi

+0

即使在模擬器中安裝谷歌播放服務後,你的意思是說,這段代碼不起作用..?因爲我的老年運動已經安裝了一切..現在我必須做..我需要測試它在我的Android手機..? – Navi

+0

傑伊你知道什麼..我得到一切像緯度經度和使用geocoder我甚至能夠得到地址也..但這是錯誤的,因爲我得到模擬器以前的位置的經度和緯度不是我目前的位置。我嘗試了所有的方式沒有得到什麼問題.. – Navi