位置监听器在服务中

时间:2015-10-21 19:47:13

标签: android service location

我需要在提醒程序中提供一项服务来反复检查位置,并且我使用此代码执行此操作但是在服务启动时我会强行关闭:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    ll = new Mylocationlistener();
    checkPermission("android.permission.ACCESS_FINE_LOCATION",1,0);
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
    return START_STICKY;
}

private class Mylocationlistener implements LocationListener {
    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            Toast.makeText(getBaseContext(), "Location changed" + location.getLatitude() + location.getLongitude(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}

1 个答案:

答案 0 :(得分:0)

每次触发Service时,您都必须检查GPS是否已启用。试试这个: 在onStartCommand中,添加GPS检查器:

if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}