Ask user to turn on Location

后端 未结 5 1909
情深已故
情深已故 2020-12-16 21:44

How can I prompt the user to turn on Location?


The app is supposed to filter a list of locations with the current location of the user. If the

5条回答
  •  离开以前
    2020-12-16 22:23

    Try

    private void turnGPSOn(){
       String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    
       if(!provider.contains("gps")){ //if gps is disabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        sendBroadcast(poke);
     }
    }
    
    private void turnGPSOff(){
       String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    
       if(provider.contains("gps")){ //if gps is enabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        sendBroadcast(poke);
    }
    }
    
    private boolean canToggleGPS() {
       PackageManager pacman = getPackageManager();
    PackageInfo pacInfo = null;
    
       try {
        pacInfo = pacman.getPackageInfo("com.android.settings", PackageManager.GET_RECEIVERS);
       } catch (NameNotFoundException e) {
        return false; //package not found
       }
    
       if(pacInfo != null){
        for(ActivityInfo actInfo : pacInfo.receivers){
            //test if recevier is exported. if so, we can toggle GPS.
            if(actInfo.name.equals("com.android.settings.widget.SettingsAppWidgetProvider") && actInfo.exported){
                return true;
            }
        }
     }
    
     return false; //default
    }
    

提交回复
热议问题