一、main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/text_location"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:editable="false" />
</LinearLayout>
View Code
二、activity
package com.mytest.huilife;
import java.util.Date;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
public class LocationActivity extends Activity {
private static final String LOG_TAG = "LocationActivity";
private LocationManager locationManager;
private ProgressDialog progressDialog;
private EditText textLoaction;
private String loactionSoureFrom; // 定位数据来自哪,GPS,还是网络
// private TimerTask timerTask;
// private Timer timer;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if(progressDialog!=null){
progressDialog.dismiss();
}
//更新界面位置信息
updateTextLoaction();
};
};
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (locationManager != null && locationListener != null) {
locationManager.removeUpdates(locationListener);
}
// if (timer != null) {
// timer.cancel();
// }
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
textLoaction = (EditText) this.findViewById(R.id.text_location);
if (NetWorkUtil.isNetAvailable(this) == false) {
Toast.makeText(this, "请打开网络连接", Toast.LENGTH_SHORT).show();
return;
}
if (NetWorkUtil.isGPSAvailable(this)) {
// 从GPS获取位置信息
getLocationFromGPS();
} else {
// 如果GPS不可用
new AlertDialog.Builder(this).setTitle("你是否要打开GPS?")
.setPositiveButton("是", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 让用户打开GPS
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(intent, 0);
}
}).setNegativeButton("否", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 从网络获取位置信息
getLocationFromNetWork();
}
}).show();
}
}
private double latitude; // 纬度
private double longitude; // 经度
private double altitude; // 海拔
private String getLocationLastTime;
private void updateTextLoaction() {
// Log.v(LOG_TAG,"updateTextLoaction:"+"经度:"+longitude+",纬度:"+latitude+",海拔:"+altitude);
textLoaction.setText("定位数据来自:" + loactionSoureFrom + ",\n经度:" + longitude + "\n纬度:" + latitude + ",\n海拔:"
+ altitude + ",获取时间:" + getLocationLastTime);
}
/**
* 采用高德地图,执行网络定位,并在定位中显示等待
*/
private void getLocationFromNetWork() {
progressDialog = new ProgressDialog(LocationActivity.this);
progressDialog.setMessage("正在定位中...");
progressDialog.setCanceledOnTouchOutside(false);// 点击外部,进度提示框不会消失
progressDialog.show();
// 初始化高德地图定位
initAmapLocation();
}
/**
* 初始化高德定位
*/
private void initAmapLocation() {
LocationManagerProxy locationManagerProxy = LocationManagerProxy.getInstance(this);
locationManagerProxy.setGpsEnable(false);
locationManagerProxy.requestLocationData(LocationProviderProxy.AMapNetwork, 3 * 1000, 10,
new AMapLocationListener() {
@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) {
}
@Override
public void onLocationChanged(AMapLocation amapLocation) {
if (amapLocation != null && amapLocation.getAMapException().getErrorCode() == 0) {
// 定位成功回调信息,设置相关消息
latitude = amapLocation.getLatitude();
longitude = amapLocation.getLongitude();
altitude = amapLocation.getAltitude();
Date date = new Date(amapLocation.getTime());
String dateStr = String.format("%d:%d %d", date.getHours(), date.getMinutes(),
date.getSeconds());
getLocationLastTime = dateStr;
// Log.v(LOG_TAG, "(amap)位置发生改变," + "时间:" + dateStr + "经度:" + amapLocation.getLongitude()
// + "纬度:" + amapLocation.getLatitude() + "海拔:" + amapLocation.getAltitude());
if (progressDialog != null) {
progressDialog.dismiss();
}
loactionSoureFrom = "amap";
// 发送消息,更新界面位置信息
handler.sendEmptyMessage(0);
}
}
});
}
/**
* 从GPS获取位置信息
*/
private void getLocationFromGPS() {
progressDialog = new ProgressDialog(LocationActivity.this);
progressDialog.setMessage("正在定位中...");
progressDialog.setCanceledOnTouchOutside(false);// 点击外部,进度提示框不会消失
progressDialog.show();
// 获取manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String bestProvider = locationManager.getBestProvider(getCriteria(), true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
Date date = new Date(location.getTime());
String dateStr = String.format("%d:%d %d", date.getHours(), date.getMinutes(), date.getSeconds());
getLocationLastTime = dateStr;
longitude = location.getLongitude(); // 纬度
latitude = location.getLatitude(); // 经度
altitude = location.getAltitude(); // 海拔
if (progressDialog != null) {
progressDialog.dismiss();
}
loactionSoureFrom = "GPS";
// 更新界面位置信息
updateTextLoaction();
} else {
// Log.i(LOG_TAG, "从GPS获取数据为空");
if (progressDialog != null) {
progressDialog.dismiss();
}
loactionSoureFrom = "GPS";
// Toast.makeText(this, "从GPS获取位置信息,得到数据为空",
// Toast.LENGTH_SHORT).show();
new AlertDialog.Builder(this).setTitle("GPS数据为空,改从网络?")
.setPositiveButton("是", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
getLocationFromNetWork();
}
}).setNegativeButton("否", null).show();
}
locationManager.addGpsStatusListener(gpsListener);
// 绑定监听,有4个参数
// 参数1,设备:有GPS_PROVIDER和NETWORK_PROVIDER两种
// 参数2,位置信息更新周期,单位毫秒
// 参数3,位置变化最小距离:当位置距离变化超过此值时,将更新位置信息
// 参数4,监听
// 备注:参数2和3,如果参数3不为0,则以参数3为准;参数3为0,则通过时间来定时更新;两者为0,则随时刷新
// 3秒更新一次,或最小位移变化超过1米更新一次;
// 注意:此处更新准确度非常低,推荐在service里面启动一个Thread,在run中sleep(10000);然后执行handler.sendMessage(),更新位置
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 1, locationListener);
}
/**
* 设置查询条件
*
* @return
*/
private Criteria getCriteria() {
// 创建查询条件
Criteria criteria = new Criteria();
// 设置定位精确度 Criteria.ACCURACY_COARSE比较粗略,Criteria.ACCURACY_FINE则比较精细
criteria.setAccuracy(Criteria.ACCURACY_FINE);
// 设置是否要求速度
criteria.setSpeedRequired(false);
// 设置是否允许运营商收费
criteria.setCostAllowed(false);
// 设置是否需要方位信息
criteria.setBearingRequired(false);
// 设置是否需要海拔信息
criteria.setAltitudeRequired(false);
// 设置对电源的需求
criteria.setPowerRequirement(Criteria.POWER_LOW);
return criteria;
}
/**
* 位置监听
*/
private LocationListener locationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
// GPS状态为可见时
case LocationProvider.AVAILABLE:
// Log.i(LOG_TAG, "当前GPS状态为可见状态");
break;
// GPS状态为服务区外时
case LocationProvider.OUT_OF_SERVICE:
// Log.i(LOG_TAG, "当前GPS状态为服务区外状态");
break;
// GPS状态为暂停服务时
case LocationProvider.TEMPORARILY_UNAVAILABLE:
// Log.i(LOG_TAG, "当前GPS状态为暂停服务状态");
break;
}
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location location) {
Date date = new Date(location.getTime());
String dateStr = String.format("%d:%d %d", date.getHours(), date.getMinutes(), date.getSeconds());
getLocationLastTime = dateStr;
longitude = location.getLongitude(); // 纬度
latitude = location.getLatitude(); // 经度
altitude = location.getAltitude(); // 海拔
// Log.v(LOG_TAG, "GPS位置发生改变," + "时间:" + dateStr + "经度:" +
// location.getLongitude() + "纬度:"
// + location.getLatitude() + "海拔:" + location.getAltitude());
if (progressDialog != null) {
progressDialog.dismiss();
}
loactionSoureFrom = "GPS";
// 发送消息,更新界面位置信息
handler.sendEmptyMessage(0);
}
};
/**
* GPS状态监听
*/
GpsStatus.Listener gpsListener = new GpsStatus.Listener() {
@Override
public void onGpsStatusChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_FIRST_FIX:
// Log.v(LOG_TAG, "第一次定位");
break;
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
// Log.v(LOG_TAG, "卫星状态发生改变");
break;
case GpsStatus.GPS_EVENT_STARTED:
// Log.v(LOG_TAG, "启动定位");
break;
case GpsStatus.GPS_EVENT_STOPPED:
// Log.v(LOG_TAG, "结束定位");
break;
}
}
};
}
View Code
三、NetWorkUtil
package com.mytest.huilife;
import android.content.Context;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetWorkUtil {
/**
* 判断网络是否可用
* @param context
* @return
*/
public static boolean isNetAvailable(Context context) {
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netWorkInfo = connManager.getActiveNetworkInfo();
if(netWorkInfo==null || !netWorkInfo.isAvailable()){
return false;
}
return true;
}
/**
* 判断GPS是否可用
*/
public static boolean isGPSAvailable(Context context) {
LocationManager locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean net = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(gps || net){
return true;
}
return false;
}
}
View Code
四、AndroidMainfest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mytest.huilife"
android:versionCode="2"
android:versionName="2" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<meta-data
android:name="com.amap.api.v2.apikey"
android:value="??????在此输入高德地图的key" />
<activity
android:name=".LocationActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".GPSActivity" >
</activity>
<activity android:name=".LocationActivity" >
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
</manifest>
View Code
五、小结
1、导入高德地图的jar包(Android_Location_V1.2.0)。
2、用了一个手机卡的旧手机测试,GPS虽然打开,但获取数据为空,改用从网络获取。
3、上述引用,注意在androidmainfest.xml中配置高德地图的相关meta、权限等。