Google地图 - 未调用onLocationChanged

时间:2015-01-01 22:29:30

标签: java android google-maps location listener

我正在使用谷歌地图开发跟踪Android应用程序。我有以下问题:我的MapFragment中的onLocationChanged方法只被调用一次,然后再也没有。即使我有一个假的GPS提供商正在运行,并经常改变我的位置。位置本身在地图上更新,但该函数仅被调用一次。而且我需要它被调用,因为我想在每个位置变化上绘制路径。

我的代码:

public class MapActivity extends FragmentActivity implements LocationListener,
                                                         SensorEventListener{

/* constants */
private static final long INTERVAL = 1000;
private static final float ACCURACY = 20;
public static final int NEW_TRACK_ID = 0;


private GoogleMap map;  
private DataSource dataSource;
private SensorManager sensorManager;
private Sensor senAccelerometer; 

private boolean zoomEnabled;
private boolean draw;
private Track currentTrack;

private Button saveTrackButton;
private LocationManager locationManager;
private String provider;

private int trackId;



@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);           
    setContentView(R.layout.activity_map);            
    initialize();
    saveTrackButton = (Button) findViewById(R.id.saveTrackButton);
    saveTrackButton.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            getDataFromPopupWindow();
        }

    });



}



private void initialize()
{
     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);      
     Criteria criteria = new Criteria();
     provider = locationManager.getBestProvider(criteria, false);
     setUpMapIfNeeded();  
     startTracking();
     dataSource = new DataSource(this);
     sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
     senAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
     sensorManager.registerListener(this, senAccelerometer , SensorManager.SENSOR_DELAY_NORMAL);   
     zoomEnabled = true;
     Intent intent = getIntent();
     trackId = intent.getIntExtra("trackId", 0);
     Toast.makeText(getApplicationContext(), "Track id:" + trackId, Toast.LENGTH_LONG).show();
     if(trackId != NEW_TRACK_ID){
         currentTrack = getTrackById(trackId);
         drawTrack();       
         draw = false;
     }
     else{
         currentTrack = new Track();
         draw = true;
     }


}

private void getDataFromPopupWindow()
{        
    LayoutInflater layoutInflater 
    = (LayoutInflater)getBaseContext()
     .getSystemService(LAYOUT_INFLATER_SERVICE);  

    View popupView = layoutInflater.inflate(R.layout.save_track_window, null);  
    final PopupWindow popupWindow = new PopupWindow(
              popupView, 
              LayoutParams.WRAP_CONTENT,  
              LayoutParams.WRAP_CONTENT);          

    final EditText editName = (EditText) popupView.findViewById (R.id.trackName);
    editName.requestFocus();


    Button btnDismiss = (Button)popupView.findViewById(R.id.cancel);
    btnDismiss.setOnClickListener(new Button.OnClickListener(){

        @Override
        public void onClick(View v) {
         // TODO Auto-generated method stub
            popupWindow.dismiss();
        }

    });

    Button btnSave = (Button) popupView.findViewById(R.id.save);
    btnSave.setOnClickListener(new Button.OnClickListener(){

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String trackName = editName.getText().toString();               
            saveTrack(trackName);
            popupWindow.dismiss();
        }

    });   
    popupWindow.setFocusable(true);
    popupWindow.update();
    popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    popupWindow.showAtLocation(saveTrackButton, Gravity.CENTER, 0, -100);
}

/**
 * Saves the track to database when finished
 */
private void saveTrack(String trackName){  
    Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);
    String date = String.valueOf(year) + "-" + String.valueOf(month) + "-" + String.valueOf(day) ;   
    currentTrack.setDate(date);
    currentTrack.setName(trackName);        
    dataSource.open();
    dataSource.insertTrack(currentTrack);       
    dataSource.close();
}

/**
 * Centers the view of the map around the current user's location.
 * @param loc LatLng object representing user's current coordinates.
 */
private void zoom (LatLng loc)
{
    if(zoomEnabled)
    {                   
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16));      
        zoomEnabled = false;
    }
}



/** Initializes the GoogleMap object if it hasn't been already done. 
 * If successful, enables location tracking.     
 */
private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (map == null) {
        // Try to obtain the map from the SupportMapFragment.
        map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
                .getMap();
        map.setMyLocationEnabled(true); 
        // Check if we were successful in obtaining the map.
        if (map != null) {                             
           startTracking();
        }
    }
} 

private void startTracking()
{       
    locationManager.requestLocationUpdates(provider, INTERVAL, ACCURACY, this);       

}

private Track getTrackById (int trackId)
{
    dataSource.open();
    Track track = dataSource.getTrack(trackId);
    dataSource.close();
    return track;
}

private void drawTrack()
{ 
    Toast.makeText(this,  currentTrack.getPoints().toString(), Toast.LENGTH_SHORT).show();
    map.addPolyline(new PolylineOptions().addAll(currentTrack.getPoints()).width(5).color(Color.BLUE));

}


@Override
protected void onPause() {          
    super.onPause();
    dataSource.close();
    locationManager.removeUpdates(this);
}

@Override
protected void onResume() {
    super.onResume();
    dataSource.open();
    setUpMapIfNeeded(); 

}

@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
    // TODO Auto-generated method stub

}

@Override
public void onSensorChanged(SensorEvent event) {        
    Sensor mySensor = event.sensor;      
    if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        if(event.values[0] > 18 || event.values[1] > 18 || event.values[2] > 18 && map.getMyLocation()!=null)
        {
            Intent intent = new Intent(this, CameraActivity.class);
            intent.putExtra("latitude", map.getMyLocation().getLatitude());
            intent.putExtra("longitude", map.getMyLocation().getLongitude());
            intent.putExtra("trackId", trackId);                
            startActivity(intent);
        }
    }       
}

@Override
public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub
    LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
    currentTrack.addPoint(loc);
    if(draw) drawTrack();   
    Toast.makeText(this,  "location changed", Toast.LENGTH_SHORT).show();

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub
     Toast.makeText(this, "Enabled new provider " + provider,
                Toast.LENGTH_SHORT).show();
}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub
      Toast.makeText(this, "Disabled provider " + provider,
                Toast.LENGTH_SHORT).show();
}


}

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

错误可能与onLocationRequest方法中的timeMin参数有关。

答案 1 :(得分:0)

该问题仅涉及requestLocationUpdate方法参数(minTime参数设置为错误的值)。问题解决了。