无法接收GPS更新

时间:2014-11-20 11:46:33

标签: android gps

这是我的代码。该应用程序非常简单,我所做的只是初始化一个地图,并尝试将活动(实现LocationListener)注册到LocationManager更新。由于某种原因,currentLocation保持为null ...请帮助吗?

public class LocationActivity extends FragmentActivity implements LocationListener{

    //Map Variables
    private GoogleMap mMap; // Might be null if Google Play services APK is not available.
    private int DEFAULT_ZOOM = 17;
    private int DEFAULT_MAP_STYLE = GoogleMap.MAP_TYPE_NORMAL;
    private Marker currentMarker = null;
    private GroundOverlay currentDebrisPic = null;

    //General Variables
    private String LOCATION_TAG = "LocationActivity";

    //Location Variables
    private LocationManager locationManager = null;
    private String locationProvider = "";
    private Location currentLocation = null;
    private int LOCATION_UPDATES_TIME_INTERVAL = 2000; //Time between two location updates
    private int LOCATION_UPDATES_DISTANCE_INTERVAL = 3;

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

        setLocationServices();
        //initializeCamera();
    }

    protected void initializeCamera(){
        //Make the Initialization small window visible
        TextView initializationTextView = (TextView)findViewById(R.id.InitializationTextView);
        ProgressBar initializationProgressBar = (ProgressBar)findViewById(R.id.InitializationProgressBar);
        initializationTextView.setVisibility(View.VISIBLE);
        initializationProgressBar.setVisibility(View.VISIBLE);

        //As progress bar advances,
        for(int i = 1; i <= DEFAULT_ZOOM; i++){
            CameraUpdate cameraUpdate = getMoveCameraUpdate(currentLocation, i);
            mMap.moveCamera(cameraUpdate);

            //for(int j = 0; j < 400000; j++);
            initializationProgressBar.setProgress((100/DEFAULT_ZOOM) * i);
        }

        //After zooming is done, make the progress bar invisible again
        initializationProgressBar.setVisibility(View.INVISIBLE);
        initializationTextView.setVisibility(View.INVISIBLE);

        addMarkerAtCurrentLocation();
    }

    //Generates and returns a new CameraUpdate containing the new position of the camera with zoom 0 and bearing 0;
    private CameraUpdate getMoveCameraUpdate(Location location, int zoom){
        LatLng newLocation = new LatLng(location.getLatitude(),location.getLongitude());
        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(newLocation, zoom, 0, 0));
        return cameraUpdate;
    }

    //Add marker at current location
    protected void addMarkerAtCurrentLocation(){
        if(null != currentMarker)
            currentMarker.remove();
        currentMarker = mMap.addMarker(new MarkerOptions()
                            .position(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()))
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.locationmarker))
                            .title("Your location"));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.location_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //If the item titled "Home Menu" was pressed
        if(id == R.id.LocationToHome) {
            try {
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                finish();
                Log.d(LOCATION_TAG, "Successfully moved from localization to home menu");
            }
            catch (Exception ex){
                Log.e(LOCATION_TAG, "Can't move to Home Menu\n" + ex.getMessage());
            }
        }
        //If the item titled "Change map type" was pressed,
        else if(id == R.id.MapTypeChange){
            //Current map is Normal type and should be changed to Hybrid
            if(mMap.getMapType() == GoogleMap.MAP_TYPE_NORMAL){
                mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                item.setTitle("Normal map");
            }
            //Current map is Hybrid type and should be changed to Normal
            else if(mMap.getMapType() == GoogleMap.MAP_TYPE_HYBRID){
                mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                item.setTitle("Hybrid map");
            }
            Log.d(LOCATION_TAG, "Map type changed successfully");

        }
        //Default item in the menu
        else if(id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        locationManager.requestLocationUpdates(locationProvider, LOCATION_UPDATES_TIME_INTERVAL, LOCATION_UPDATES_DISTANCE_INTERVAL, this);
        addMarkerAtCurrentLocation();
    }

    @Override
    protected void onStop(){
        super.onStop();
        //To save battery, location updates are not necessary when the map isn't currently showed. When onResume is called,
        //the LocationManager is requested to re-set the updates.
        locationManager.removeUpdates(this);
    }


    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     * <p>
     * This should only be called once and when we are sure that {@link #mMap} is not null.
     */
    private void setUpMap() {
        //Default map type is Hybrid, can be changed in the menu
        mMap.setMapType(DEFAULT_MAP_STYLE);

        //Auto zoom to a resolution of a few houses, additional zoom can be done manually
        CameraUpdate cameraUpdate = CameraUpdateFactory.zoomTo(12);
        mMap.animateCamera(cameraUpdate);

        //Receive the current location and zoom onto it
    }

    protected void setLocationServices(){
        //Try to open a location service and check if GPS is available. If not, open the GPS settings so that the
        //user will be able to enable it manually.
        locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
        boolean locationEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        if (!locationEnabled) {
            //Alert!
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }

        //Choose best location provider by criteria, when initialized with empty constructor
        // gives the best criteria available
        Criteria criteria = new Criteria();
        locationProvider = locationManager.getBestProvider(criteria, false);
        try {
            Location location = locationManager.getLastKnownLocation(locationProvider);
            onLocationChanged(location);
            if(null != location) {
                Log.d(LOCATION_TAG, "Location successfully obtained from provider");
                onLocationChanged(location);
            }
            else {
                Log.d(LOCATION_TAG, "getLastKnownLocation failed");
            }
        }
        catch (Exception ex){
            Log.e(LOCATION_TAG, "Can't obtain location\n" + ex.getMessage());
        }
        locationManager.requestLocationUpdates(locationProvider, LOCATION_UPDATES_TIME_INTERVAL, LOCATION_UPDATES_DISTANCE_INTERVAL, this);
    }

    //Called when the location provider updates the current location
    @Override
    public void onLocationChanged(Location newLocation){
        try {
            currentLocation = newLocation;
            Log.d(LOCATION_TAG, "Location successfully assigned to currentLocation");

            //Move marker to current location
            addMarkerAtCurrentLocation();
            //Log.d(LOCATION_TAG, "Marker added successfully");
        }
        catch (Exception ex){
            Log.e(LOCATION_TAG, "Can't assign new location to currentLocation\n" + ex.getMessage());
        }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        switch(status){
            case LocationProvider.OUT_OF_SERVICE:
                Toast.makeText(this, "Location provider unavailable, please restart", Toast.LENGTH_LONG).show();
                Log.d(LOCATION_TAG, provider + "Location provider out of service");
                break;
            case LocationProvider.AVAILABLE:
                Toast.makeText(this, "Location provider available", Toast.LENGTH_SHORT).show();
                Log.d(LOCATION_TAG, provider + "Location provider available");
                break;
            case LocationProvider.TEMPORARILY_UNAVAILABLE:
                Toast.makeText(this, "Location provider temporarily unavailable", Toast.LENGTH_SHORT).show();
                Log.d(LOCATION_TAG, provider + "Location provider temporarily unavailable");
                break;
        }
    }

    //Called when the provider is enabled by the user.
    @Override
    public void onProviderEnabled(String provider) {
        //Toast.makeText(this, provider + "Location provider enabled", Toast.LENGTH_SHORT);
        Log.d(LOCATION_TAG, provider + "Location provider enabled");
    }

    //Called when the provider is disabled by the user. If requestLocationUpdates is called on an already
    //disabled provider, this method is called immediately.
    @Override
    public void onProviderDisabled(String provider) {
        Toast.makeText(this, provider + "Location provider disabled", Toast.LENGTH_SHORT).show();
        Log.d(LOCATION_TAG, provider + "Location provider disabled");
    }

}

1 个答案:

答案 0 :(得分:0)

当您使用V2时,最好让Google处理此问题,V2可以帮助您使用GoogleMap自己的列表工具找到您的位置。

 mMap.setMyLocationEnabled(true);
 mMap.setOnMyLocationChangeListener(new OnMyLocationChangeListener()
            {

                @Override
                public void onMyLocationChange(Location location)
                    {
                        // Do your stuff here

                    }
            });