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

Posted

技术标签:

【中文标题】棒棒糖和棉花糖 gps 问题无法获取经度和纬度值,但在 21 以下的 api 上工作的代码相同【英文标题】:lollipop and marshmallow gps issue not able to fetch longitude and latitude values but same code working on api below 21 【发布时间】:2017-02-09 07:39:11 【问题描述】:

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

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

我能够在 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 as Lat 0 Long 0

关于 gradle 的信息

我是面向 sdk 23 版本

在搜索了几个问题后,我知道我们需要获得这些值的许可才能在这方面明确地帮助我

清单文件

我已经添加了

 <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/>

还有 网络提供商权限

**

现在我已经根据下面的更改添加了新代码

**

    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;



【问题讨论】:

【参考方案1】:

首先您需要检查设备的操作系统版本然后获得许可,这意味着如果设备操作系统版本为 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();
        
    

【讨论】:

您可以在哪个设备上运行您的应用程序 我想在从 api 15 到 api 23 的所有 api 中运行 如果 API 级别 23,那么我们需要获得动态权限,否则不需要,正如我在回答中解释的那样,如果您的 API 级别低于 23,那么它也可以正常工作。请检查我的最新答案。它适用于所有 API 级别 嗨,我会检查更新的代码,你的旧代码对我有用在 api 5.0 中,您将在一天内通知您有关新代码的信息。.. 我也使用 genymotion 所有 api 直到 kitkat 工作,但棒棒糖和棉花糖模拟器根本没有开始无法启动虚拟设备错误,而其他设备工作正常

以上是关于棒棒糖和棉花糖 gps 问题无法获取经度和纬度值,但在 21 以下的 api 上工作的代码相同的主要内容,如果未能解决你的问题,请参考以下文章

onActivityResult 返回 Intent data.getData();仅在棉花糖和棒棒糖中始终为空

onActivityResult 返回 Intent data.getData();仅在棉花糖和棒棒糖中始终为空

如何同时使用 GPS 和网络提供商在 Android 中获取当前位置的纬度和经度值

获取棉花糖中的当前位置 0,其中 23 API 以下使用融合位置给出准确的当前位置

使用gps从纬度和经度获取当前位置

我可以得到纬度和经度,但我无法在 SWIFT 中访问 GPS 高度信息