NETWORK_PROVIDER 和 GPS_PROVIDER 在片段中返回 null
Posted
技术标签:
【中文标题】NETWORK_PROVIDER 和 GPS_PROVIDER 在片段中返回 null【英文标题】:NETWORK_PROVIDER and GPS_PROVIDER returns null in fragments 【发布时间】:2014-11-26 07:04:53 【问题描述】:我面临的问题
nwLocation
& gpsLocation
在 onStart()
处为空
我有清单
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
FrgAddNewJobsLocation.java(类扩展片段)
@Override
public void onStart()
super.onStart();
initilizeMap();
appLocationService = new AppLocationService(getActivity());
nwLocation = appLocationService.getLocation(LocationManager.NETWORK_PROVIDER);
gpsLocation = appLocationService.getLocation(LocationManager.GPS_PROVIDER);
AppLocationService.java
public class AppLocationService extends Service implements LocationListener
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
public AppLocationService(Context context)
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
public Location getLocation(String provider)
if (locationManager.isProviderEnabled(provider))
locationManager.requestLocationUpdates(provider, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null)
location = locationManager.getLastKnownLocation(provider);
return location;
return null;
@Override
public void onLocationChanged(Location location)
@Override
public void onProviderDisabled(String provider)
@Override
public void onProviderEnabled(String provider)
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
@Override
public IBinder onBind(Intent arg0)
return null;
【问题讨论】:
如果你把它们放在onActivityCreted里呢? 这可能看起来很傻,但设备上是否启用了位置设置? 【参考方案1】:而不是appLocationService = new AppLocationService(getActivity());
使用:
Context mcontext;
appLocationService = new AppLocationService(mContext);
还要检查您是否在清单文件中提供了互联网权限
【讨论】:
以上是关于NETWORK_PROVIDER 和 GPS_PROVIDER 在片段中返回 null的主要内容,如果未能解决你的问题,请参考以下文章
使用 GPS_PROVIDER 和 NETWORK_PROVIDER 获取当前位置的问题
NETWORK_PROVIDER 和 GPS_PROVIDER 在片段中返回 null
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) 使用 Wi-Fi 总是返回 false
当 gps 关闭时,.isProviderEnabled(LocationManager.NETWORK_PROVIDER) 总是返回 false?