Android 如何在后台使用GPS连续跟踪定位
我正在开发一个应用程序,它将跟踪用户的位置,并且我添加了接近警报,以便在该特定位置执行一些操作。我练习了这个使用活动,效果很好,但在后台它不起作用。下面是一个例子,它不起作用。如果任何人有以下问题,请告诉我解决方案:Android 如何在后台使用GPS连续跟踪定位,android,Android,我正在开发一个应用程序,它将跟踪用户的位置,并且我添加了接近警报,以便在该特定位置执行一些操作。我练习了这个使用活动,效果很好,但在后台它不起作用。下面是一个例子,它不起作用。如果任何人有以下问题,请告诉我解决方案: public class TrackLoc extends Service implements LocationListener{ LocationManager locationManager; Location location; @Overri
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);
}
}
希望这将有助于:
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(),因为当另一个组件(如活动)通过调用startService()请求启动服务时,onStartCommand()被调用。一旦执行此方法,服务就会启动,并且可以无限期地在后台运行。如果您实现了这一点,则您有责任在服务完成后通过调用stopSelf()或stopService()停止服务。如果您需要仅为接近警报跟踪他,请使用,尤其是。
您可以在不烧掉设备电池的情况下跟踪多达100个
Geofence
s。访问官方文档请添加解释或对解决方案进行评论,而不仅仅是代码