【问题标题】:requestLocationUpdates errorrequestLocationUpdates 错误
【发布时间】:2016-03-17 12:22:42
【问题描述】:

请问我的代码有问题:

import android.Manifest;
import android.content.Context;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    private GoogleMap mMap;
    private GoogleApiClient mGoogleApiClient;
    private static final int REQUEST_LOCATION = 2;
    private Location myLocation;
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
    public static final String TAG = MapsActivity.class.getSimpleName();
    private LocationRequest mLocationRequest;
    protected LocationManager locationManager;
    protected LocationListener locationListener;
    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }

        mGoogleApiClient.connect();


        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    REQUEST_LOCATION);
        } else {
            // permission has been granted, continue as usual
            Location myLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        }

        if (myLocation == null) {
            Log.i(TAG, "Location services not enabled!");
        } else {
            handleNewLocation(myLocation);
        }


        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(3 * 1000)        // 3 seconds, in milliseconds
                .setFastestInterval(1 * 1000); // 1 second, in milliseconds


        locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);

        //Got aproblem with requestLocationUpdates !!!!
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 3, this);

    }


    private void handleNewLocation(Location location) {

        Log.d(TAG, location.toString());

        double currentLatitude = location.getLatitude();
        double currentLongitude = location.getLongitude();

        LatLng latLng = new LatLng(currentLatitude, currentLongitude);
        MarkerOptions options = new MarkerOptions().position(latLng).title("I am here!");

        mMap.addMarker(options);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        //handleNewLocation(myLocation);
    }


    @Override
    public void onConnected(Bundle bundle) {

        Location mLastLocation;

        Log.i(TAG, "Location services connected.");

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        }
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "Location services suspended. Please reconnect.");
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (connectionResult.hasResolution()) {
            try {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
            }
        } else {
            Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }

    @Override
    public void onLocationChanged(Location location) {

        String str = "Latitude: "+location.getLatitude()+"Longitude: "+location.getLongitude();

        Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
    }

}

正好在这部分:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 3, this);

它说无法解析该方法。我尝试了一些在这里找到的“解决方案”,但都没有奏效! 你能帮帮我吗

【问题讨论】:

    标签: android gps geolocation


    【解决方案1】:

    不要传递 this 参数;(从该活动中删除实现 LocationListener)而是这样做

    LocationListener myLocationListener= new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Log.d("dj","on location changed: "+location.getLatitude()+" & "+location.getLongitude());
                toastLocation(location);
            }
    
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
    
            }
    
            @Override
            public void onProviderEnabled(String provider) {
    
            }
    
            @Override
            public void onProviderDisabled(String provider) {
    
            }
        };
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000, 0, myLocationListener);
    
    
     private void toastLocation(final Location location){
    
        Handler handler = new Handler(Looper.getMainLooper());
    
        handler.post(new Runnable() {
    
            @Override
            public void run() {
                Toast.makeText(ServiceProvide.this.getApplicationContext(),"Location latitude: "+ location.getLatitude()
                        +"longitude: "+location.getLongitude(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    

    【讨论】:

    • 因为你的 fragmentActivity 实现了这么多回调......它可能不会这样做;我想这会有所帮助,如果 min_time 需要工作,min_distance 也必须为 0
    • 谢谢 DJphy,我没有收到错误,但是当我添加时代码仍然不起作用:locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, locationListener);
    • 不要使用 GPS_PROVIDER 而是使用 LocationManager.NETWORK_PROVIDER... 并且将最小距离设为 0 并给出一些最短时间为 2000 毫秒
    • 但要确保 GPS 已打开,并写下这样的祝酒词:@Override public void onLocationChanged(Location location) { Log.d("dj","on location changed: "+location .getLatitude()+" & "+location.getLongitude());吐司位置(位置); } 在地点改变了
    • 嗨 DJphy,谢谢您的回复。我写道: locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000, 0, locationListener);但该应用程序仍然无法运行
    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多