gpt4 book ai didi

java - android经纬度返回0.0

转载 作者:行者123 更新时间:2023-11-29 02:41:19 25 4
gpt4 key购买 nike

我正在使用 NET_PROVIDER 检查当前的经度和纬度,并将它们打印为应用程序中的 toast 消息。但是,设置权限和连接网络后,经度和纬度总是返回0.0

我为解决此问题所做的工作:

  1. 设置权限
  2. onLocationChanged 方法中保存了之前的位置
  3. 我在模拟器和真实设备 (api22) 中都试过了。但都返回 0 给我。

enter image description here

这是我的代码。

TrackGps.java:

import android.Manifest;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;


import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;

/**
* Created by Hannah Liao on 5/7/2017
*/

public class TrackGps extends Service implements LocationListener {

private final Context mContext;

boolean checkNetwork = false;

boolean canGetLocation = false;
LocationListener locationListener;
Location loc ;
double latitude;
double longitude;


private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;


private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;

public TrackGps(Context mContext) {
this.mContext = mContext;
getLocation();
}

private Location getLocation() {

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

checkNetwork = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if(!checkNetwork) {
Toast.makeText(mContext, "No Service Provider Available", Toast.LENGTH_SHORT).show();
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (checkNetwork) {
Toast.makeText(mContext, "Network", Toast.LENGTH_SHORT).show();

try {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");

if (locationManager != null) {
loc = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
this.onLocationChanged(loc);
}

if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
} catch (SecurityException e) {

}
}
}
// if GPS Enabled get lat/long using GPS Services
// otherwise just use network
/*if (checkGPS) {
Toast.makeText(mContext, "GPS", Toast.LENGTH_SHORT).show();
if (loc == null) {
try {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
loc = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
}
} catch (SecurityException e) {

}
}
}*/

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

return loc;
}

public double getLongitude() {
if (loc != null) {
longitude = loc.getLongitude();
}
return longitude;
}

public double getLatitude() {
if (loc != null) {
latitude = loc.getLatitude();
}
return latitude;
}

public boolean canGetLocation() {
return this.canGetLocation;
}

public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);


alertDialog.setTitle("GPS Not Enabled");

alertDialog.setMessage("Do you wants to turn On GPS");


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


alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});


alertDialog.show();
}



public void stopUsingGPS() {
if (locationManager != null) {

locationManager.removeUpdates(TrackGps.this);
}
}

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

@Override
public void onLocationChanged(Location location) {
this.loc = location;
getLocation();
getLongitude();
getLatitude();
}

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

}

@Override
public void onProviderEnabled(String s) {

}

@Override
public void onProviderDisabled(String s) {

}

MainActivity.java

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private Button b_get;
private TrackGps gps;
double longitude;
double latitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b_get = (Button)findViewById(R.id.get);
b_get.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

gps = new TrackGps(MainActivity.this);

if(gps.canGetLocation()){


longitude = gps.getLongitude();
latitude = gps .getLatitude();

Toast.makeText(getApplicationContext(),"Longitude:"+String.valueOf(longitude)+"\nLatitude:"+Double.toString(latitude),Toast.LENGTH_SHORT).show();
}
else
{

gps.showSettingsAlert();
}

}
});
}

@Override
protected void onDestroy() {
super.onDestroy();
gps.stopUsingGPS();
}
}

list :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.map.hannah.location3">

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-feature android:name="android.hardware.location.gps" />
<application


android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<service android:name=".TrackGps" android:enabled="true" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

gradle:

apply plugin: 'com.android.application'

android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "com.map.hannah.location3"
minSdkVersion 17
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
}

最佳答案

 For Api marshmallow and above use run time permission as:
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
// do your work
} else {
// request permission.
ActivityCompat.requestPermissions(this, new String[]
{
Manifest.permission.ACCESS_FINE_LOCATION}, MY_LOCATION_REQUEST_CODE);
}

public void onRequestPermissionsResult(int requestCode, String[]
permissions, int[] grantResults) {
if (requestCode == MY_LOCATION_REQUEST_CODE) {
if (permissions.length == 1 &&
permissions[0] == Manifest.permission.ACCESS_FINE_LOCATION &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
/// granted do your work
} else {
// Permission was denied. Display an error message.
}
}

关于java - android经纬度返回0.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43854727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com