我正在开发一个跟踪用户位置的应用,我已添加了近距离警报以在该特定位置执行某些操作。我使用活动练习它并且它工作正常,但在后台它不起作用。这是一个不起作用的例子。请告诉我一个解决方案,如果有人:
public class TrackLoc extends Service implements LocationListener{
LocationManager locationManager;
Location location;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
@Deprecated
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
locationManager=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
10000,
0, this);
if (locationManager != null) {
{location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
onLocationChanged(location);
}
}
答案 0 :(得分:0)
希望它会有所帮助:
public class TrackLoc extends Service implements LocationListener{
LocationManager locationManager;
Location location;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
locationManager=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
10000,
0, this);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
10000,
0, this);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onLocationChanged(Location location) {
// Do work with new location. Implementation of this method will be covered later.
Log.e("Location updated: ", "Lat: "+location.getLatitude()+" Long: "+location.getLongitude());
}
}
在此我将请求位置代码从OnStart()替换为onStartCommand(),因为onStartCommand()是在另一个组件(例如活动)通过调用startService()请求启动服务时进行的调用。一旦执行此方法,服务就会启动并可以无限期地在后台运行。如果您实现了这一点,则通过调用stopSelf()或stopService(),您有责任在工作完成后停止服务。
答案 1 :(得分:0)
如果您需要仅为接近警报跟踪他,请使用Location API
s,尤其是Geofence API
。
您无需刻录设备的电池即可追踪最多100 Geofence
个。