我正在使用android studio创建一个应用程序,并在一个欢迎的弹出对话框中,我希望应用程序获得用户的位置,所以我编写了代码,但为什么它找不到我的位置。为什么?!?我正在努力工作几天。这是我的代码
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private TextView addressField;
private LocationManager locationManager;
private String provider;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
addressField = (TextView) findViewById(R.id.TextView05);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
Log.d("SomeTag", provider);
Log.d("SomeTag", String.valueOf(locationManager.isProviderEnabled(provider)));
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Please wait for location update...");
longitudeField.setText("Please wait for location update...");
addressField.setText("Please wait for location update...");
}
}
@Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
@Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
@Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
StringBuilder builder = new StringBuilder();
try {
List<Address> address = geoCoder.getFromLocation(lat, lng, 1);
int maxLines = address.get(0).getMaxAddressLineIndex();
for (int i=0; i<maxLines; i++) {
String addressStr = address.get(0).getAddressLine(i);
builder.append(addressStr);
builder.append(" ");
}
String fnialAddress = builder.toString();
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
addressField.setText(fnialAddress);
} catch (IOException e) {}
catch (NullPointerException e) {}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
你可以帮我找出什么问题吗?
即使它更简单,我只需要应用程序知道我居住的地方(我的意思是城市)
答案 0 :(得分:1)
你是否写了许可
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
并使用真实手机
或者通过ddms为模拟器设置gps位置
答案 1 :(得分:0)
阅读有关位置策略的Android文档here。您需要为位置更新添加侦听器。 getLastKnownLocation()
应该仍然有用,但你不能依赖它。另外,您是否在模拟器上进行测试?如果你没有使用开发工具设置位置,那么你经常得到null
。