Java 在 Android Studio 应用中获取当前位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33415033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting current location in Android Studio app
提问by RayzaN
I am developing my first Android app which should get the latitudeand longitudeof an android device and send it via a web service to a template document.
我正在开发我的第一个 Android 应用程序,它应该获取Android 设备的纬度和经度,并通过 Web 服务将其发送到模板文档。
I followed the guide of getting the location from http://developer.android.com/training/location/retrieve-current.html.
我按照从http://developer.android.com/training/location/retrieve-current.html获取位置的指南进行操作。
This is the code from my .java class:
这是我的 .java 类中的代码:
import android.content.Context;
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.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
public class GetLocation extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
EditText textLat;
EditText textLong;
EditText lat;
EditText lon;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.get_location);
textLat = (EditText) findViewById(R.id.latitude);
textLong = (EditText) findViewById(R.id.longitude);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
private boolean isGPSEnabled() {
LocationManager cm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return cm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
@Override
public void onConnected(Bundle bundle) {
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
lat.setText(String.valueOf(mLastLocation.getLatitude()));
lon.setText(String.valueOf(mLastLocation.getLongitude()));
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public void onButtonClick(View v){
if(v.getId() == R.id.getGpsLocation){
if(!isGPSEnabled()){
new AlertDialog.Builder(this)
.setMessage("Please activate your GPS Location!")
.setCancelable(false)
.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
})
.setNegativeButton("Cancel", null)
.show();
} else {
textLat.setText(String.valueOf(lat));
textLong.setText(String.valueOf(lon));
}
}
}
}
I don't get any errors but when I am tapping the button which should get the coordinates, I get 'null' text in both views.
我没有收到任何错误,但是当我点击应该获取坐标的按钮时,我在两个视图中都得到了“空”文本。
I also have included permissions for internet, access fine and coarse location.
我还包括了互联网的权限,访问精细和粗略的位置。
Thanks in advance!
提前致谢!
回答by KishuDroid
You need to define LocationListener .
您需要定义 LocationListener 。
public class MainActivity extends Activity implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
@Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
@Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
@Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}
And need to give below permission :
并需要给予以下许可:
ACCESS_COARSE_LOCATION: It is used when we use network location provider for our Android app.
ACCESS_COARSE_LOCATION:当我们为我们的 Android 应用程序使用网络位置提供程序时使用它。
ACCESS_FINE_LOCATION: It is providing permission for both providers.
ACCESS_FINE_LOCATION:它为两个提供者提供许可。
INTERNET: permission is must for the use of network provider.
INTERNET: 使用网络提供商必须获得许可。
回答by Keith
Here is a working example of user location:
这是用户位置的工作示例:
https://github.com/keithweaver/Android-Samples/tree/master/Location
https://github.com/keithweaver/Android-Samples/tree/master/Location
回答by Parsania Hardik
我在deviluts.com上写了详细的教程,涵盖了这个主题。你可以在这里找到更多的描述,也可以下载整个演示源代码以更好地理解。
First of all, put this in gradle file
首先,把它放在gradle文件中
compile 'com.google.android.gms:play-services:9.0.2'
then implement necessary interfaces
然后实现必要的接口
public class MainActivity extends BaseActivitiy implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener
declare instances
声明实例
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationManager locationManager;
private LocationRequest mLocationRequest;
put this in onCreate()
把这个放进去 onCreate()
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
At last, override necessary methods
最后,覆盖必要的方法
@Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
} startLocationUpdates();
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLocation == null){
startLocationUpdates();
}
if (mLocation != null) {
double latitude = mLocation.getLatitude();
double longitude = mLocation.getLongitude();
} else {
// Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
}
}
protected void startLocationUpdates() {
// Create the location request
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL);
// Request location updates
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
Log.d("reque", "--->>>>");
}
@Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection Suspended");
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}
@Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
public void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
@Override
public void onLocationChanged(Location location) {
}
Don't forget to start GPS in your device before running app.
在运行应用程序之前,不要忘记在您的设备中启动 GPS。