安卓转向GPS On&在2.2中以编程方式关闭?

时间:2011-12-22 07:39:56

标签: android google-maps-api-3 gps

我在我的应用程序中使用GPS,我想以编程方式打开和关闭GPS以节省电力我该怎么办 :(

这是关闭我需要打开

private void turnGPSOnOff(){
  String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
  if(!provider.contains("gps")){
    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);
    //Toast.makeText(this, "Your GPS is Enabled",Toast.LENGTH_SHORT).show();
  }
}

3 个答案:

答案 0 :(得分:1)

private void turnGPSOnOn(){
  String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
  if(provider.contains("gps")){ // for turn on
    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);
    Toast.makeText(this, "Your GPS is Enabled",Toast.LENGTH_SHORT).show();
  }
}

答案 1 :(得分:1)

    try
                {
                dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
              } 
              catch (SecurityException e1) 
              {
                // TODO Auto-generated catch block
                e1.printStackTrace();
              } 
              catch (NoSuchMethodException e1) 
              {
                // TODO Auto-generated catch block
                e1.printStackTrace();
              }

                dataMtd.setAccessible(true); 
               try {

                dataMtd.invoke(conm,true);


                //gprDisable();
              } 
               catch (IllegalArgumentException e) 
               {
                // TODO Auto-generated catch block
                e.printStackTrace();
              } 
               catch (IllegalAccessException e) 
               {
                // TODO Auto-generated catch block
                e.printStackTrace();
              } 
               catch (InvocationTargetException e) 
               {
                // TODO Auto-generated catch block
                e.printStackTrace();
              }

如果您将选项设为false,则可以禁用GPS。希望这可以帮到你。

答案 2 :(得分:-2)

您可以使用

打开gps
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new CTLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1.0f, locationListener);

并使用

将其关闭
locationManager.removeUpdates(locationListener);

或者您也可以在使用的gps上找到另一个帖子: How can I enable or disable the GPS programmatically on Android?