How to enable gps in Android

前端 未结 2 1619
灰色年华
灰色年华 2021-01-07 01:45

How to open the gps in Android when it is closed to retrieve the current position. I test two method

private void turnGPSOn(){
    String provider = Settings         


        
相关标签:
2条回答
  • 2021-01-07 02:11

    You can't enable GPS for a user, what you can do is, if GPS s disabled, prompt the user with a message to ask him to enable GPS and send him to the settings to enable it

    with this code :

    Intent gpsOptionsIntent = new Intent(  
        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);  
    startActivity(gpsOptionsIntent);
    

    This is a more detailed code on how to do it

    http://java-blog.kbsbng.com/2012/08/displaying-dialog-in-android-to-prompt.html

    To get the location you do this

        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    
      /*try to see if the location stored on android is close enough for you,and avoid rerequesting the location*/
        Location location =  locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    
        if (location == null
                || location.getTime()
                        - Calendar.getInstance().getTimeInMillis() > MAX_LAST_LOCATION_TIME)
        {
    
            locationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, TIME_INTERVAL, LOCATION_INTERVAL, yourLocationListener);
    
        }
        else
        {
            //do your handling if the last known location stored on android is enouh for you
        }
    

    in yourLocationListener, you implement what to do when you get the location

    0 讨论(0)
  • 2021-01-07 02:16

    It's inappropiate to enable GPS from the code. You can't fo that.

    There used to be an exploit that allowed the GPS to be turned on by an app with no special permissions. That exploit no longer exists as of 2.3 (in most ROMs).

    0 讨论(0)
提交回复
热议问题