2013-03-15 57 views
27

嗨,我正在创建一个防盗应用程序,并通过短信定位我的手机,它的工作完美,直到2.3。 但在4.0我不能以编程方式打开或关闭gps是否有任何其他可能的方式来通过代码开关gps。我怎样才能启用禁用GPS在编程方式在Android?

+0

http://stackoverflow.com/questions/4721449/enable-gps-programatically-like-tasker有看的代码在这里 – Dilip 2013-03-15 06:31:11

+2

过去PIC在你的问题。 – dhams 2013-04-10 06:06:36

+0

您是否检查过此链接http://stackoverflow.com/questions/4721449/enable-gps-programatically-like-tasker? – Jitendra 2013-04-10 06:08:27

回答

41

请尝试使用此代码。它适用于所有版本的我。

public void turnGPSOn() 
{ 
    Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE"); 
    intent.putExtra("enabled", true); 
    this.ctx.sendBroadcast(intent); 

    String provider = Settings.Secure.getString(ctx.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")); 
     this.ctx.sendBroadcast(poke); 


    } 
} 
// automatic turn off the gps 
public void turnGPSOff() 
{ 
    String provider = Settings.Secure.getString(ctx.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); 
    if(provider.contains("gps")){ //if gps is enabled 
     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")); 
     this.ctx.sendBroadcast(poke); 
    } 
} 
+0

非常感谢... – 2013-03-15 08:24:22

+0

此代码打开我的设备中的GPS,它不工作在关闭我正在使用4.0.4 ics – 2013-03-15 09:11:14

+2

嗨它不是在三星galaxy y工作。它把GPS接收机在常开模式,得到修复后,它应该是在睡眠模式.. – Sandeep 2013-06-02 10:00:26