gpt4 book ai didi

android - Lollipop 和棉花糖 gps 问题无法获取经度和纬度值,但相同的代码在 21 以下的 api 上工作

转载 作者:行者123 更新时间:2023-11-29 01:15:43 24 4
gpt4 key购买 nike

我在堆栈溢出中遇到了很多问题 **但无法解决我的问题它不是任何垃圾邮件问题**

大家好,我遇到了与纬度和经度值相关的问题

我能够在 Android 5.0 之前的所有 api 中获取值,但是从 5.1 开始我面临无法获取值的问题

这是我使用的代码

我只添加了用于获取权限的代码

   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(MainActivity.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, MainActivity.this);

// Check if GPS enabled
if (gps.canGetLocation()) {

getlatitude = gps.getLatitude();
getlongitude = gps.getLongitude();

// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + getlatitude + "\nLong: " + getlongitude, 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) {


gps = new GPSTracker(mContext, MainActivity.this);

// Check if GPS enabled
if (gps.canGetLocation()) {

getlatitude = gps.getLatitude();
getlongitude = gps.getLongitude();

// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + getlatitude + "\nLong: " + getlongitude, 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;
}
}
}

但我还是得到了

Toast 为 Lat 0 Long 0

关于gradle的信息

目标是 sdk 23 版本

在搜索了几个问题后,我开始知道我们需要获得这些值的许可,任何人都可以在这方面明确地帮助我

list 文件

我已经添加了

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

还有网络供应商许可

**

Now i have added the new code according to changes in below

**

    public class MainActivity extends Activity {



Context context;

double latitude_user,longitude_user;

public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;

String[] permissions= new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


if (checkPermissions()) {

GPSTracker gps;

gps = new GPSTracker(context);

latitude_user= gps.getLatitude();
longitude_user = gps.getLongitude();

Toast.makeText(MainActivity.this, "Permission has been granted"+latitude_user+" "+longitude_user, Toast.LENGTH_SHORT).show();

}else{

Toast.makeText(MainActivity.this, "Not granted", Toast.LENGTH_SHORT).show();

}


}


private boolean checkPermissions() {
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
for (String p:permissions) {
result = ContextCompat.checkSelfPermission(getApplicationContext(),p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
}

和GPSTracker.class

public class GPSTracker extends Service implements LocationListener {

private final 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 = 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(Context 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;
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(){

}

/**
* 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("GPS is not enabled. Do you want to go to settings menu?");

// 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) {
this.location = location;
getLatitude();
getLongitude();
}

@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;
}

}

最佳答案

首先你需要检查设备的操作系统版本然后你获得权限,意味着如果设备操作系统版本是 6.0 或以上那么动态获得权限是必需的但低于则不需要。请你也注意 GPS 位置是开/关,所以我建议你在获得许可后还可以动态检查 GPS 位置是否开/关。请使用这个它在我的应用程序中工作,我希望你也能得到你的答案

public class GettingPermission extends AppCompatActivity {

Activity activity;

public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

activity = GettingPermission.this;

if (Build.VERSION.SDK_INT >=23)
{
getPermission();
}
else
{
startApp();
}
}

private void startApp()
{
Intent i = new Intent(activity, GetLatLog.class)
activity.startActivity(i)
}



private void getPermission()
{
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION)
+ ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {

Log.i("Permission is require first time", "...OK...getPermission() method!..if");
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_ID_MULTIPLE_PERMISSIONS);

}
else
{
Log.i("Permission is already granted ", "...Ok...getPermission() method!..else");
startApp();
}
}


@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {
if ((grantResults.length > 0) && (grantResults[0]+grantResults[1])
== PackageManager.PERMISSION_GRANTED) {
// Permission granted.

Log.i("onRequestPermissionsResult()...","Permission granted");
startApp();

} else {
// User refused to grant permission.
Toast.makeText(StartActivity.this, "All Permission is required to use the Screen Recorder", Toast.LENGTH_LONG).show();
getPermission();

}
}
}

GetLatLog.java 文件是

public class GetLatLog extends AppCompatActivity{

Activity activity;

private int ENABLE_LOCATION = 100;

double latitude = 0.0, longitude = 0.0;

private GPSTracker gps;
ProgressDialog pd;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.temp);

try
{
activity = GetLatLog.this;

locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);

if (isLocationEnabled())
{
getLocation();
}
else
{
showSettingsAlert();
}

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

protected LocationManager locationManager;
private boolean isLocationEnabled()
{
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}

private void getLocation()
{
try
{
if (isLocationEnabled())
{
gps = new GPSTracker(activity);

// check if GPS enabled
if(gps.canGetLocation())
{
latitude = gps.getLatitude();
longitude = gps.getLongitude();

Log.i("Location", ""+latitude + " : " + longitude);

if(latitude == 0.0 || longitude == 0.0)
{
retryGettingLocationDialog();
}
else
{
//startYour code here, You come here after getting lat and log.
}
}
else
{
Toast.makeText(activity , "Location Not Enabled", Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(activity , "GPS disabled. Cannot get location. Please enable it and try again!", Toast.LENGTH_LONG).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}

public void showSettingsAlert()
{

Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
activity.startActivityForResult(intent, ENABLE_LOCATION);

}

public void retryGettingLocationDialog()
{
retryGettingLocation();
}

private void retryGettingLocation()
{
try
{
new AsyncTask<Void, Void , Void>()
{
@Override
protected void onPreExecute()
{
try {
pd = new ProgressDialog(activity);
pd.setCancelable(false);
pd.setMessage("Please while we retry getting your location...");
pd.show();
} catch (Exception e) {
e.printStackTrace();
}

super.onPreExecute();
}

@Override
protected Void doInBackground(Void... params)
{
try
{
Thread.sleep(1500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}

return null;
}

@Override
protected void onPostExecute(Void aVoid)
{
super.onPostExecute(aVoid);

if(pd != null)
{
pd.cancel();
pd.dismiss();
pd = null;
}

getLocation();
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void)null);
}
catch (Exception e)
{
e.printStackTrace();
}
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);

try {
//if (resultCode == Activity.RESULT_OK)
{
if(requestCode == ENABLE_LOCATION)
{
if (isLocationEnabled())
{
getLocation();
}
else
{
showSettingsAlert();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

关于android - Lollipop 和棉花糖 gps 问题无法获取经度和纬度值,但相同的代码在 21 以下的 api 上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39796381/

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