1
我希望找到有關檢查全天在Android上的位置(大約每15分鐘)和存儲地理座標信息。當應用程序處於後臺時也會發生這種情況,而不僅僅是當應用程序在前臺運行時。我不確定搜索條件,我似乎無法找到任何東西。任何人都可以建議搜索條件指向正確的方向嗎?Android的地理位置(如果應用程序沒有運行)
非常感謝, 凱文
編輯:
public class MyService extends Service
{
private static final String TAG = "Location";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
private class LocationListener implements android.location.LocationListener{
Location mLastLocation;
public LocationListener(String provider)
{
Log.i(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
public void onLocationChanged(Location location)
{
Log.i(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
}
public void onProviderDisabled(String provider)
{
Log.i(TAG, "onProviderDisabled: " + provider);
}
public void onProviderEnabled(String provider)
{
Log.i(TAG, "onProviderEnabled: " + provider);
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.i(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
};
@Override
public IBinder onBind(Intent arg0)
{
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.i(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
@Override
public void onCreate()
{
Log.i(TAG, "onCreate");
initializeLocationManager();
try {
Thread LocThread = new Thread(new Runnable() {
public void run() {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
}
});
try {
LocThread.join();
} catch (InterruptedException e) {
Log.i("LocationError","Thread could not join");
e.printStackTrace();
}
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.i(TAG, "gps provider does not exist " + ex.getMessage());
}
}
@Override
public void onDestroy()
{
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
Thread LocThread = new Thread(new Runnable() {
public void run() {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
});
try {
LocThread.join();
} catch (InterruptedException e) {
Log.i("LocationError","Thread could not join");
e.printStackTrace();
}
}
}
}
謝謝。我已經發現了更多關於這方面的信息,並且我嘗試了一些東西。我可以讓AlarmManager定期調用onStartCommand,但無法使位置服務正常工作。我將在原始問題中發佈我的代碼 - 如果有人能提供幫助,我將不勝感激。謝謝。 – Kevin