0

我正在制作一个小测试程序来掌握 Android GPS 的窍门,看看电池对学校项目的影响。我只是想让我的设备通过打印出最后检测到的已知位置的纬度来检测我的位置。但该位置始终在 onResume() 回调中返回 null。

任何帮助是极大的赞赏。

TextView Updates;
long start = -1;
long battStart = -1;
long stop = -1;
PowerManager.WakeLock wl;
LocationManager locationManager; 
LocationListener locationListener;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Updates = (TextView) findViewById(R.id.textView);
    Updates.append("\n onCreate()");

    batteryLevel();
    start = System.currentTimeMillis(); 

    locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
    locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
          // Called when a new location is found by the network location provider.
          Updates.append("\n Found a place! "+location.getLatitude()+","+location.getLongitude());
        }
        public void onStatusChanged(String provider, int status, Bundle extras) {}
        public void onProviderEnabled(String provider) {
            Updates.append("yes"+provider);
        }
        public void onProviderDisabled(String provider) {
            Updates.append("No"+provider);
        }
    }; 
}

protected void onStart() {
    super.onStart();
    Updates.append("\n onStart()");

    // Set up a wake lock 
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    this.wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag2");
    this.wl.acquire();

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}


protected void onResume() {
    super.onResume();
    batteryLevel();
    Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (loc != null) {
        Updates.append(String.valueOf(loc.getLatitude()));
    } else {
        Updates.append("loc is null");
    }
}
4

3 回答 3

2

我想到了!

原来,我只好出去了:)

于 2012-06-18T19:34:36.227 回答
1

如果 GPS 被禁用,它将始终返回 null。有关LocationManager.getLastKnownLocation的信息,请参阅 Android 文档

于 2012-06-18T19:24:11.790 回答
0

在这种情况下,您应该使用 LocationListener。因为它可能会发生,您可能无法从 getLastKnownLocation() 获取位置。

只需调用 requestLocationUpdates 您将在 LocationListener 中获得回调

于 2012-06-18T19:26:13.820 回答