enable GPS - Android Map

Android examples for Map:GPS

Description

enable GPS

Demo Code


//package com.java2s;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.net.Uri;
import android.provider.Settings;
import android.util.Log;

public class Main {

    public static void enableGPS(Context context) {
        try {//from  www .  ja  v a  2s  . c  o m
            if (android.os.Build.VERSION.SDK_INT >= 8) {
                if (!android.provider.Settings.Secure
                        .isLocationProviderEnabled(
                                context.getContentResolver(),
                                LocationManager.GPS_PROVIDER)) {
                    android.provider.Settings.Secure
                            .setLocationProviderEnabled(
                                    context.getContentResolver(),
                                    LocationManager.GPS_PROVIDER, true);
                }
            } else {
                if (!isGpsEnabled(context))
                    toggleGPS(context);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @return true if GPS location is opened,or false
     */
    public static boolean isGpsEnabled(Context context) {
        String str1 = Settings.Secure.getString(
                context.getContentResolver(),
                Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        Log.v("GPS", str1);
        if (str1 != null) {
            return str1.contains(LocationManager.GPS_PROVIDER);
        } else {
            return false;
        }
    }

    private static void toggleGPS(Context context) {
        Intent gpsIntent = new Intent();
        gpsIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        gpsIntent.addCategory("android.intent.category.ALTERNATIVE");
        gpsIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, gpsIntent, 0).send();
        } catch (CanceledException e) {
            e.printStackTrace();
        }
    }
}

Related Tutorials