即使启用GPS并且所有位置管理器和侦听器设置正确,我也无法获取位置。这是我到目前为止:为什么此代码通过GPS无法获取位置?
public class GpsTest extends Activity {
private TextView text;
private LocationManager manager;
private LocationListener listener;
private Location myLocation;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView)findViewById(R.id.textView1);
try
{
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
myLocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER); //"gps"
text.setText(("Lat: " + myLocation.getLatitude()
+ "\nLLong: " + myLocation.getLongitude()));
listener = new MyLocationListener();
manager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
1,
listener);
if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(this, "GPS is enable. ", Toast.LENGTH_SHORT).show();
}
else createGpsDisabledAlert();
}catch(Exception ex)
{
createGpsDisabledAlert();
}
}
public void onclicklistener(View v){
try
{
text.setText(("Lat: " + myLocation.getLatitude()
+ "\nLLong: " + myLocation.getLongitude()));
}catch(Exception ex)
{
Toast.makeText(this, "Error while getting locations. "+ex.toString(), Toast.LENGTH_SHORT).show();
}
}
private void createGpsDisabledAlert(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("GPS is disabled! Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Enable GPS",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
showGpsOptions();
}
});
builder.setNegativeButton("No Thanks",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void showGpsOptions(){
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
private class MyLocationListener implements LocationListener{
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null){
text.setText(("Lat: " + location.getLatitude()
+ "\nLLong: " + location.getLongitude()));
}
Toast.makeText(GpsTest.this, ""+location, Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
}
谢谢GPS可以独立工作或需要一个网络来获取位置,我的设备没有数据网络。 – 2011-04-16 11:05:48
我认为网络连接不是必需的。 – Aracem 2011-04-16 15:36:52