LocationManager getProviders(true)不返回提供者

时间:2012-04-09 08:27:43

标签: android broadcastreceiver locationmanager

好的,基本上我想开始从BroadcastReceiver开始监听单个更新,并且出于某种原因,我的访问权限禁用了所有提供商。这是代码段

LocationManager locationManager = (LocationManager)
                            context.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_LOW);
String majorProvider = locationManager.getBestProvider(criteria, true);
Log.d("location test", "major provider " + majorProvider);
List<String> allProviders = locationManager.getAllProviders();
for(int i=0; i < allProviders.size();i++) {
    Log.d("location test", "provider " + i + ": " + allProviders.get(i));
}
Log.d("location test", "enabled...");
allProviders = locationManager.getProviders(true);
for(int i=0; i < allProviders.size();i++) {
    Log.d("location test", "enabled provider " + i + ": " + allProviders.get(i));
}

和我的logcat结果

04-09 11:23:35.763: D/location test(32576): major provider null
04-09 11:23:35.763: D/location test(32576): provider 0: network
04-09 11:23:35.763: D/location test(32576): provider 1: passive
04-09 11:23:35.763: D/location test(32576): provider 2: gps
04-09 11:23:35.763: D/location test(32576): enabled...

我猜测问题是我从BroadcastReceiver调用所有这些,但我尝试从其他地方传递上下文。是否无法从BroadcastReceiver

访问LocationManager

2 个答案:

答案 0 :(得分:6)

哇我觉得自己像个白痴。好吧,这只是一个许可问题。如果有人再次遇到此问题,那么只需将使用权限添加到清单

即可
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

答案 1 :(得分:0)

好吧,除了清单中的权限声明外,您可能还需要手动询问用户与位置相关的权限。并在授予权限后,呼叫getProviders| getBestProvider

String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};    
ActivityCompat.requestPermissions(this, perms, REQ_LOCATION_PERMISSION);