此问题与同一篇流行的stackoverflow问题直接相关,在 "Android: get current location of user without using gps or internet" 这里,被接受的答案实际上没有回答这个问题。
我应该能够通过网络提供商获取设备的当前位置名称(例如城市名称、村庄名称),而不是使用GPS或互联网。以下是该问题中被接受的答案。(下面的代码部分应包含在
我应该能够通过网络提供商获取设备的当前位置名称(例如城市名称、村庄名称),而不是使用GPS或互联网。以下是该问题中被接受的答案。(下面的代码部分应包含在
onCreate()
方法中)// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
我按照链接答案中给出的代码改变了上面的代码,但没有成功。protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView txtView = (TextView) findViewById(R.id.tv1);
txtView.setText("ayyo samitha");
////
// Acquire a reference to the system Location Manager
LocationManager locationManager;
locationManager= (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
private void makeUseOfNewLocation(Location location) {
txtView.setText("sam came in");
txtView.append(location.toString());
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {
// makeUseOfNewLocation(location);
}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
}
如何通过更正上面的代码或任何其他方法来实现我想要的目标?请注意,我想获取位置名称,而不是经纬度。有人能帮帮我吗。