android gps 获取方位_Android GPS应用:动态获取位置信息

本文展示了如何在Android应用中实时获取GPS定位信息,包括经纬度、高度、速度和方向。通过LocationManager服务和LocationListener实现动态更新,并展示在EditText中。当GPS信息变化时,应用会更新位置详情。
摘要由CSDN通过智能技术生成

在上文中,介绍了GPS概念及Android开发GPS应用涉及到的常用类和方法。在本文中,开发一个小应用,实时获取定位信息,包括用户所在的纬度、经度、高度、方向、移动速度等。代码如下:

Activity:

package comhome.location;

import android.app.Activity;

import android.content.Context;

import android.location.Location;

import android.location.LocationListener;

import android.location.LocationManager;

import android.os.Bundle;

import android.widget.EditText;

public class LocationTestActivity extends Activity {

// 定义LocationManager对象

private LocationManager locationManager;

private EditText show;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

show = (EditText) findViewById(R.id.main_et_show);

// 获取系统LocationManager服务

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

// 从GPS获取最近的定位信息

Location location = locationManager

.getLastKnownLocation(LocationManager.GPS_PROVIDER);

// 将location里的位置信息显示在EditText中

updateView(location);

// 设置每2秒获取一次GPS的定位信息

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,

2000, 8, new LocationListener() {

@Override

public void onLocationChanged(Location location) {

// 当GPS定位信息发生改变时,更新位置

updateView(location);

}

@Override

public void onProviderDisabled(String provider) {

updateView(null);

}

@Override

public void onProviderEnabled(String provider) {

// 当GPS LocationProvider可用时,更新位置

updateView(locationManager

.getLastKnownLocation(provider));

}

@Override

public void onStatusChanged(String provider, int status,

Bundle extras) {

}

});

}

private void updateView(Location location) {

if (location != null) {

StringBuffer sb = new StringBuffer();

sb.append("实时的位置信息:\n经度:");

sb.append(location.getLongitude());

sb.append("\n纬度:");

sb.append(location.getLatitude());

sb.append("\n高度:");

sb.append(location.getAltitude());

sb.append("\n速度:");

sb.append(location.getSpeed());

sb.append("\n方向:");

sb.append(location.getBearing());

sb.append("\n精度:");

sb.append(location.getAccuracy());

show.setText(sb.toString());

} else {

// 如果传入的Location对象为空则清空EditText

show.setText("");

}

}

}

布局XML:

android:layout_width="match_parent"

android:layout_height="match_parent" >

android:id="@+id/main_et_show"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:cursorVisible="false"

android:editable="false" />

权限:

附上图片效果:

如果把该程序与Google Map结合,让程序根据GPS提供的信息实时地显示用户在地图上的位置,即可开发出GPS导航系统。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值