How do I find out if the GPS of an Android device is enabled

后端 未结 10 1559
暖寄归人
暖寄归人 2020-11-22 08:36

On an Android Cupcake (1.5) enabled device, how do I check and activate the GPS?

10条回答
  •  悲哀的现实
    2020-11-22 09:18

    yes GPS settings cannot be changed programatically any more as they are privacy settings and we have to check if they are switched on or not from the program and handle it if they are not switched on. you can notify the user that GPS is turned off and use something like this to show the settings screen to the user if you want.

    Check if location providers are available

        String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if(provider != null){
            Log.v(TAG, " Location providers: "+provider);
            //Start searching for location and update the location text when update available
            startFetchingLocation();
        }else{
            // Notify users and show settings if they want to enable GPS
        }
    

    If the user want to enable GPS you may show the settings screen in this way.

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

    And in your onActivityResult you can see if the user has enabled it or not

        protected void onActivityResult(int requestCode, int resultCode, Intent data){
            if(requestCode == REQUEST_CODE && resultCode == 0){
                String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
                if(provider != null){
                    Log.v(TAG, " Location providers: "+provider);
                    //Start searching for location and update the location text when update available. 
    // Do whatever you want
                    startFetchingLocation();
                }else{
                    //Users did not switch on the GPS
                }
            }
        }
    

    Thats one way to do it and i hope it helps. Let me know if I am doing anything wrong.

提交回复
热议问题