到目前为止。它应该在两个单独的文本视图中显示当前位置作为纬度和经度。
我已经在模拟器和真正的Android手机上尝试了这个,它也不起作用。没有任何反应,textviews会显示任何坐标。也没有错误。
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final int LOCATION_REQUEST_INTERVAL = 60000;
private static final int LOCATION_REQUEST_FASTEST = 15000;
private static final int MY_PERMISSION_REQUEST_READ_COARSE_LOCATION = 102;
private TextView latitudeTextView;
private TextView longitudeTextView;
private ImageButton imageButton;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi;
private double mLatitude;
private double mLongitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latitudeTextView = (TextView) findViewById(R.id.latitudeTextView);
longitudeTextView = (TextView) findViewById(R.id.longitudeTextView);
imageButton = (ImageButton) findViewById(R.id.imageButton);
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
locationRequest = new LocationRequest();
locationRequest.setInterval(LOCATION_REQUEST_INTERVAL);
locationRequest.setFastestInterval(LOCATION_REQUEST_FASTEST);
locationRequest.setPriority(locationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
@Override
public void onConnected(@Nullable Bundle bundle) {
requestLocationUpdates();
}
private void requestLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSION_REQUEST_READ_COARSE_LOCATION);
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
latitudeTextView.setText(String.valueOf(mLatitude));
longitudeTextView.setText(String.valueOf(mLongitude));
}
@Override
protected void onStart() {
super.onStart();
googleApiClient.connect();
}
@Override
protected void onStop() {
super.onStop();
googleApiClient.disconnect();
}
@Override
protected void onResume() {
super.onResume();
if(googleApiClient.isConnected())
requestLocationUpdates();;
}
@Override
protected void onPause() {
super.onPause();
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient,this);
}
}
为什么不起作用?我遵循了一些指南,其中一个是Android开发人员指南。
您有任何想法或建议吗?
感谢任何输入。
答案 0 :(得分:3)
创建一个GpsTracker.java类:
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1000; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 100000 * 60 * 1; // 5 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
//isGPSEnabled = locationManager
//.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
//showSettingsAlert();
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
else {
if(isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
System.exit(0);
}
});
// Showing Alert Message
alertDialog.show();
}
@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;
}
}
现在您可以获取GpsTracker.java的位置创建实例,如:
GPSTracker gpstracker=new GPSTracker(EditProfile.this);
double lat=gpstracker.getLatitude();
double longitude=gpstracker.getLongitude();
答案 1 :(得分:3)
根据我的经验,模拟器不适用于PRIORITY_BALANCED_POWER_ACCURACY
,但需要PRIORITY_HIGH_ACCURACY
。
更改代码行
locationRequest.setPriority(locationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
到
LocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
我还注意到权限请求对话框仅授予粗略位置的权限。我会把它改成好位置。更改代码行:
new String[] Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_REQUEST_READ_COARSE_LOCATION);
到
requestPermissions(new
String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSION_REQUEST_FINE_LOCATION);
并为MY_PERMISSION_REQUEST_FINE_LOCATION
最后,检查是否已在设备或模拟器上授予位置权限。转到“设置” - > 'apps'并检查该应用是否正在使用位置服务。如果没有,请单击“权限”并启用该服务。