【发布时间】:2017-07-06 14:34:49
【问题描述】:
此服务的目的是在后台更新用户的当前位置,我不想要前台服务。然后每 50 个位置写入一个 GMX 文件。
我面临的问题是,在随机更新数次后(通常在生成 50 个位置点之前),服务无缘无故死掉,然后服务再次启动。任何时候都不会调用 onDestroy。
这是服务代码(使用 startService 启动):
public class LocationService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
private static LocationManager locationManager;
private final class ServiceHandler extends android.os.Handler{
private LocationManager locationManager;
public ServiceHandler(Looper looper){
super(looper);
}
@Override
public void handleMessage(Message msg) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
run(locationManager);
}
}
@Override
public void onCreate() {
HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
Log.i("Service","onHandleIntent lancé");
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
Log.i("Service","onHandleIntent lancé");
return START_STICKY; //permet de redémarrer le service s'il est tué
}
@Override
public void onDestroy() {
Log.i("DESTROY","IsDestroyed");
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
protected void run(LocationManager locationManager){
Log.i("Service","Service lancé");
boolean hasLocationFeature = checkLocationFeature();
if ( hasLocationFeature && (ACCESS_FINE_LOCATION == PackageManager.PERMISSION_GRANTED || ACCESS_COARSE_LOCATION == PackageManager.PERMISSION_GRANTED ) ) {
sLocation(locationManager);
}
}
protected void sLocation(LocationManager locationManagerArg){
final List<Location> locations = new ArrayList<>();
final LocationManager locationManager = locationManagerArg;
Log.i("sLocation","lancé");
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
saveNewLocation(location);
if (location != null) {
locations.add(location);
Log.i("Locationsize", String.valueOf(locations.size()));
if(locations.size()%50 == 0) {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + System.currentTimeMillis() + ".gpx");
GPXWriter(file, "test1", locations);
locations.clear();
}
}
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,0,locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,5000,0,locationListener);
}
写入GPX文件的方法没有问题。我已经在一个模拟器和两个实际设备上对此进行了测试,出现了同样的问题。它可能与内存压力无关。我的手机上有来自其他应用程序的其他 LocationService 已运行超过 100 小时。
为什么这个服务会死掉,我该怎么办? 谢谢
【问题讨论】: