在Android M中获取纬度和经度0.0

我在Android Marshmallow(API 23)即6.0中获得了价值0.0作为纬度和经度的问题。

我已经搜索了很多关于这个,但没有找到它的解决方案。 我的代码完全适用于小于23的其他API版本。

我也把selfPermission的代码和所有正在运行的代码放在一起,而不是它给我0.0很晚和很长。

请看看我关注的方式:

GPSTracker.java

public class GPSTracker extends Service implements LocationListener { private Context 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 // The minimum distance to change Updates in meters private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1000; // 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; Activity activity; public GPSTracker() { } public GPSTracker(Context context, Activity activity) { this.mContext = context; this.activity = activity; 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; if (isNetworkEnabled) { int requestPermissionsCode = 50; if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, requestPermissionsCode); } else { 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 latitude/longitude using GPS Services if (isGPSEnabled) { if (location == null) { if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 50); } else { 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) { if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 50); } else { 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/Wi-Fi enabled * @return boolean * */ public boolean canGetLocation() { return this.canGetLocation; } /** * Function to show settings alert dialog. * On pressing the Settings button it will launch 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("GPS is not enabled. Do you want to go to settings menu?"); // On pressing the 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 the 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; } } 

DashboardActivity.java:

在onCreate()中我初始化了GPSTracker:

 gps = new GPSTracker(mContext,DashboardActivity.this); // Check if GPS enabled if(gps.canGetLocation()) { double latitude = gps.getLatitude(); double longitude = gps.getLongitude(); // \n is for new line Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show(); } else { // Can't get location. // GPS or network is not enabled. // Ask user to enable GPS/network in settings. gps.showSettingsAlert(); } 

AndroidManifest.xml中

      

我已经浏览了Stack Overflow中提供的许多链接,但它们都没有帮助我解决这个问题。

我很感激这里的任何帮助。

CommonsWareBlackkara的帮助下,我能够解决我的问题。

根据他们的建议,我已经改变了我的代码,并通过调试了解我的代码的每一步。

由于我遇到了问题,我的onLocationChanged()在Marshmallow的情况下没有被解雇,但令人惊讶的是,在旧设备的情况下,它会低于Android M或6.0。

为了解决这个问题,我已经更改了我的代码,在这里,我发布了完整的代码,以便任何有相同问题的人都可以摆脱它。

GPSTracker.java

 public class GPSTracker extends Service{ private Context 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 // The minimum distance to change Updates in meters private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1000; // 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; Activity activity; public GPSTracker() { } public GPSTracker(Context context, Activity activity) { this.mContext = context; this.activity = activity; 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; if (isNetworkEnabled) { int requestPermissionsCode = 50; locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, mLocationListener); 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 latitude/longitude using GPS Services if (isGPSEnabled) { if (location == null) { if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 50); } else { locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, mLocationListener); 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() { } private final LocationListener mLocationListener = new LocationListener() { @Override public void onLocationChanged(final Location location) { if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }; /** * 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/Wi-Fi enabled * @return boolean * */ public boolean canGetLocation() { return this.canGetLocation; } /** * Function to show settings alert dialog. * On pressing the Settings button it will launch 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("GPS is not enabled. Do you want to go to settings menu?"); // On pressing the 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 the cancel button alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); // Showing Alert Message alertDialog.show(); } @Override public IBinder onBind(Intent arg0) { return null; } } 

DashboardActivity.java

 public class DashboardActivity extends Activity { Context mContext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dashboard); mContext = this; if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(DashboardActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1); } else { Toast.makeText(mContext,"You need have granted permission",Toast.LENGTH_SHORT).show(); gps = new GPSTracker(mContext, DashboardActivity.this); // Check if GPS enabled if (gps.canGetLocation()) { double latitude = gps.getLatitude(); double longitude = gps.getLongitude(); // \n is for new line Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show(); } else { // Can't get location. // GPS or network is not enabled. // Ask user to enable GPS/network in settings. gps.showSettingsAlert(); } } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case 1: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the // contacts-related task you need to do. gps = new GPSTracker(mContext, DashboardActivity.this); // Check if GPS enabled if (gps.canGetLocation()) { double latitude = gps.getLatitude(); double longitude = gps.getLongitude(); // \n is for new line Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show(); } else { // Can't get location. // GPS or network is not enabled. // Ask user to enable GPS/network in settings. gps.showSettingsAlert(); } } else { // permission denied, boo! Disable the // functionality that depends on this permission. Toast.makeText(mContext, "You need to grant permission", Toast.LENGTH_SHORT).show(); } return; } } } } 

Manifest.xml:

已添加的权限

     

在Application Tag中声明服务:

   

首先,删除这些:

   

这些是由平台定义的,而不是你。

此外,当用户实际授予您权限时,您不会做出反应。 请求您的活动中的权限,并且在您获得许可之前不要创建GPSTracker的实例。 如果checkSelfPermission()表示您有权限,则可能会立即执行此操作。 否则,将在使用onRequestPermissionResult()调用活动时。

位置工作本身也是错误的,因为您似乎认为您将立即获得一个位置,而在大多数情况下情况并非如此。

你可能有以下原因?

第一个原因

位置提供商没有给出0.0值作为纬度和经度。 你得到了第一次定义的东西。 因为,您没有收到新的位置或getLastKnownLocation()返回null。 所以纬度和经度变量保持其第一个值(0.0)

 double latitude; double longitude; 

第二个原因

每当你调用getLocation()方法时,getLastKnownLocation()方法都会做什么,直到onLocationChanged fire! (取决于提供者)

 @Override public void onLocationChanged(Location location) { } 

详细说明’取决于供应商’

您已请求gps和网络提供商。

 requestLocationUpdates(LocationManager.NETWORK_PROVIDER ... mLocationListener); requestLocationUpdates(LocationManager.GPS_PROVIDER ... mLocationListener); 

然后为两个提供程序调用了getLastKnownLocation方法

 locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 

假设这两个提供程序返回null 。 在这种情况下,您需要等到onLocationChanged方法被触发。 否则,您将从getLastKnownLocation方法获取null, 具体取决于提供程序

 @Override public void onLocationChanged(final Location location) { String providerName = location.getProvider(); if(providerName.equals(LocationManager.GPS_PROVIDER)){ // onLocationChanged method is fired by gps provider. // After this point, getLastKnownLocation(); method returns not-null // for LocationManager.GPS_PROVIDER } if( providerName.equals(LocationManager.NETWORK_PROVIDER)){ // onLocationChanged method is fired by network provider. // After this point, getLastKnownLocation(); method returns not-null // for LocationManager.NETWORK_PROVIDER } }