簡體   English   中英

android在2.2中以編程方式打開和關閉GPS?

[英]android turn GPS On & Off Programmatically in 2.2?

我在應用程序中使用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();
  }
}
    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。 希望這對您有幫助。

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();
  }
}

您可以使用以下方式打開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上找到另一個線程: 如何在Android上以編程方式啟用或禁用GPS?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM