Android examples for Hardware:Gps
enable GPS
//package com.java2s; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.provider.Settings; import android.util.Log; public class Main { private static final String LOG_TAG = "Geo Utils"; /**//from ww w . ja va 2 s . c o m * @param activity * @return true if GPS could be enabled without user interaction, else the * settings will be started and false is returned */ public static boolean enableGPS(Activity activity) { return switchGPS(activity, true, true); } /** * @param activity * @param enableGPS * @param showSettingsIfAutoSwitchImpossible * @return true if GPS could be switched to the desired value without user * interaction, else the settings will be started and false is * returned */ public static boolean switchGPS(Activity activity, boolean enableGPS, boolean showSettingsIfAutoSwitchImpossible) { if (canTurnOnGPSAutomatically(activity)) { String provider = Settings.Secure.getString( activity.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); boolean currentlyEnabled = provider.contains("gps"); if (!currentlyEnabled && enableGPS) { pokeGPSButton(activity); } else if (currentlyEnabled && !enableGPS) { pokeGPSButton(activity); } return true; } else if (showSettingsIfAutoSwitchImpossible) { Log.d(LOG_TAG, "Can't enable GPS automatically, will start " + "settings for manual enabling!"); openLocationSettingsPage(activity); } return false; } /** * source from * http://stackoverflow.com/questions/4721449/enable-gps-programatically * -like-tasker */ private static boolean canTurnOnGPSAutomatically(Context c) { PackageInfo pacInfo = null; try { pacInfo = c.getPackageManager().getPackageInfo( "com.android.settings", PackageManager.GET_RECEIVERS); } catch (NameNotFoundException e) { Log.e(LOG_TAG, "com.android.settings package not found"); 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 } private static void pokeGPSButton(Activity activity) { 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")); activity.sendBroadcast(poke); } public static void openLocationSettingsPage(Activity activity) { activity.startActivity(new Intent( android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); } }