我正在调查一个 android 软件中的问题,该软件在后台将设备的位置记录到日志文件中。代码是这样的:
package com.otpc.auto;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
public class LocationUpdate extends Service {
private String TAG = "LocationUpdate";
private LocationManager loc;
private class CustomLocationListener implements LocationListener {
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
public void onLocationChanged(Location location) {
writeLocationData(location);
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Location Update service has been started", Toast.LENGTH_SHORT).show();
loc = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
loc.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60 * 60 * 1000, 100,
new CustomLocationListener(),
Looper.myLooper());
loc.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60 * 60 * 1000, 100,
new CustomLocationListener(),
Looper.myLooper());
return Service.START_STICKY;
}
private void writeLocationData(Location location){
final double latitude = location.getLatitude();
final double lon = location.getLongitude();
new Thread(){
public void run() {
try {
FileOutputStream latitudeFile = new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/latitude.txt");
latitudeFile.write(String.valueOf(latitude).getBytes());
latitudeFile.close();
FileOutputStream longitudeFile = new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/longitude.txt");
longitudeFile.write(String.valueOf(lon).getBytes());
longitudeFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
};
}.start();
}
}
将此注册为启动服务后,其他应用程序将无法再使用 GPS 服务。使用 GPS Tester 应用程序测试 GPS 会得到与设备没有 GPS 一样的结果。只有在我们从设备中删除此应用程序后,GPS 才能恢复正常运行。
上面的代码有什么问题。我不是 Android 专家,但据我所知,我无法在代码中发现任何异常。
谢谢。