1

我正在使用IntentService并通过使用获取设备的位置LocationManager。但是当我获得位置时,我的位置始终为空。为什么 ?这是我的代码

package com.example.netlogger.Services;

import java.util.ArrayList;
import java.util.Date;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

public class LocationLogService extends IntentService {

    SharedPreferences prefs;
    LocationManager lm;
    Location l;
    LocationListener ls = new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            l = location;
        }
    };

    public LocationLogService() {
        super("some name");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        Log.d("TAGG", "HERE");
        prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        lm = (LocationManager) getBaseContext().getSystemService(
                LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ls);
        l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (l != null) {
            Log.d("TAGG", "NOT NULL");
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("", "done");
        lm.removeUpdates(ls);
    }

}
4

1 回答 1

0

检查是否没有最后一个已知位置后初始化ls,然后等待它获取位置,有延迟。onHandledIntent

当您获得所需的位置时,您应该从位置管理器中删除位置侦听器。

这是我的实用程序类的要点。Locator

于 2013-04-14T05:29:39.197 回答