我正在使用此代码来获取我当前位置的纬度和经度......但应用程序有时会崩溃。在某些手机上,获取位置需要很长时间,而其他使用 gps 的应用程序在同一设备上可以更快地获取位置
package com.example.newproject;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity implements LocationListener {
private TextView tv;
private static LocationManager locationMgr = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.textView1);
locationMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
@Override
protected void onStop()
{
super.onStop();
try {
locationMgr.removeUpdates(this);
} catch (Exception ex) {
ex.printStackTrace();
}
locationMgr = null;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
tv.setText(""+location.getLatitude()+","+location.getLongitude());
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}