以下是布局文件:
encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
android:id="@+id/txt1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
以下是源码:
package com.demo;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity
{
//
定义LocationManager
private LocationManager locationmanager;
//
定义TextView
private TextView txt1;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main3);
// TextView 控件
txt1 = (TextView) this.findViewById(R.id.txt1);
// 获取设备位置服务
locationmanager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
//获取活动位置服务
Location location = locationmanager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//打印信息
printMsg(location);
}
private void printMsg(Location
location) {
//获取经纬度
if(location != null){
double lat = location.getLatitude();
double lng = location.getLongitude();
//显示信息
txt1.setText("经度:"+ lat + " 纬度:"+ lng);
}
}
}
2.跟踪
跟踪是通过注册监听器来实现的。声明LocationListener监听器,在onLocationChanged(Location)方法中实现位置变化的代码。通过LocationManager的requestLocationUpdates()方法注册监听器,当设备位置发生变化时监听器被触发,onLocationChanged(Location
l)方法被调用。
package com.demo;
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.TextView;
public class GPSActivity2 extends Activity
{
// 定义LocationManager
private
LocationManager locationmanager;
// 定义TextView
private TextView
txt1;
@Override
protected
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main3);
// TextView 控件
txt1 = (TextView) this.findViewById(R.id.txt1);
// 获取设备位置服务
locationmanager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
// 获取活动位置服务
Location location = locationmanager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateMsg(location);
LocationListener ll = new LocationListener() {
@Override
public void onStatusChanged(String provider,
int status,
Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onLocationChanged(Location location)
{
updateMsg(location);
}
};
locationmanager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
1000, 10, ll);
}
private void
updateMsg(Location location) {
// 获取经纬度
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
// 显示信息
txt1.setText("经度:" + lat + " 纬度:" + lng +
"");
}
}
}