Android的定位跟踪 系统

本文介绍了一种安卓应用开发方案,通过GPS获取用户位置信息,并将这些信息发送到服务器,利用百度地图API进行坐标展示。文章详细展示了如何在安卓应用中集成GPS功能,包括XML布局文件、AndroidManifest配置及Java代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现对安卓手机的跟踪,将安卓的GPS坐标返回给服务器,然后通过百度地图API将坐标显示出来。
1.安卓程序
搭建安卓开发环境的方法在这里不讨论,大家可以搜索一下
新建一个项目mygps,在res/layout/main.xml里码入如下内容:


  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:layout_width="fill_parent"
  4.     android:layout_height="fill_parent"
  5.     android:orientation="vertical" >

  6.     <EditText
  7.         android:id="@ id/editText"
  8.         android:layout_width="fill_parent"
  9.         android:layout_height="wrap_content"
  10.         android:cursorVisible="false"
  11.         android:editable="false" />

  12.     <TextView
  13.         android:id="@ id/tv"
  14.         android:layout_width="match_parent"
  15.         android:layout_height="wrap_content"
  16.         android:editable="false"
  17.         android:textSize="30sp"
  18.         android:textColor="#FF0000" />

  19. </LinearLayout>
AndroidManifest.xml里码入:

  1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  2.     package="com.lxb.mygps"
  3.     android:versionCode="1"
  4.     android:versionName="1.0">

  5.     <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" />
  6.     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  7.     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  8.     <uses-permission android:name="android.permission.INTERNET" />
  9.     
  10.     <application android:label="@string/app_name"
  11.         android:icon="@drawable/ic_launcher"
  12.         android:theme="@style/AppTheme">
  13.         <activity
  14.             android:name="com.lxb.activity.GpsActivity"
  15.             android:label="gpsTest" >
  16.             <intent-filter>
  17.                 <action android:name="android.intent.action.MAIN" />
  18.                 <category android:name="android.intent.category.LAUNCHER" />
  19.             </intent-filter>
  20.         </activity>
  21.     </application>

  22. </manifest>
src下新建包com.lxb.activity,新建GpsActivity.java,码入:

点击(此处)折叠或打开

  1. package com.lxb.activity;

  2. import java.util.Iterator;

  3. import com.lxb.mygps.R;

  4. import org.apache.http.HttpResponse;
  5. import org.apache.http.NameValuePair;
  6. import org.apache.http.client.entity.UrlEncodedFormEntity;
  7. import org.apache.http.client.methods.HttpPost;
  8. import org.apache.http.impl.client.DefaultHttpClient;
  9. import org.apache.http.message.BasicNameValuePair;
  10. import org.apache.http.protocol.HTTP;
  11. import org.apache.http.util.EntityUtils;
  12. import java.util.ArrayList;
  13. import java.util.List;

  14. import android.annotation.TargetApi;
  15. import android.app.Activity;
  16. import android.content.Context;
  17. import android.content.Intent;
  18. import android.location.Criteria;
  19. import android.location.GpsSatellite;
  20. import android.location.GpsStatus;
  21. import android.location.Location;
  22. import android.location.LocationListener;
  23. import android.location.LocationManager;
  24. import android.location.LocationProvider;
  25. import android.os.Bundle;
  26. import android.os.StrictMode;
  27. import android.provider.Settings;
  28. import android.util.Log;
  29. import android.widget.EditText;
  30. import android.widget.TextView;
  31. import android.widget.Toast;

  32. @TargetApi(9)
  33. public class GpsActivity extends Activity {
  34.     private EditText editText;
  35.     private LocationManager lm;
  36.     private static final String TAG = "GpsActivity";
  37.     private static final String url = "http://abc.com/gps.php";
  38.     HttpPost httpRequest = null;
  39.     List<NameValuePair> params = null;
  40.     HttpResponse httpResponse;
  41.     TextView tv = null;

  42.     @Override
  43.     protected void onDestroy() {
  44.         // TODO Auto-generated method stub
  45.         super.onDestroy();
  46.         lm.removeUpdates(locationListener);
  47.     }

  48.     @TargetApi(9)
  49.     @Override
  50.     public void onCreate(Bundle savedInstanceState) {
  51.         // 高低版本兼容性代码
  52.         String strVer = GetSystemVersion();
  53.         strVer = strVer.substring(0, 3).trim();
  54.         float fv = Float.valueOf(strVer);
  55.         if (fv > 2.3) {
  56.             StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
  57.                 .detectDiskReads().detectDiskWrites().detectAll()
  58.                 .penaltyLog()
  59.                 .build()
  60.             );
  61.             StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
  62.                 .detectLeakedSqlLiteObjects()
  63.                 .penaltyLog()
  64.                 .penaltyDeath().build()
  65.             );
  66.         }
  67.         // 高低版本兼容性代码结束
  68.         super.onCreate(savedInstanceState);
  69.         setContentView(R.layout.main);

  70.         editText = (EditText) findViewById(R.id.editText);
  71.         tv = (TextView) findViewById(R.id.tv);
  72.         lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

  73.         // 判断GPS是否正常启动
  74.         if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
  75.             Toast.makeText(this, "请开启GPS导航...", Toast.LENGTH_LONG).show();
  76.             // 返回开启GPS导航设置界面
  77.             Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
  78.             startActivityForResult(intent, 0);
  79.             return;
  80.         }

  81.         // 为获取地理位置信息时设置查询条件
  82.         String bestProvider = lm.getBestProvider(getCriteria(), true);
  83.         // 获取位置信息
  84.         // 如果不设置查询要求,getLastKnownLocation方法传人的参数为LocationManager.GPS_PROVIDER
  85.         Location location = lm.getLastKnownLocation(bestProvider);
  86.         updateView(location);
  87.         // 监听状态
  88.         lm.addGpsStatusListener(listener);
  89.         // 绑定监听,有4个参数
  90.         // 参数1,设备:有GPS_PROVIDER和NETWORK_PROVIDER两种
  91.         // 参数2,位置信息更新周期,单位毫秒
  92.         // 参数3,位置变化最小距离:当位置距离变化超过此值时,将更新位置信息
  93.         // 参数4,监听
  94.         // 备注:参数2和3,如果参数3不为0,则以参数3为准;参数3为0,则通过时间来定时更新;两者为0,则随时刷新

  95.         // 1秒更新一次,或最小位移变化超过1米更新一次;
  96.         // 注意:此处更新准确度非常低,推荐在service里面启动一个Thread,在run中sleep(10000);然后执行handler.sendMessage(),更新位置
  97.         lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1,
  98.                 locationListener);
  99.     }

  100.     // 位置监听
  101.     private LocationListener locationListener = new LocationListener() {

  102.         /**
  103.          * 位置信息变化时触发
  104.          */
  105.         public void onLocationChanged(Location location) {
  106.             updateView(location);
  107.             Log.i(TAG, "时间:" location.getTime());
  108.             Log.i(TAG, "经度:" location.getLongitude());
  109.             Log.i(TAG, "纬度:" location.getLatitude());
  110.             Log.i(TAG, "海拔:" location.getAltitude());
  111.         }

  112.         /**
  113.          * GPS状态变化时触发
  114.          */
  115.         public void onStatusChanged(String provider, int status, Bundle extras) {
  116.             switch (status) {
  117.             // GPS状态为可见时
  118.             case LocationProvider.AVAILABLE:
  119.                 Log.i(TAG, "当前GPS状态为可见状态");
  120.                 break;
  121.             // GPS状态为服务区外时
  122.             case LocationProvider.OUT_OF_SERVICE:
  123.                 Log.i(TAG, "当前GPS状态为服务区外状态");
  124.                 break;
  125.             // GPS状态为暂停服务时
  126.             case LocationProvider.TEMPORARILY_UNAVAILABLE:
  127.                 Log.i(TAG, "当前GPS状态为暂停服务状态");
  128.                 break;
  129.             }
  130.         }

  131.         /**
  132.          * GPS开启时触发
  133.          */
  134.         public void onProviderEnabled(String provider) {
  135.             Location location = lm.getLastKnownLocation(provider);
  136.             updateView(location);
  137.         }

  138.         /**
  139.          * GPS禁用时触发
  140.          */
  141.         public void onProviderDisabled(String provider) {
  142.             updateView(null);
  143.         }

  144.     };

  145.     // 状态监听
  146.     GpsStatus.Listener listener = new GpsStatus.Listener() {
  147.         public void onGpsStatusChanged(int event) {
  148.             switch (event) {
  149.             // 第一次定位
  150.             case GpsStatus.GPS_EVENT_FIRST_FIX:
  151.                 Log.i(TAG, "第一次定位");
  152.                 break;
  153.             // 卫星状态改变
  154.             case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
  155.                 Log.i(TAG, "卫星状态改变");
  156.                 // 获取当前状态
  157.                 GpsStatus gpsStatus = lm.getGpsStatus(null);
  158.                 // 获取卫星颗数的默认最大值
  159.                 int maxSatellites = gpsStatus.getMaxSatellites();
  160.                 // 创建一个迭代器保存所有卫星
  161.                 Iterator<GpsSatellite> iters = gpsStatus.getSatellites()
  162.                         .iterator();
  163.                 int count = 0;
  164.                 while (iters.hasNext() && count <= maxSatellites) {
  165.                     GpsSatellite s = iters.next();
  166.                     count ;
  167.                 }
  168.                 System.out.println("搜索到:" count "颗卫星");
  169.                 break;
  170.             // 定位启动
  171.             case GpsStatus.GPS_EVENT_STARTED:
  172.                 Log.i(TAG, "定位启动");
  173.                 break;
  174.             // 定位结束
  175.             case GpsStatus.GPS_EVENT_STOPPED:
  176.                 Log.i(TAG, "定位结束");
  177.                 break;
  178.             }
  179.         };
  180.     };

  181.     /**
  182.      * 实时更新文本内容
  183.      *
  184.      * @param location
  185.      */
  186.     private void updateView(Location location) {
  187.         editText.setText("GPS状态:等待定位");
  188.         tv.setText("等待获取位置信息");
  189.         if(location!=null){
  190.             editText.setText("GPS状态:定位成功\n");
  191.             editText.append("设备位置信息\n\n经度:");
  192.             editText.append(String.valueOf(location.getLongitude()));
  193.             editText.append("\n纬度:");
  194.             editText.append(String.valueOf(location.getLatitude()));
  195.             
  196.             /* 建立HttpPost连接 */
  197.             httpRequest=new HttpPost(url);
  198.             /*Post运作传送变数必须用NameValuePair[]阵列储存*/
  199.             params=new ArrayList<NameValuePair>();
  200.             params.add(new BasicNameValuePair("wd",String.valueOf(location.getLatitude())));
  201.             params.add(new BasicNameValuePair("jd",String.valueOf(location.getLongitude())));
  202.             
  203.             try {
  204.                 //发出HTTP request
  205.                 httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
  206.                 //取得HTTP response
  207.                 httpResponse=new DefaultHttpClient().execute(httpRequest);
  208.                 //若状态码为200
  209.                 if(httpResponse.getStatusLine().getStatusCode()==200){
  210.                     //取出回应字串
  211.                     String strResult=EntityUtils.toString(httpResponse.getEntity());
  212.                     tv.setText(strResult);
  213.                 }else{
  214.                     tv.<SPAN div styl<>
  215. 注:暂存的内容只能恢复到当前文章的编辑器中,如需恢复到其他文章中,请编辑该文章并从暂存箱中恢复;或者直接复制以上内容,手工恢复到相关文章。
  216. 恢复到编辑器  关闭

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值