2013-03-11 68 views
0

我试图检测我的设备上的GPS是否打开。无法返回布尔值从GPS检查

目前,我只是返回一个布尔真或假的值,然后要么继续我的代码,要么引导用户到GPS设置。

当我返回布尔值时,我的代码崩溃了。我已经调试过它,但仍然无法看到它为什么会返回值。

下面是代码:

GPSYesOrNo g = new GPSYesOrNo(this); 

    check = g.checkStatus(); 
    // check if GPS enabled 
    if (check == true) { 
    Intent Appoint = new Intent("com.example.flybaseapp.appointmantMenu"); 
    startActivity(Appoint); 
    } else { 
    alert(); 
    } 

而且GPSYesOrNo类:

public class GPSYesOrNo { 
    Context cc; 
    private LocationManager locationManager; 
    boolean enable; 

    public GPSYesOrNo(Context c) { 
     this.cc = c; 
     checkStatus(); 
    } 

    public boolean checkStatus() { 
     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
     boolean enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 

     if (enabled) { 
     return true; 
     } else { 
     return false; 
     } 
    } 
} 

任何人都可以看到,我错了?

+0

邮政logcat的请。 – Egor 2013-03-11 20:52:49

+0

@Egor Logcat添加了 – user1352057 2013-03-11 20:59:21

+0

是否指定了'locationManager'?向我们展示代码。 – 323go 2013-03-11 21:00:43

回答

1

您不应该扩展Activity,只需传入上下文即可获取locationManager。无论如何,你的应用程序崩溃,因为你没有与上下文参数调用构造函数。因此cc是空的。顺便说getSystemService(cc.LOCATION_SERVICE)应getSystemService(Context.LOCATION_SERVICE)

变化

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

locationManager = (LocationManager) cc.getSystemService(Context.LOCATION_SERVICE); 
+0

感谢您的回答。我明白你说的关于传递上下文的意见。我将它改回到没有活动类并编辑我的代码。我在创建类的实例时传递上下文,然后通过构造函数简单地调用方法。此刻我仍然收到一个错误,指出'方法getSystemService(字符串)未定义类型GPSYesOrNo' – user1352057 2013-03-11 23:46:43

+0

您必须将调用与在构造函数中传递的上下文前缀。类似ctx.getSystemService()其中ctx是上下文传入。 – 2013-03-11 23:49:08

+0

Nyguyen非常感谢它正在工作。不能相信我设法得到一个简单的构造函数对象如此搞砸。再次谢谢你。 – user1352057 2013-03-12 00:09:52

4

你分配启用,不是在比较:

if(enable = true) 

将其更改为==代替,你应该是好的。就像其他人说的那样,if (enable)看起来会更干净。

更新:

随着新的信息,看来你的LocationManager为空时,你就可以调用isProviderEnabled。在调用checkStatus()之前验证它是否设置正确。

+0

好的。在我看来,你也可以这样做,“如果(启用)”更清晰和更标准,但是或者将起作用 – codeMagic 2013-03-11 20:55:24

+0

实际上,'return enable;'将是最干净的。 – 323go 2013-03-11 20:56:48

+0

@ 323go好点 – codeMagic 2013-03-11 20:58:28