set GPS Enabled - Android Hardware

Android examples for Hardware:Gps

Description

set GPS Enabled

Demo Code


//package com.java2s;

import android.content.Context;
import android.content.Intent;

import android.net.Uri;

import android.provider.Settings;

public class Main {
    public static void setGPSEnabled(Context context, boolean enabled) {
        Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
        intent.putExtra("enabled", true);
        context.sendBroadcast(intent);/*  w w  w  . j  a v  a 2 s . co m*/

        String provider = Settings.Secure.getString(
                context.getContentResolver(),
                Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if (enabled && !provider.contains("gps")) {
            //if gps is disabled and the caller wants it on
            sendToggle(context, "3");
        } else if (!enabled && provider.contains("gps")) {
            //if gps is enabled and the caller wants it off
            sendToggle(context, "3");
        }
    }

    /**
     * toggles a setting in the widget provider. This is a hack to bypass GPS activation restrictions and only works on older versions of Android.
     *
     * @param context
     * @param position
     */
    private static void sendToggle(Context context, String position) {
        final Intent toggle = new Intent();
        toggle.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        toggle.addCategory(Intent.CATEGORY_ALTERNATIVE);
        toggle.setData(Uri.parse(position));
        context.sendBroadcast(toggle);
    }
}

Related Tutorials