NETWORK_PROVIDER和GPS_PROVIDER在片段中返回null

时间:2014-11-26 07:04:54

标签: android locationmanager

我面临的问题

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;
    }
}

1 个答案:

答案 0 :(得分:0)

而不是appLocationService = new AppLocationService(getActivity());

使用:

Context mcontext;      
appLocationService = new AppLocationService(mContext);

另请检查您是否在清单文件中提供了互联网权限