在手机上获取当前位置,不起作用? [安卓]

Posted

技术标签:

【中文标题】在手机上获取当前位置,不起作用? [安卓]【英文标题】:Getting current location on phone, not working? [Android] 【发布时间】:2016-08-05 19:52:39 【问题描述】:

到目前为止。它应该在两个单独的文本视图中将当前位置显示为纬度和经度。

我已经在模拟器和真正的 android 手机上尝试过,但两者都不起作用。没有任何反应,文本视图不显示任何坐标。也没有错误。

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 开发者指南。

您有什么想法或建议吗?

感谢您的任何意见。

【问题讨论】:

您需要使用Log.d 来识别哪一行代码不能正常工作。一旦你找到一个意想不到或没有价值的点,然后发布问题。所以在每一行后面加上一个Log.d 语句。如果您不弄清楚到底是什么不起作用,就要求浪费他们的时间是没有意义的。 【参考方案1】:

根据我的经验,模拟器不适用于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定义一个字符串值

最后,检查设备或模拟器是否已授予位置权限。转到“设置”->“应用程序”并检查该应用程序是否正在使用定位服务。如果没有,请点击“权限”并打开服务。

【讨论】:

嗨,欢迎来到 SO。发布时,请在发布代码时使用代码格式标记 - 请参阅指南***.com/editing-help#code。快乐的黑客攻击!【参考方案2】:

创建一个类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();

【讨论】:

以上是关于在手机上获取当前位置,不起作用? [安卓]的主要内容,如果未能解决你的问题,请参考以下文章

安卓webview dom元素的scrollTo方法不起作用

react-slick 有问题。在手机上滑动不起作用

位置服务关闭和打开时地理定位不起作用

OneSignal:推送通知不起作用

为啥overflow-x:clip 在移动浏览器上不起作用

加速度计服务在 Android TV Box 上不起作用