java 在 Android M 中获取纬度和经度 0.0
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36915290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting Latitude and Longitude 0.0 in Android M
提问by KishuDroid
I am suffering from the problem of getting value 0.0 as latitude and longitude in Android Marshmallow (API 23) i.e. 6.0.
我遇到了在 Android Marshmallow (API 23) ie 6.0 中获取 0.0 作为纬度和经度的问题。
I have searched a lot regarding this but didn't find solution of it. My code is fully working for the other API versions which are less than 23.
我对此进行了很多搜索,但没有找到解决方案。我的代码完全适用于小于 23 的其他 API 版本。
I have also put the code for selfPermission and which all are working instead it's giving me 0.0 as late and long.
我还为 selfPermission 放置了代码,并且所有这些代码都在工作,而是给了我 0.0 作为迟到时间。
Please have a look on the way I am following:
请看看我关注的方式:
GPSTracker.java
GPS追踪器.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:
DashboardActivity.java:
In onCreate() I have initialized GPSTracker:
在 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
AndroidManifest.xml
<permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
I have gone through many links provided in Stack Overflow but none of them helped me to solve this problem.
我浏览了 Stack Overflow 中提供的许多链接,但没有一个能帮助我解决这个问题。
I would appreciate any kind of help here.
我很感激这里的任何帮助。
回答by KishuDroid
With the help of CommonsWareand Blackkaraanswer, I was able to solve my problem.
在CommonsWare和Blackkara的帮助下,我解决了我的问题。
As per their suggestion I have changed my code and have a look after each and every step of my code with debugging.
根据他们的建议,我更改了代码,并通过调试查看了代码的每一步。
Due to that I came with the problem that my onLocationChanged() did not get fired in the case of Marshmallow but surprisingly, it gets fire in the case of older devices which are less than Android M or 6.0.
因此,我遇到了一个问题,即我的 onLocationChanged() 在 Marshmallow 的情况下没有被触发,但令人惊讶的是,它在低于 Android M 或 6.0 的旧设备的情况下被触发。
For solving this I have changed my code as below, here I am posting the full code so that anyone who has the same problem can get rid of it.
为了解决这个问题,我已经改变了我的代码如下,在这里我发布了完整的代码,以便任何有同样问题的人都可以摆脱它。
GPSTracker.java
GPS追踪器.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
仪表盘活动.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 :
清单.xml :
Permission which are added
添加的权限
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Declare service in Application Tag:
在应用程序标签中声明服务:
<service android:name=".utilities.GPSTracker"/>
回答by blackkara
You could be having below causes?
您可能有以下原因?
First cause
第一个原因
Location provider is not giving you 0.0 values as latitude and longitude. You are getting what had you define first time. Because, you didn't receive fresh location or getLastKnownLocation() returns null. So latitude and longitude variables keep their first values (0.0)
位置提供程序没有为您提供 0.0 值作为纬度和经度。你得到了你第一次定义的东西。因为,您没有收到新位置或 getLastKnownLocation() 返回 null。所以纬度和经度变量保持它们的第一个值 (0.0)
double latitude;
double longitude;
Second cause
第二个原因
Whenever you call getLocation() method, getLastKnownLocation() method will be doing nothing until onLocationChanged fire! (depending on provider)
每当您调用 getLocation() 方法时,getLastKnownLocation() 方法将不会执行任何操作,直到 onLocationChanged 触发!(取决于供应商)
@Override
public void onLocationChanged(Location location) {
}
Elaborated for 'depending on provider'
详细说明“取决于提供者”
You have requested both gps and network providers.
您已请求 GPS 和网络提供商。
requestLocationUpdates(LocationManager.NETWORK_PROVIDER ... mLocationListener);
requestLocationUpdates(LocationManager.GPS_PROVIDER ... mLocationListener);
And then has called getLastKnownLocation method for both two providers
然后为两个提供者调用了 getLastKnownLocation 方法
locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Assume that those two providers have returned null. In this case, you need to wait until onLocationChanged method has been fired. Otherwise you will be getting null from getLastKnownLocation method depending on 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
}
}
回答by CommonsWare
First, remove these:
首先,删除这些:
<permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Those are defined by the platform, not you.
这些是由平台定义的,而不是你。
Also, you are not reacting when the user actually grants permission to you. Request the permissions in your activity, and do not create an instance of GPSTracker
until you have permission. That maybe immediately, if checkSelfPermission()
says that you have permission. Otherwise, that will be when the activity is called with onRequestPermissionResult()
.
此外,当用户实际向您授予权限时,您并没有做出反应。在您的活动中请求权限,并且GPSTracker
在您获得权限之前不要创建实例。这可能是立即的,如果checkSelfPermission()
说你有许可。否则,这将是使用onRequestPermissionResult()
.
The location work itself is also buggy, in that you seem to think that you will get a location immediately, which will not be the case much of the time.
定位工作本身也有问题,因为您似乎认为自己会立即获得定位,但很多时候情况并非如此。
回答by jaiminkumar patel
Guy I resolved this issue, first answer which is given in this blocks works fine. In order to remove the 0.0 from the Latitude and Longitude, just Go in your phone settings, open the app manager and grant the permission for app. it will show, as for letting it pending for user, we can throw the Dialog with permission.
我解决了这个问题,这个块中给出的第一个答案工作正常。要从经纬度中删除0.0,只需进入手机设置,打开应用程序管理器并授予应用程序权限。它会显示,至于让它为用户挂起,我们可以在允许的情况下抛出对话框。