Java 获取用户的当前位置名称,无需使用gps或internet,而是使用android中的网络提供商
该问题与“”处的同一个普遍问题直接相关,在该问题中,接受的答案实际上没有回答该问题 我应该能够通过网络提供商而不是GPS或互联网获取设备的当前位置名称(例如:城市名称、村庄名称)。 以下是该问题的公认答案。(以下代码部分应包含在Java 获取用户的当前位置名称,无需使用gps或internet,而是使用android中的网络提供商,java,android,location,locationmanager,Java,Android,Location,Locationmanager,该问题与“”处的同一个普遍问题直接相关,在该问题中,接受的答案实际上没有回答该问题 我应该能够通过网络提供商而不是GPS或互联网获取设备的当前位置名称(例如:城市名称、村庄名称)。 以下是该问题的公认答案。(以下代码部分应包含在onCreate()方法中) 我将链接答案中给出的上述代码更改如下,但没有成功 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
onCreate()
方法中)
我将链接答案中给出的上述代码更改如下,但没有成功
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);
}
}
如何通过更正上述代码或任何其他方法来实现我想要的?请注意,我想获得位置名称,但不是经度和纬度。有人能帮帮我吗。根据android文档,使用
LocationManager
不是当前推荐的API(请参阅):
要了解如何设置Google Services客户端库,请参阅《Google Play Services指南》中的
将Google Services客户端库链接到应用程序后,您可以使用FusedLocationProviderApi实现用户位置:
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends ActionBarActivity
implements ConnectionCallbacks, OnConnectionFailedListener {
// ..
private GoogleApiClient mGoogleAPIClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create google api client object
mGoogleAPIClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
@Override
protected void onStart() {
super.onStart();
mGoogleAPIClient.connect();
}
@Override
protected void onStop() {
super.onStop();
mGoogleAPIClient.disconnect();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this,
"Could not connect to Google Play Services",
Toast.LENGTH_SHORT).show();
finish();
}
@Override
public void onConnected(Bundle bundle) {
Log.i(TAG,
"Successfuly connect to Google Play Services");
// retrieve last location once connected
Location lastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleAPIClient);
if (lastLocation == null) {
// should request new one
// location should be enabled
Log.i(TAG,
"No location data previously acquired.. should request!");
Toast.makeText(this,
"Requesting location data ..",
Toast.LENGTH_SHORT).show();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(5000);
PendingResult<Status> result = LocationServices.FusedLocationApi
.requestLocationUpdates(mGoogleAPIClient,
locationRequest,
new LocationListener() {
@Override
public void onLocationChanged(Location location) {
makeUseOfNewLocation(location);
}
});
// TODO: use result to retrieve more info
} else {
makeUseOfNewLocation(lastLocation);
}
}
@Override
public void onConnectionSuspended(int i) {
}
private void makeUseOfNewLocation(Location location) {
// do your stuff here
}
导入android.location.location;
导入android.os.Bundle;
导入android.support.v7.app.ActionBarActivity;
导入android.util.Log;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.widget.Toast;
导入com.google.android.gms.common.ConnectionResult;
导入com.google.android.gms.common.api.GoogleAppClient;
导入com.google.android.gms.common.api.GoogleAppClient.ConnectionCallbacks;
导入com.google.android.gms.common.api.GoogleAppClient.OnConnectionFailedListener;
导入com.google.android.gms.common.api.pendingreult;
导入com.google.android.gms.common.api.ResultCallback;
导入com.google.android.gms.common.api.Status;
导入com.google.android.gms.location.FusedLocationProviderApi;
导入com.google.android.gms.location.LocationListener;
导入com.google.android.gms.location.LocationRequest;
导入com.google.android.gms.location.LocationServices;
公共类MainActivity扩展了ActionBarActivity
实现ConnectionCallbacks、OnConnectionFailedListener{
// ..
私人GoogleapClient MGoogleapClient;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//创建google api客户端对象
mgoogleapclient=新的Googleapclient.Builder(此)
.addApi(LocationServices.API)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.build();
}
@凌驾
受保护的void onStart(){
super.onStart();
mGoogleAPIClient.connect();
}
@凌驾
受保护的void onStop(){
super.onStop();
mGoogleAPIClient.disconnect();
}
@凌驾
公共无效onConnectionFailed(ConnectionResult ConnectionResult){
Toast.makeText(这个,
“无法连接到Google Play服务”,
吐司。长度(短)。show();
完成();
}
@凌驾
未连接的公共空间(捆绑包){
Log.i(标签,
“成功连接到Google Play服务”);
//连接后检索最后一个位置
Location lastLocation=LocationServices.FusedLocationApi
.getLastLocation(MGoogleapClient);
if(lastLocation==null){
//你应该申请新的
//应启用位置
Log.i(标签,
“以前未获取位置数据..应请求!”);
Toast.makeText(这个,
“正在请求位置数据…”,
吐司。长度(短)。show();
LocationRequest LocationRequest=LocationRequest.create();
locationRequest.setPriority(locationRequest.PRIORITY\u高精度);
位置请求设置间隔(5000);
Pendingreult结果=LocationServices.FusedLocationApi
.RequestLocationUpdate(mgoogleapClient,
位置请求,
新位置侦听器(){
@凌驾
已更改位置上的公共无效(位置){
使用新位置(位置);
}
});
//TODO:使用结果检索更多信息
}否则{
使用新位置(最后位置);
}
}
@凌驾
公共空间连接暂停(int i){
}
私有void makeUseOfNewLocation(位置){
//在这里做你的事
}
我已经测试了上面的代码,它可以在没有internet连接的情况下工作,但它要求用户在设备上启用位置功能。它还要求用户已经在位置功能中启用了位置历史功能
希望这能对您有所帮助。问题是您尝试的代码确实有效,可能只是没有您希望的那么好。例如,三星Galaxy S3上的这种方法提供的精度是2000米,这意味着实际位置在半径为2公里的圆内的任何地方。此外,可能需要对locat进行相当大的更改在你的应用程序被告知位置改变之前,ion会被告知,因为误差太大了 GPS或
定位请求。获得合理的位置需要优先级\u平衡\u功率\u精度
(如果使用Google Play Services)。这确实需要android。权限。访问\u精细位置
,但除非您只需要公里级别
The Google Play services location APIs are preferred over the
Android framework location APIs (android.location) as a way of
adding location awareness to your app.
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends ActionBarActivity
implements ConnectionCallbacks, OnConnectionFailedListener {
// ..
private GoogleApiClient mGoogleAPIClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create google api client object
mGoogleAPIClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
@Override
protected void onStart() {
super.onStart();
mGoogleAPIClient.connect();
}
@Override
protected void onStop() {
super.onStop();
mGoogleAPIClient.disconnect();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this,
"Could not connect to Google Play Services",
Toast.LENGTH_SHORT).show();
finish();
}
@Override
public void onConnected(Bundle bundle) {
Log.i(TAG,
"Successfuly connect to Google Play Services");
// retrieve last location once connected
Location lastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleAPIClient);
if (lastLocation == null) {
// should request new one
// location should be enabled
Log.i(TAG,
"No location data previously acquired.. should request!");
Toast.makeText(this,
"Requesting location data ..",
Toast.LENGTH_SHORT).show();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(5000);
PendingResult<Status> result = LocationServices.FusedLocationApi
.requestLocationUpdates(mGoogleAPIClient,
locationRequest,
new LocationListener() {
@Override
public void onLocationChanged(Location location) {
makeUseOfNewLocation(location);
}
});
// TODO: use result to retrieve more info
} else {
makeUseOfNewLocation(lastLocation);
}
}
@Override
public void onConnectionSuspended(int i) {
}
private void makeUseOfNewLocation(Location location) {
// do your stuff here
}
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends Activity implements
com.google.android.gms.location.LocationListener, ConnectionCallbacks,
OnConnectionFailedListener {
private final FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi;
private GoogleApiClient mGoogleAPIClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleAPIClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
}
@Override
protected void onResume() {
super.onResume();
mGoogleAPIClient.connect();
}
@Override
protected void onPause() {
super.onPause();
if (mGoogleAPIClient != null) {
mGoogleAPIClient.disconnect();
}
}
@Override
public void onConnected(Bundle arg0) {
final LocationRequest locationRequest = LocationRequest.create();
locationRequest
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
fusedLocationProviderApi.requestLocationUpdates(mGoogleAPIClient,
locationRequest, this);
}
@Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location location) {
// the location is no more than 10 min old, and with reasonable
// accurarcy (50m), done
if (System.currentTimeMillis() < location.getTime() + 10 * 60 * 1000
&& location.getAccuracy() < 50) {
mGoogleAPIClient.disconnect();
mGoogleAPIClient = null;
((TextView) findViewById(R.id.test)).setText(location.toString());
}
}
}
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
public AppLocationService(Context context) {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class AndroidLocationActivity extends Activity {
Button btnGPSShowLocation;
Button btnNWShowLocation;
AppLocationService appLocationService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appLocationService = new AppLocationService(
AndroidLocationActivity.this);
btnGPSShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);
btnGPSShowLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Location gpsLocation = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation != null) {
double latitude = gpsLocation.getLatitude();
double longitude = gpsLocation.getLongitude();
Toast.makeText(
getApplicationContext(),
"Mobile Location (GPS): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
} else {
showSettingsAlert("GPS");
}
}
});
btnNWShowLocation = (Button) findViewById(R.id.btnNWShowLocation);
btnNWShowLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Location nwLocation = appLocationService
.getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
double latitude = nwLocation.getLatitude();
double longitude = nwLocation.getLongitude();
Toast.makeText(
getApplicationContext(),
"Mobile Location (NW): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
} else {
showSettingsAlert("NETWORK");
}
}
});
}
public void showSettingsAlert(String provider) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
AndroidLocationActivity.this);
alertDialog.setTitle(provider + " SETTINGS");
alertDialog
.setMessage(provider + " is not enabled! Want to go to settings menu?");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
AndroidLocationActivity.this.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
<!-- to get location using GPS -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- to get location using NetworkProvider -->
<uses-permission android:name="android.permission.INTERNET" />
List<Address> list = geoCoder.getFromLocation(location
.getLatitude(), location.getLongitude(), 1);
if (list != null & list.size() > 0) {
Address address = list.get(0);
result = address.getLocality();
return result;
String locale = context.getResources().getConfiguration().locale.getCountry();
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
// Will work on all networks. Only provide the SIM card's country
String countryCode = tm.getSimCountryIso();
// Might not work well on CDMA networks. Will provide the country code
// for the country the device is currently in.
String currentCountryCode = tm.getNetworkCountryIso();