2017-05-03 84 views
0

我需要獲取當前設備位置(緯度/經度),但「getCurrentLocation()」始終顯示「無提供商」,因此位置爲空。我把這種方法的onCreate(),並宣佈在清單文件中的所有權限:無法獲得當前位置

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

真實設備位置服務已啓用爲好。

getCurrentLocation()java代碼:

public void getCurrentLocation() { 
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 
    Criteria c = new Criteria(); 
    provider = locationManager.getBestProvider(c, false); 
    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. 
     return; 
    } 
    location = locationManager.getLastKnownLocation(provider); 
    if(location!=null) 
    { 
     double lng=location.getLongitude(); 
     double lat=location.getLatitude(); 
     Toast.makeText(this, Double.toString(lat) + "\n" + Double.toString(lng), Toast.LENGTH_SHORT).show(); 
    } 
    else 
    { 
     Toast.makeText(this, "No provider", Toast.LENGTH_SHORT).show(); 
    } 
} 

我怎樣才能解決這個問題?

P.S .:我修改了很多類似的問題,但找不到合適的解決方案。

+0

你已經評論了有關權限的部分,你是否至少給了使用設置的權限? (Android 5.0及更早版本) – AxelH

回答

0

首先考慮使用FusedLocationProvider而不是LocationManager。 Here你可以找到如何使用id的指南。

第二 - 你試圖得到「最後知道的位置」,它並不總是在那裏。要接收用戶位置,您需要訂閱LocationManager更新。 This是如何做到這一點。

+0

*要接收用戶位置,您需要訂閱LocationManager更新*,這不正確。只有當你想要更新 –

+0

@TimCastelijns,如果你沒有收到位置作爲最後的知道,那麼訂閱是唯一的選擇。 – Ekalips

-2
public class GPSTracker extends Service implements LocationListener { 

private final Activity mContext; 

// flag for GPS status 
boolean isGPSEnabled = false; 

// flag for network status 
boolean isNetworkEnabled = false; 

// flag for GPS status 
boolean canGetLocation = false; 

Location location; // location 
double latitude; // latitude 
double longitude; // longitude 

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; 

// The minimum distance to change Updates in meters 
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters 

// The minimum time between updates in milliseconds 
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute 

// Declaring a Location Manager 
protected LocationManager locationManager; 
public GPSTracker(Activity context) { 
    this.mContext = context; 
    getLocation(); 
} 

public Location getLocation() { 
    try { 
     locationManager = (LocationManager) mContext 
       .getSystemService(LOCATION_SERVICE); 

     // getting GPS status 
     isGPSEnabled = locationManager 
       .isProviderEnabled(LocationManager.GPS_PROVIDER); 

     // getting network status 
     isNetworkEnabled = locationManager 
       .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

     if (!isGPSEnabled && !isNetworkEnabled) { 
      // no network provider is enabled 
     } else { 
      this.canGetLocation = true; 
      // First get location from Network Provider 
      checkLocationPermission(); 
      if (isNetworkEnabled) { 
       locationManager.requestLocationUpdates(
         LocationManager.NETWORK_PROVIDER, 
         MIN_TIME_BW_UPDATES, 
         MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
       Log.d("Network", "Network"); 
       if (locationManager != null) { 
        location = locationManager 
          .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        if (location != null) { 
         latitude = location.getLatitude(); 
         longitude = location.getLongitude(); 
        } 
       } 
      } 
      // if GPS Enabled get lat/long using GPS Services 
      if (isGPSEnabled) { 
       if (location == null) { 
        locationManager.requestLocationUpdates(
          LocationManager.GPS_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("GPS Enabled", "GPS Enabled"); 
        if (locationManager != null) { 
         location = locationManager 
           .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
         if (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
         } 
        } 
       } 
      } 
     } 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    return location; 
} 

/** 
* Stop using GPS listener 
* Calling this function will stop using GPS in your app 
* */ 
public void stopUsingGPS(){ 
    if(locationManager != null){ 
     checkLocationPermission(); 
     locationManager.removeUpdates(GPSTracker.this); 
    } 
} 

/** 
* Function to get latitude 
* */ 
public double getLatitude(){ 
    if(location != null){ 
     latitude = location.getLatitude(); 
    } 

    // return latitude 
    return latitude; 
} 

/** 
* Function to get longitude 
* */ 
public double getLongitude(){ 
    if(location != null){ 
     longitude = location.getLongitude(); 
    } 

    // return longitude 
    return longitude; 
} 

/** 
* Function to check GPS/wifi enabled 
* @return boolean 
* */ 
public boolean canGetLocation() { 
    return this.canGetLocation; 
} 

/** 
* Function to show settings alert dialog 
* On pressing Settings button will lauch Settings Options 
* */ 
public void showSettingsAlert(){ 
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 

    // Setting Dialog Title 
    //alertDialog.setTitle("GPS is settings"); 

    // Setting Dialog Message 
    alertDialog.setMessage("Please enable GPS to get locations."); 

    // On pressing Settings button 
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int which) { 
      Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
      mContext.startActivity(intent); 
     } 
    }); 

    // on pressing cancel button 
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int which) { 
      dialog.cancel(); 
     } 
    }); 

    // Showing Alert Message 
    alertDialog.show(); 
} 

@Override 
public void onLocationChanged(Location location) { 
} 

@Override 
public void onProviderDisabled(String provider) { 
} 

@Override 
public void onProviderEnabled(String provider) { 
} 

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

@Override 
public IBinder onBind(Intent arg0) { 
    return null; 
} 

public boolean checkLocationPermission() 
{ 
    if (ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
    { 
     // Should we show an explanation? 
     if (ActivityCompat.shouldShowRequestPermissionRationale(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION)) 
     { 
      // Show an expanation to the user *asynchronously* -- don't block 
      // this thread waiting for the user's response! After the user 
      // sees the explanation, try again to request the permission. 

      //Prompt the user once explanation has been shown 
      ActivityCompat.requestPermissions(mContext, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 
        MY_PERMISSIONS_REQUEST_LOCATION); 
     } 
     else 
     { 
      // No explanation needed, we can request the permission. 
      ActivityCompat.requestPermissions(mContext, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 
        MY_PERMISSIONS_REQUEST_LOCATION); 
     } 
     return false; 
    } 
    else 
    { 
     if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) 
     { 
      showGPSDisabledAlertToUser(); 
     } 

     return true; 
    } 
} 

private void showGPSDisabledAlertToUser() 
{ 
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext); 
    alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?") 
      .setCancelable(false) 
      .setPositiveButton("Settings", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
        Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
        mContext.startActivity(callGPSSettingIntent); 
       } 
      }); 
    alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
    { 
     public void onClick(DialogInterface dialog, int id) 
     { 
      dialog.cancel(); 
     } 
    }); 
    AlertDialog alert = alertDialogBuilder.create(); 
    alert.show(); 
} 

}

試試這個代碼,每當你需要獲得位置創建一個GPS對象並獲取經緯度和長

如:

GPSTracker gpsTracker = new GPSTracker(activity); 
      Latitude = gpsTracker.getLatitude(); 
      Longtude = gpsTracker.getLongitude(); 
+0

當'location'會被更新? 'public void onLocationChanged(Location location){'沒有實現。我不認爲這是使用聽衆只獲得一個職位的最佳解決方案。 – AxelH

+2

從您自己的項目中複製粘貼一整套代碼並不能很好地解決問題。這確實不能回答問題 –

+0

我使用完全相同的代碼來獲取經緯度 –

0
provider = locationManager.getBestProvider(c, true); 

試代碼中的這種變化

0

不保證.getLastKnownLocation()返回先前存儲的位置數據。

它可以返回一個null

因此,您必須爲需要偵聽位置更新的情況做好準備。你註冊他們這樣的:

locationManager 
      .requestLocationUpdates(provider, 0, 0, 
        new LocationListener() { 
         @Override 
         public void onLocationChanged(Location location) { 
          //here you receive the new location 
         } 

         @Override 
         public void onStatusChanged(String s, int i, Bundle bundle) { 

         } 

         @Override 
         public void onProviderEnabled(String s) { 

         } 

         @Override 
         public void onProviderDisabled(String s) { 

         } 
        }););