服务中的位置侦听器
Location Listener In Service
我的提醒程序中需要一项服务来反复检查位置,我正在使用此代码执行此操作,但在服务启动时我强制关闭了:
@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) {
}
}
每次触发 Service
时,您都必须检查 GPS 是否已启用。试试这个:
在 onStartCommand
中添加一个 GPS 检查器:
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
我的提醒程序中需要一项服务来反复检查位置,我正在使用此代码执行此操作,但在服务启动时我强制关闭了:
@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) {
}
}
每次触发 Service
时,您都必须检查 GPS 是否已启用。试试这个:
在 onStartCommand
中添加一个 GPS 检查器:
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}