我正在尝试学习如何获取Android设备的当前坐标,并且我有以下代码:
package com.example.pruebageolocalizacion;
import java.util.List;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager locManager = (LocationManager)getSystemService(LOCATION_SERVICE);
List<String> listaProviders = locManager.getAllProviders();
for(int i=0;i<listaProviders.size();i++) {
Toast.makeText(getApplicationContext(),listaProviders.get(i).toString(),Toast.LENGTH_LONG).show();
}
if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Toast.makeText(getApplicationContext(), "GPS DESACTIVADO",Toast.LENGTH_LONG).show();
}
else {
Location ultimaLocalizacion = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(ultimaLocalizacion!=null) {
double ultimaLatitud = ultimaLocalizacion.getLatitude();
double ultimaLongitud = ultimaLocalizacion.getLongitude();
Toast.makeText(getApplicationContext(), "Ultma latitud: " + ultimaLatitud ,Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Ultma longitud: " + ultimaLongitud ,Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Ultma localizacion es null",Toast.LENGTH_LONG).show();
LocationListener locListener = new LocationListener() {
public void onLocationChanged(Location location) {
Toast.makeText(getApplicationContext(), "Ultma latitud: " + String.valueOf(location.getLatitude()) ,Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Ultma longitud: " + String.valueOf(location.getLongitude()) ,Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Precision: " + String.valueOf(location.getAccuracy()) ,Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String provider){
Toast.makeText(getApplicationContext(), "GPS DESACTIVADO",Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String provider){
Toast.makeText(getApplicationContext(), "GPS ACTIVADO",Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras){
Toast.makeText(getApplicationContext(), "Status del proveedor" + status,Toast.LENGTH_LONG).show();
}
};
Toast.makeText(getApplicationContext(), "A",Toast.LENGTH_LONG).show();
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, locListener);
Toast.makeText(getApplicationContext(), "B",Toast.LENGTH_LONG).show();
}
}
}
}
我在Android虚拟设备和手机中都尝试了这些,这些是我在屏幕上可以看到的消息:
“网络”,“被动”,“gps”,“Ultma localizacion es null”,“A”,“B”,
我在两台设备上都启用了WIFI和GPS。而且我多次使用手机的GPS。那么,ultimaLocalizacion不应该与null不同吗?
另外,如果ultimaLocalizacion为空,为什么它不会每三秒向我显示纬度,经度和准确度?
非常感谢。