2016-07-15 40 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