我正在調查一個android軟件的問題,在後臺將設備的位置記錄到日誌文件中。該代碼是這樣的:onStartCommand中的requestLocationUpdates導致GPS停止響應?
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的專家,但從我所看到的,我無法發現代碼中的任何異常。
謝謝。