Is there way to programmatically enable GPS on Android 2.1 & above?

╄→尐↘猪︶ㄣ 提交于 2019-12-04 23:14:22

If the documentation said that it can't be set programmatically, I suggest you not to do so. There are many impacts why the documentation said that. And if someone was able to do that (enabling the GPS programmatically), it means he/she doing something that was undocumented.

Activating GPS requires user's permission. If your application was able to activate the GPS without notifying the users (furthermore, asking for the user's permission), you might violate the privacy policy.

No you can't. But you can prompt the user to enable it. Here's the code.

private void buildAlertMessageNoGps() {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(
            "Your GPS seems to be disabled, do you want to enable it?")
            .setCancelable(false).setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(
                                @SuppressWarnings("unused") final DialogInterface dialog,
                                @SuppressWarnings("unused") final int id) {
                            Intent intent = new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(intent);
                        }
                    }).setNegativeButton("No",
                    new DialogInterface.OnClickListener() {
                        public void onClick(final DialogInterface dialog,
                                @SuppressWarnings("unused") final int id) {
                            dialog.cancel();
                        }
                    });
    final AlertDialog alert = builder.create();
    alert.show();
}

yes this can be done up to 2.2 (sdk 8).

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);
}
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!