美文网首页
android獲取經緯度以及監聽位置變化

android獲取經緯度以及監聽位置變化

作者: 奶酪师 | 来源:发表于2018-04-02 17:38 被阅读0次

    獲取android手機系統定位經緯度(可以的話,用百度,高德之類的sdk比較好)0.0

    private Location location;
    private LocationManager locationManager;
    
    //獲取經緯度,自動選擇最精確經緯度
    public Location getLastKnownLocation() {
            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            List<String> providers = locationManager.getProviders(true);
            Location bestLocation = null;
            for (String provider : providers) {
                location = null;
                if (ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED &&
                        ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    location = locationManager.getLastKnownLocation(provider);
                    locationManager.requestLocationUpdates(provider, 0, 2, locationListener);
                }
    
                if (location == null) {
                    continue;
                }
                if (bestLocation == null
                        || location.getAccuracy() < bestLocation.getAccuracy()) {
    
                    bestLocation = location;
                }
            }
            if (bestLocation == null) {
                return null;
            }
            return bestLocation;
        }
    
       LocationListener locationListener = new LocationListener() {
           @Override
           public void onLocationChanged(Location location) {
               //位置變化監聽
               MainActivity.this.location = location;
           }
    
           @Override
           public void onStatusChanged(String s, int i, Bundle bundle) {
    
           }
    
           @Override
           public void onProviderEnabled(String s) {
    
           }
    
           @Override
           public void onProviderDisabled(String s) {
    
           }
       };
     @Override
        protected void onDestroy() {
            super.onDestroy();
            //移除位置監聽
            if (locationManager != null) {
                locationManager.removeUpdates(locationListener);
            }
        }
    

    最好監聽位置變化,以獲取經緯度,不然的話獲取的經緯度不是最新的,app重開還是上一個地點的經緯度(能否有大神告知我原因)導致位置出錯

    相关文章

      网友评论

          本文标题:android獲取經緯度以及監聽位置變化

          本文链接:https://www.haomeiwen.com/subject/znuxhftx.html