实现对安卓手机的跟踪,将安卓的GPS坐标返回给服务器,然后通过百度地图API将坐标显示出来。
1.安卓程序
搭建安卓开发环境的方法在这里不讨论,大家可以搜索一下
新建一个项目mygps,在res/layout/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/editText"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:cursorVisible="false"
- android:editable="false"
/>
- <TextView
- android:id="@ id/tv"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:editable="false"
- android:textSize="30sp"
- android:textColor="#FF0000"
/>
- </LinearLayout>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.lxb.mygps"
- android:versionCode="1"
- android:versionName="1.0">
- <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15"
/>
- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
- <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
- <uses-permission android:name="android.permission.INTERNET"
/>
-
- <application android:label="@string/app_name"
- android:icon="@drawable/ic_launcher"
- android:theme="@style/AppTheme">
- <activity
- android:name="com.lxb.activity.GpsActivity"
- android:label="gpsTest"
>
- <intent-filter>
- <action android:name="android.intent.action.MAIN"
/>
- <category android:name="android.intent.category.LAUNCHER"
/>
- </intent-filter>
- </activity>
- </application>
- </manifest>
点击(此处)折叠或打开
- package com.lxb.activity;
- import java.util.Iterator;
- import com.lxb.mygps.R;
- import org.apache.http.HttpResponse;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.http.protocol.HTTP;
- import org.apache.http.util.EntityUtils;
- import java.util.ArrayList;
- import java.util.List;
- import android.annotation.TargetApi;
- import android.app.Activity;
- import android.content.Context;
- import android.content.Intent;
- import android.location.Criteria;
- import android.location.GpsSatellite;
- 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.StrictMode;
- import android.provider.Settings;
- import android.util.Log;
- import android.widget.EditText;
- import android.widget.TextView;
- import android.widget.Toast;
- @TargetApi(9)
- public class GpsActivity
extends Activity
{
- private EditText editText;
- private LocationManager lm;
- private static
final String TAG
= "GpsActivity";
- private static
final String
url =
"http://abc.com/gps.php";
- HttpPost httpRequest =
null;
- List<NameValuePair>
params =
null;
- HttpResponse httpResponse;
- TextView tv =
null;
- @Override
- protected
void onDestroy()
{
- // TODO Auto-generated method stub
- super.onDestroy();
- lm.removeUpdates(locationListener);
- }
- @TargetApi(9)
- @Override
- public void onCreate(Bundle savedInstanceState)
{
- // 高低版本兼容性代码
- String strVer
= GetSystemVersion();
- strVer = strVer.substring(0, 3).trim();
- float fv
= Float.valueOf(strVer);
- if (fv
> 2.3)
{
- StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
- .detectDiskReads().detectDiskWrites().detectAll()
- .penaltyLog()
- .build()
- );
- StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
- .detectLeakedSqlLiteObjects()
- .penaltyLog()
- .penaltyDeath().build()
- );
- }
- // 高低版本兼容性代码结束
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- editText =
(EditText) findViewById(R.id.editText);
- tv = (TextView) findViewById(R.id.tv);
- lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
- // 判断GPS是否正常启动
- if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
- Toast.makeText(this,
"请开启GPS导航...", Toast.LENGTH_LONG).show();
- // 返回开启GPS导航设置界面
- Intent intent =
new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
- startActivityForResult(intent, 0);
- return;
- }
- // 为获取地理位置信息时设置查询条件
- String bestProvider
= lm.getBestProvider(getCriteria(), true);
- // 获取位置信息
- // 如果不设置查询要求,getLastKnownLocation方法传人的参数为LocationManager.GPS_PROVIDER
- Location
location = lm.getLastKnownLocation(bestProvider);
- updateView(location);
- // 监听状态
- lm.addGpsStatusListener(listener);
- // 绑定监听,有4个参数
- // 参数1,设备:有GPS_PROVIDER和NETWORK_PROVIDER两种
- // 参数2,位置信息更新周期,单位毫秒
- // 参数3,位置变化最小距离:当位置距离变化超过此值时,将更新位置信息
- // 参数4,监听
- // 备注:参数2和3,如果参数3不为0,则以参数3为准;参数3为0,则通过时间来定时更新;两者为0,则随时刷新
- // 1秒更新一次,或最小位移变化超过1米更新一次;
- // 注意:此处更新准确度非常低,推荐在service里面启动一个Thread,在run中sleep(10000);然后执行handler.sendMessage(),更新位置
- lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1,
- locationListener);
- }
- // 位置监听
- private LocationListener locationListener
= new LocationListener()
{
- /**
- * 位置信息变化时触发
- */
- public
void onLocationChanged(Location
location)
{
- updateView(location);
- Log.i(TAG,
"时间:" location.getTime());
- Log.i(TAG,
"经度:" location.getLongitude());
- Log.i(TAG,
"纬度:" location.getLatitude());
- Log.i(TAG,
"海拔:" location.getAltitude());
- }
- /**
- * GPS状态变化时触发
- */
- public
void onStatusChanged(String
provider,
int status, Bundle extras)
{
- switch
(status)
{
- // GPS状态为可见时
- case LocationProvider.AVAILABLE:
- Log.i(TAG,
"当前GPS状态为可见状态");
- break;
- // GPS状态为服务区外时
- case LocationProvider.OUT_OF_SERVICE:
- Log.i(TAG,
"当前GPS状态为服务区外状态");
- break;
- // GPS状态为暂停服务时
- case LocationProvider.TEMPORARILY_UNAVAILABLE:
- Log.i(TAG,
"当前GPS状态为暂停服务状态");
- break;
- }
- }
- /**
- * GPS开启时触发
- */
- public
void onProviderEnabled(String
provider)
{
- Location
location = lm.getLastKnownLocation(provider);
- updateView(location);
- }
- /**
- * GPS禁用时触发
- */
- public
void onProviderDisabled(String
provider)
{
- updateView(null);
- }
- };
- // 状态监听
- GpsStatus.Listener listener
= new GpsStatus.Listener()
{
- public
void onGpsStatusChanged(int
event)
{
- switch
(event)
{
- // 第一次定位
- case GpsStatus.GPS_EVENT_FIRST_FIX:
- Log.i(TAG,
"第一次定位");
- break;
- // 卫星状态改变
- case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
- Log.i(TAG,
"卫星状态改变");
- // 获取当前状态
- GpsStatus gpsStatus = lm.getGpsStatus(null);
- // 获取卫星颗数的默认最大值
- int maxSatellites
= gpsStatus.getMaxSatellites();
- // 创建一个迭代器保存所有卫星
- Iterator<GpsSatellite> iters
= gpsStatus.getSatellites()
- .iterator();
- int
count = 0;
- while
(iters.hasNext()
&&
count <= maxSatellites)
{
- GpsSatellite s = iters.next();
- count
;
- }
- System.out.println("搜索到:"
count
"颗卫星");
- break;
- // 定位启动
- case GpsStatus.GPS_EVENT_STARTED:
- Log.i(TAG,
"定位启动");
- break;
- // 定位结束
- case GpsStatus.GPS_EVENT_STOPPED:
- Log.i(TAG,
"定位结束");
- break;
- }
- };
- };
- /**
- * 实时更新文本内容
- *
- * @param location
- */
- private void updateView(Location
location)
{
- editText.setText("GPS状态:等待定位");
- tv.setText("等待获取位置信息");
- if(location!=null){
- editText.setText("GPS状态:定位成功\n");
- editText.append("设备位置信息\n\n经度:");
- editText.append(String.valueOf(location.getLongitude()));
- editText.append("\n纬度:");
- editText.append(String.valueOf(location.getLatitude()));
-
- /* 建立HttpPost连接 */
- httpRequest=new HttpPost(url);
- /*Post运作传送变数必须用NameValuePair[]阵列储存*/
- params=new
ArrayList<NameValuePair>();
- params.add(new BasicNameValuePair("wd",String.valueOf(location.getLatitude())));
- params.add(new BasicNameValuePair("jd",String.valueOf(location.getLongitude())));
-
- try
{
- //发出HTTP request
- httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
- //取得HTTP response
- httpResponse=new DefaultHttpClient().execute(httpRequest);
- //若状态码为200
- if(httpResponse.getStatusLine().getStatusCode()==200){
- //取出回应字串
- String strResult=EntityUtils.toString(httpResponse.getEntity());
- tv.setText(strResult);
- }else{
- tv.<SPAN div styl<>
- 注:暂存的内容只能恢复到当前文章的编辑器中,如需恢复到其他文章中,请编辑该文章并从暂存箱中恢复;或者直接复制以上内容,手工恢复到相关文章。
- 恢复到编辑器 关闭