2013-12-23 74 views
0

可能的重複,編程開啓GPS在android系統

How to enable/disable gps and mobile data in android programmatically?

我已經看到的人,告訴他們可以在android系統編程打開GPS。但是我使用相同的代碼,並且無法做到這一點。

它只是顯示「正在搜索GPS ..」,但實際上並沒有這樣做。

這裏是我使用的代碼,

//Enable GPS 
    Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE"); 
    intent.putExtra("enabled", true); 
    sendBroadcast(intent); 

    //Disable GPS 
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE"); 
intent.putExtra("enabled", false); 
sendBroadcast(intent); 

我也試過這個,

String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); 
    if(!provider.contains("gps")){ 
     //if gps is disabled 
     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")); 
     context.sendBroadcast(poke); 
    } 

但是,當我這樣做,

LocationManager manager = (LocationManager) getSystemService(getApplicationContext().LOCATION_SERVICE); 
boolean isGPSEnabled = manager 
      .isProviderEnabled(LocationManager.GPS_PROVIDER); 

它返回我isGPSEnabled總是假的。如果我手動打開GPS,它將返回爲true。

任何機構都可以告訴我是否可以打開GPS?如果是這樣,我會出錯的地方。

+0

問:在哪裏我要去錯了嗎?答:知道這個問題是重複的,但仍然會繼續發佈。 – NickT

回答

3
//Enable GPS 
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE"); 
intent.putExtra("enabled", true); 
context.sendBroadcast(intent); 

//Disable GPS 
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE"); 
intent.putExtra("enabled", false); 
context.sendBroadcast(intent); 

當您廣播時使用上下文。

希望這個作品..

爲了使移動數據,你應該使用這個 -

final ConnectivityManager conman = (ConnectivityManager) context 
      .getSystemService(Context.CONNECTIVITY_SERVICE); 
    final Class conmanClass = Class.forName(conman.getClass().getName()); 
    final Field iConnectivityManagerField = conmanClass 
      .getDeclaredField("mService"); 
    iConnectivityManagerField.setAccessible(true); 
    final Object iConnectivityManager = iConnectivityManagerField 
      .get(conman); 
    final Class iConnectivityManagerClass = Class 
      .forName(iConnectivityManager.getClass().getName()); 
    final Method setMobileDataEnabledMethod = iConnectivityManagerClass 
      .getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE); 
    setMobileDataEnabledMethod.setAccessible(true); 

    setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled); 
+0

我只使用第一個代碼,但沒有上下文。它不起作用 – tejas

+0

它應該工作時,你會使用上下文,請嘗試使用上下文。 – Amit

+0

我試過使用getApplicationContext()。sendBroadcast(intent);如果我手動打開GPS,禁用工作但不啓用。它只是說,搜索GPS – tejas