分享

Android Service获取当前位置(GPS+基站)

 QCamera 2014-12-15

需求详情:

1)、Service中每隔1秒执行一次定位操作(GPS+基站)
2)、定位的结果实时显示在界面上(要求得到经度、纬度)
技术支持:
1)、获取经纬度
通过GPS+基站获取经纬度,先通过GPS来获取,如果为空改用基站进行获取–>GPS+基站(基站获取支持联通、电信、移动)。
2)、实时获取经纬度
为了达到实时获取经纬度,需在后台启动获取经纬度的Service,然后把经纬度数据通过广播发送出去,在需要的地方进行广播注册(比如在Activity中注册广播,显示在界面中)–>涉及到Service+BroadcastReceiver+Activity+Thread等知识点。
备注:本文注重实践,如有看不懂的,先去巩固下知识点,可以去看看我前面写的几篇文章。
1、CellInfo实体类–>基站信息
  1. package com.ljq.activity;

  2. /**
  3. * 基站信息
  4. *
  5. * @author jiqinlin
  6. *
  7. */
  8. public class CellInfo {
  9. /** 基站id,用来找到基站的位置 */
  10. private int cellId;
  11. /** 移动国家码,共3位,中国为460,即imsi前3位 */
  12. private String mobileCountryCode="460";
  13. /** 移动网络码,共2位,在中国,移动的代码为00和02,联通的代码为01,电信的代码为03,即imsi第4~5位 */
  14. private String mobileNetworkCode="0";
  15. /** 地区区域码 */
  16. private int locationAreaCode;
  17. /** 信号类型[选 gsm|cdma|wcdma] */
  18. private String radioType="";

  19. public CellInfo() {
  20. }

  21. public int getCellId() {
  22.   return cellId;
  23. }

  24. public void setCellId(int cellId) {
  25.   this.cellId = cellId;
  26. }

  27. public String getMobileCountryCode() {
  28.   return mobileCountryCode;
  29. }

  30. public void setMobileCountryCode(String mobileCountryCode) {
  31.   this.mobileCountryCode = mobileCountryCode;
  32. }

  33. public String getMobileNetworkCode() {
  34.   return mobileNetworkCode;
  35. }

  36. public void setMobileNetworkCode(String mobileNetworkCode) {
  37.   this.mobileNetworkCode = mobileNetworkCode;
  38. }

  39. public int getLocationAreaCode() {
  40.   return locationAreaCode;
  41. }

  42. public void setLocationAreaCode(int locationAreaCode) {
  43.   this.locationAreaCode = locationAreaCode;
  44. }

  45. public String getRadioType() {
  46.   return radioType;
  47. }

  48. public void setRadioType(String radioType) {
  49.   this.radioType = radioType;
  50. }

  51. }
复制代码
2、Gps类–>Gps封装类,用来获取经纬度
  1. package com.ljq.activity;

  2. import android.content.Context;
  3. import android.location.Criteria;
  4. import android.location.Location;
  5. import android.location.LocationListener;
  6. import android.location.LocationManager;
  7. import android.os.Bundle;

  8. public class Gps{
  9. private Location location = null;
  10. private LocationManager locationManager = null;
  11. private Context context = null;

  12. /**
  13.   * 初始化
  14.   *
  15.   * @param ctx
  16.   */
  17. public Gps(Context ctx) {
  18.   context=ctx;
  19.   locationManager=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
  20.   location = locationManager.getLastKnownLocation(getProvider());
  21.   locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
  22. }


  23. // 获取Location Provider
  24. private String getProvider() {
  25.   // 构建位置查询条件
  26.   Criteria criteria = new Criteria();
  27.   // 查询精度:高
  28.   criteria.setAccuracy(Criteria.ACCURACY_FINE);
  29.   // 是否查询海拨:否
  30.   criteria.setAltitudeRequired(false);
  31.   // 是否查询方位角 : 否
  32.   criteria.setBearingRequired(false);
  33.   // 是否允许付费:是
  34.   criteria.setCostAllowed(true);
  35.   // 电量要求:低
  36.   criteria.setPowerRequirement(Criteria.POWER_LOW);
  37.   // 返回最合适的符合条件的provider,第2个参数为true说明 , 如果只有一个provider是有效的,则返回当前provider
  38.   return locationManager.getBestProvider(criteria, true);
  39. }

  40. private LocationListener locationListener = new LocationListener() {
  41.   // 位置发生改变后调用
  42.   public void onLocationChanged(Location l) {
  43.    if(l!=null){
  44.     location=l;
  45.    }
  46.   }

  47.   // provider 被用户关闭后调用
  48.   public void onProviderDisabled(String provider) {
  49.    location=null;
  50.   }

  51.   // provider 被用户开启后调用
  52.   public void onProviderEnabled(String provider) {
  53.    Location l = locationManager.getLastKnownLocation(provider);
  54.    if(l!=null){
  55.     location=l;
  56.    }
  57.      
  58.   }

  59.   // provider 状态变化时调用
  60.   public void onStatusChanged(String provider, int status, Bundle extras) {
  61.   }

  62. };
  63.   
  64. public Location getLocation(){
  65.   return location;
  66. }
  67.   
  68. public void closeLocation(){
  69.   if(locationManager!=null){
  70.    if(locationListener!=null){
  71.     locationManager.removeUpdates(locationListener);
  72.     locationListener=null;
  73.    }
  74.    locationManager=null;
  75.   }
  76. }


  77. }
复制代码
3、GpsService服务类
  1. package com.ljq.activity;

  2. import java.util.ArrayList;

  3. import android.app.Service;
  4. import android.content.Intent;
  5. import android.location.Location;
  6. import android.os.IBinder;
  7. import android.util.Log;

  8. public class GpsService extends Service {
  9. ArrayList<CellInfo> cellIds = null;
  10. private Gps gps=null;
  11. private boolean threadDisable=false;
  12. private final static String TAG=GpsService.class.getSimpleName();

  13. @Override
  14. public void onCreate() {
  15.   super.onCreate();
  16.    
  17.   gps=new Gps(GpsService.this);
  18.   cellIds=UtilTool.init(GpsService.this);
  19.    
  20.   new Thread(new Runnable(){
  21.    @Override
  22.    public void run() {
  23.     while (!threadDisable) {
  24.      try {
  25.       Thread.sleep(1000);
  26.      } catch (InterruptedException e) {
  27.       e.printStackTrace();
  28.      }
  29.       
  30.      if(gps!=null){ //当结束服务时gps为空
  31.       //获取经纬度
  32.       Location location=gps.getLocation();
  33.       //如果gps无法获取经纬度,改用基站定位获取
  34.       if(location==null){
  35.        Log.v(TAG, "gps location null");
  36.        //2.根据基站信息获取经纬度
  37.        try {
  38.         location = UtilTool.callGear(GpsService.this, cellIds);
  39.        } catch (Exception e) {
  40.         location=null;
  41.         e.printStackTrace();
  42.        }
  43.        if(location==null){
  44.         Log.v(TAG, "cell location null");
  45.        }
  46.       }
  47.       
  48.       //发送广播
  49.       Intent intent=new Intent();
  50.       intent.putExtra("lat", location==null?"":location.getLatitude()+"");
  51.       intent.putExtra("lon", location==null?"":location.getLongitude()+"");
  52.       intent.setAction("com.ljq.activity.GpsService");
  53.       sendBroadcast(intent);
  54.      }

  55.     }
  56.    }
  57.   }).start();
  58.    
  59. }

  60. @Override
  61. public void onDestroy() {
  62.   threadDisable=true;
  63.   if(cellIds!=null&&cellIds.size()>0){
  64.    cellIds=null;
  65.   }
  66.   if(gps!=null){
  67.    gps.closeLocation();
  68.    gps=null;
  69.   }
  70.   super.onDestroy();
  71. }

  72. @Override
  73. public IBinder onBind(Intent arg0) {
  74.   return null;
  75. }


  76. }
复制代码
4、GpsActivity–>在界面上实时显示经纬度数据
  1. package com.ljq.activity;

  2. import android.app.Activity;
  3. import android.content.BroadcastReceiver;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.content.IntentFilter;
  7. import android.location.Location;
  8. import android.location.LocationManager;
  9. import android.os.Bundle;
  10. import android.util.Log;
  11. import android.widget.EditText;
  12. import android.widget.Toast;

  13. public class GpsActivity extends Activity {
  14. private Double homeLat=26.0673834d; //宿舍纬度
  15. private Double homeLon=119.3119936d; //宿舍经度
  16. private EditText editText = null;
  17. private MyReceiver receiver=null;
  18. private final static String TAG=GpsActivity.class.getSimpleName();

  19. @Override
  20. public void onCreate(Bundle savedInstanceState) {
  21.   super.onCreate(savedInstanceState);
  22.   setContentView(R.layout.main);
  23.    
  24.   editText=(EditText)findViewById(R.id.editText);
  25.    
  26.   //判断GPS是否可用
  27.   Log.i(TAG, UtilTool.isGpsEnabled((LocationManager)getSystemService(Context.LOCATION_SERVICE))+"");
  28.   if(!UtilTool.isGpsEnabled((LocationManager)getSystemService(Context.LOCATION_SERVICE))){
  29.    Toast.makeText(this, "GSP当前已禁用,请在您的系统设置屏幕启动。", Toast.LENGTH_LONG).show();
  30.    Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);  
  31.    startActivity(callGPSSettingIntent);
  32.             return;
  33.   }   
  34.    
  35.   //启动服务
  36.   startService(new Intent(this, GpsService.class));
  37.    
  38.   //注册广播
  39.   receiver=new MyReceiver();
  40.   IntentFilter filter=new IntentFilter();
  41.   filter.addAction("com.ljq.activity.GpsService");
  42.   registerReceiver(receiver, filter);
  43. }
  44.   
  45. //获取广播数据
  46. private class MyReceiver extends BroadcastReceiver{
  47.   @Override
  48.   public void onReceive(Context context, Intent intent) {
  49.    Bundle bundle=intent.getExtras();      
  50.    String lon=bundle.getString("lon");   
  51.    String lat=bundle.getString("lat");
  52.    if(lon!=null&&!"".equals(lon)&&lat!=null&&!"".equals(lat)){
  53.     double distance=getDistance(Double.parseDouble(lat),
  54.       Double.parseDouble(lon), homeLat, homeLon);
  55.     editText.setText("目前经纬度\n经度:"+lon+"\n纬度:"+lat+"\n离宿舍距离:"+java.lang.Math.abs(distance));
  56.    }else{
  57.     editText.setText("目前经纬度\n经度:"+lon+"\n纬度:"+lat);
  58.    }
  59.   }
  60. }
  61.   
  62. @Override
  63. protected void onDestroy() {
  64.   //注销服务
  65.   unregisterReceiver(receiver);
  66.   //结束服务,如果想让服务一直运行就注销此句
  67.   stopService(new Intent(this, GpsService.class));
  68.   super.onDestroy();
  69. }
  70.   
  71. /**
  72.   * 把经纬度换算成距离
  73.   *
  74.   * @param lat1 开始纬度
  75.   * @param lon1 开始经度
  76.   * @param lat2 结束纬度
  77.   * @param lon2 结束经度
  78.   * @return
  79.   */
  80. private double getDistance(double lat1, double lon1, double lat2, double lon2) {
  81.   float[] results = new float[1];
  82.   Location.distanceBetween(lat1, lon1, lat2, lon2, results);
  83.   return results[0];
  84. }  
  85. }
复制代码
5、UtilTool–>工具类
  1. package com.ljq.activity;

  2. import java.io.ByteArrayOutputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.OutputStream;
  6. import java.io.UnsupportedEncodingException;
  7. import java.net.HttpURLConnection;
  8. import java.net.MalformedURLException;
  9. import java.net.ProtocolException;
  10. import java.net.URL;
  11. import java.util.ArrayList;
  12. import java.util.Calendar;
  13. import java.util.List;
  14. import java.util.Locale;

  15. import org.apache.http.client.ClientProtocolException;
  16. import org.json.JSONException;
  17. import org.json.JSONObject;

  18. import android.content.Context;
  19. import android.location.Location;
  20. import android.location.LocationManager;
  21. import android.telephony.NeighboringCellInfo;
  22. import android.telephony.TelephonyManager;
  23. import android.telephony.cdma.CdmaCellLocation;
  24. import android.telephony.gsm.GsmCellLocation;
  25. import android.util.Log;
  26. import android.widget.Toast;

  27. public class UtilTool {
  28. public static boolean isGpsEnabled(LocationManager locationManager) {
  29.   boolean isOpenGPS = locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
  30.   boolean isOpenNetwork = locationManager.isProviderEnabled(android.location.LocationManager.NETWORK_PROVIDER);
  31.   if (isOpenGPS || isOpenNetwork) {
  32.    return true;
  33.   }
  34.   return false;
  35. }
  36.   
  37.     /**
  38.      * 根据基站信息获取经纬度
  39.      *
  40.      * 原理向http://www.google.com/loc/json发送http的post请求,根据google返回的结果获取经纬度
  41.      *
  42.      * @param cellIds
  43.      * @return
  44.      * @throws Exception
  45.      */
  46.     public static Location callGear(Context ctx, ArrayList<CellInfo> cellIds) throws Exception {
  47.      String result="";
  48.      JSONObject data=null;
  49.      if (cellIds == null||cellIds.size()==0) {
  50.       UtilTool.alert(ctx, "cell request param null");
  51.       return null;
  52.      };
  53.       
  54.   try {
  55.    result = UtilTool.getResponseResult(ctx, "http://www.google.com/loc/json", cellIds);
  56.    
  57.    if(result.length() <= 1)
  58.     return null;
  59.    data = new JSONObject(result);
  60.    data = (JSONObject) data.get("location");

  61.    Location loc = new Location(LocationManager.NETWORK_PROVIDER);
  62.    loc.setLatitude((Double) data.get("latitude"));
  63.    loc.setLongitude((Double) data.get("longitude"));
  64.    loc.setAccuracy(Float.parseFloat(data.get("accuracy").toString()));
  65.    loc.setTime(UtilTool.getUTCTime());
  66.    return loc;
  67.   } catch (JSONException e) {
  68.    return null;
  69.   } catch (UnsupportedEncodingException e) {
  70.    e.printStackTrace();
  71.   } catch (ClientProtocolException e) {
  72.    e.printStackTrace();
  73.   } catch (IOException e) {
  74.    e.printStackTrace();
  75.   }
  76.   return null;
  77. }

  78.     /**
  79.      * 接收Google返回的数据格式
  80.      *
  81.   * 出参:{"location":{"latitude":26.0673834,"longitude":119.3119936,
  82.   *       "address":{"country":"??-???","country_code":"CN","region":"?|???o???","city":"?|??·????",
  83.   *       "street":"?o??????-è·ˉ","street_number":"128??·"},"accuracy":935.0},
  84.   *       "access_token":"2:xiU8YrSifFHUAvRJ:aj9k70VJMRWo_9_G"}
  85.   * 请求路径:http://maps.google.cn/maps/geo?key=abcdefg&q=26.0673834,119.3119936
  86.      *
  87.      * @param cellIds
  88.      * @return
  89.      * @throws UnsupportedEncodingException
  90.      * @throws MalformedURLException
  91.      * @throws IOException
  92.      * @throws ProtocolException
  93.      * @throws Exception
  94.      */
  95. public static String getResponseResult(Context ctx,String path, ArrayList<CellInfo> cellInfos)
  96.    throws UnsupportedEncodingException, MalformedURLException,
  97.    IOException, ProtocolException, Exception {
  98.   String result="";
  99.   Log.i(ctx.getApplicationContext().getClass().getSimpleName(),
  100.     "in param: "+getRequestParams(cellInfos));
  101.   InputStream inStream=UtilTool.sendPostRequest(path,
  102.     getRequestParams(cellInfos), "UTF-8");
  103.   if(inStream!=null){
  104.    byte[] datas=UtilTool.readInputStream(inStream);
  105.    if(datas!=null&&datas.length>0){
  106.     result=new String(datas, "UTF-8");
  107.     //Log.i(ctx.getClass().getSimpleName(), "receive result:"+result);//服务器返回的结果信息
  108.     Log.i(ctx.getApplicationContext().getClass().getSimpleName(),
  109.         "google cell receive data result:"+result);
  110.    }else{
  111.     Log.i(ctx.getApplicationContext().getClass().getSimpleName(),
  112.       "google cell receive data null");
  113.    }
  114.   }else{
  115.    Log.i(ctx.getApplicationContext().getClass().getSimpleName(),
  116.        "google cell receive inStream null");
  117.   }
  118.   return result;
  119. }
  120.      
  121.   
  122. /**
  123.   * 拼装json请求参数,拼装基站信息
  124.   *
  125.   * 入参:{'version': '1.1.0','host': 'maps.google.com','home_mobile_country_code': 460,
  126.   *       'home_mobile_network_code': 14136,'radio_type': 'cdma','request_address': true,
  127.   *       'address_language': 'zh_CN','cell_towers':[{'cell_id': '12835','location_area_code': 6,
  128.   *       'mobile_country_code': 460,'mobile_network_code': 14136,'age': 0}]}
  129.   * @param cellInfos
  130.   * @return
  131.   */
  132. public static String getRequestParams(List<CellInfo> cellInfos){
  133.   StringBuffer sb=new StringBuffer("");
  134.   sb.append("{");
  135.   if(cellInfos!=null&&cellInfos.size()>0){
  136.    sb.append("'version': '1.1.0',"); //google api 版本[必]
  137.    sb.append("'host': 'maps.google.com',"); //服务器域名[必]
  138.    sb.append("'home_mobile_country_code': "+cellInfos.get(0).getMobileCountryCode()+","); //移动用户所属国家代号[选 中国460]
  139.    sb.append("'home_mobile_network_code': "+cellInfos.get(0).getMobileNetworkCode()+","); //移动系统号码[默认0]
  140.    sb.append("'radio_type': '"+cellInfos.get(0).getRadioType()+"',"); //信号类型[选 gsm|cdma|wcdma]
  141.    sb.append("'request_address': true,"); //是否返回数据[必]
  142.    sb.append("'address_language': 'zh_CN',"); //反馈数据语言[选 中国 zh_CN]
  143.    sb.append("'cell_towers':["); //移动基站参数对象[必]
  144.    for(CellInfo cellInfo:cellInfos){
  145.     sb.append("{");
  146.     sb.append("'cell_id': '"+cellInfo.getCellId()+"',"); //基站ID[必]
  147.     sb.append("'location_area_code': "+cellInfo.getLocationAreaCode()+","); //地区区域码[必]
  148.     sb.append("'mobile_country_code': "+cellInfo.getMobileCountryCode()+",");
  149.     sb.append("'mobile_network_code': "+cellInfo.getMobileNetworkCode()+",");
  150.     sb.append("'age': 0"); //使用好久的数据库[选 默认0表示使用最新的数据库]
  151.     sb.append("},");
  152.    }
  153.    sb.deleteCharAt(sb.length()-1);
  154.    sb.append("]");
  155.   }
  156.   sb.append("}");
  157.   return sb.toString();
  158. }
  159.      
  160. /**
  161.   * 获取UTC时间
  162.   *
  163.   * UTC + 时区差 = 本地时间(北京为东八区)
  164.   *
  165.   * @return
  166.   */
  167. public static long getUTCTime() {
  168.      //取得本地时间
  169.         Calendar cal = Calendar.getInstance(Locale.CHINA);
  170.         //取得时间偏移量
  171.         int zoneOffset = cal.get(java.util.Calendar.ZONE_OFFSET);
  172.         //取得夏令时差
  173.         int dstOffset = cal.get(java.util.Calendar.DST_OFFSET);
  174.         //从本地时间里扣除这些差量,即可以取得UTC时间
  175.         cal.add(java.util.Calendar.MILLISECOND, -(zoneOffset + dstOffset));
  176.         return cal.getTimeInMillis();
  177.     }
  178. /**
  179.   * 初始化,记得放在onCreate()方法里初始化,获取基站信息
  180.   *
  181.   * @return
  182.   */
  183. public static ArrayList<CellInfo> init(Context ctx) {
  184.   ArrayList<CellInfo> cellInfos = new ArrayList<CellInfo>();
  185.    
  186.   TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
  187.   //网络制式
  188.   int type = tm.getNetworkType();
  189.       /**
  190.      * 获取SIM卡的IMSI码
  191.      * SIM卡唯一标识:IMSI 国际移动用户识别码(IMSI:International Mobile Subscriber Identification Number)是区别移动用户的标志,
  192.      * 储存在SIM卡中,可用于区别移动用户的有效信息。IMSI由MCC、MNC、MSIN组成,其中MCC为移动国家号码,由3位数字组成,
  193.      * 唯一地识别移动客户所属的国家,我国为460;MNC为网络id,由2位数字组成,
  194.      * 用于识别移动客户所归属的移动网络,中国移动为00,中国联通为01,中国电信为03;MSIN为移动客户识别码,采用等长11位数字构成。
  195.      * 唯一地识别国内GSM移动通信网中移动客户。所以要区分是移动还是联通,只需取得SIM卡中的MNC字段即可
  196.    */
  197.   String imsi = tm.getSubscriberId();
  198.   alert(ctx, "imsi: "+imsi);
  199.   //为了区分移动、联通还是电信,推荐使用imsi来判断(万不得己的情况下用getNetworkType()判断,比如imsi为空时)
  200.   if(imsi!=null&&!"".equals(imsi)){
  201.    alert(ctx, "imsi");
  202.    if (imsi.startsWith("46000") || imsi.startsWith("46002")) {// 因为移动网络编号46000下的IMSI已经用完,所以虚拟了一个46002编号,134/159号段使用了此编号
  203.     // 中国移动
  204.     mobile(cellInfos, tm);
  205.    } else if (imsi.startsWith("46001")) {
  206.     // 中国联通
  207.     union(cellInfos, tm);
  208.    } else if (imsi.startsWith("46003")) {
  209.     // 中国电信
  210.     cdma(cellInfos, tm);
  211.    }   
  212.   }else{
  213.    alert(ctx, "type");
  214.    // 在中国,联通的3G为UMTS或HSDPA,电信的3G为EVDO
  215.    // 在中国,移动的2G是EGDE,联通的2G为GPRS,电信的2G为CDMA
  216.    // String OperatorName = tm.getNetworkOperatorName();
  217.    
  218.    //中国电信
  219.    if (type == TelephonyManager.NETWORK_TYPE_EVDO_A
  220.      || type == TelephonyManager.NETWORK_TYPE_EVDO_0
  221.      || type == TelephonyManager.NETWORK_TYPE_CDMA
  222.      || type ==TelephonyManager.NETWORK_TYPE_1xRTT){
  223.     cdma(cellInfos, tm);
  224.    }
  225.    //移动(EDGE(2.75G)是GPRS(2.5G)的升级版,速度比GPRS要快。目前移动基本在国内升级普及EDGE,联通则在大城市部署EDGE。)
  226.    else if(type == TelephonyManager.NETWORK_TYPE_EDGE
  227.      || type == TelephonyManager.NETWORK_TYPE_GPRS ){
  228.     mobile(cellInfos, tm);
  229.    }
  230.    //联通(EDGE(2.75G)是GPRS(2.5G)的升级版,速度比GPRS要快。目前移动基本在国内升级普及EDGE,联通则在大城市部署EDGE。)
  231.    else if(type == TelephonyManager.NETWORK_TYPE_GPRS
  232.      ||type == TelephonyManager.NETWORK_TYPE_EDGE
  233.      ||type == TelephonyManager.NETWORK_TYPE_UMTS
  234.      ||type == TelephonyManager.NETWORK_TYPE_HSDPA){
  235.     union(cellInfos, tm);
  236.    }
  237.   }
  238.    
  239.   return cellInfos;
  240. }


  241. /**
  242.   * 电信
  243.   *
  244.   * @param cellInfos
  245.   * @param tm
  246.   */
  247. private static void cdma(ArrayList<CellInfo> cellInfos, TelephonyManager tm) {
  248.   CdmaCellLocation location = (CdmaCellLocation) tm.getCellLocation();
  249.   CellInfo info = new CellInfo();
  250.   info.setCellId(location.getBaseStationId());
  251.   info.setLocationAreaCode(location.getNetworkId());
  252.   info.setMobileNetworkCode(String.valueOf(location.getSystemId()));
  253.   info.setMobileCountryCode(tm.getNetworkOperator().substring(0, 3));
  254.   info.setRadioType("cdma");
  255.   cellInfos.add(info);
  256.    
  257.   //前面获取到的都是单个基站的信息,接下来再获取周围邻近基站信息以辅助通过基站定位的精准性
  258.   // 获得邻近基站信息
  259.   List<NeighboringCellInfo> list = tm.getNeighboringCellInfo();
  260.   int size = list.size();
  261.   for (int i = 0; i < size; i++) {
  262.    CellInfo cell = new CellInfo();
  263.    cell.setCellId(list.get(i).getCid());
  264.    cell.setLocationAreaCode(location.getNetworkId());
  265.    cell.setMobileNetworkCode(String.valueOf(location.getSystemId()));
  266.    cell.setMobileCountryCode(tm.getNetworkOperator().substring(0, 3));
  267.    cell.setRadioType("cdma");
  268.    cellInfos.add(cell);
  269.   }
  270. }


  271. /**
  272.   * 移动
  273.   *
  274.   * @param cellInfos
  275.   * @param tm
  276.   */
  277. private static void mobile(ArrayList<CellInfo> cellInfos,
  278.    TelephonyManager tm) {
  279.   GsmCellLocation location = (GsmCellLocation)tm.getCellLocation();  
  280.   CellInfo info = new CellInfo();
  281.   info.setCellId(location.getCid());
  282.   info.setLocationAreaCode(location.getLac());
  283.   info.setMobileNetworkCode(tm.getNetworkOperator().substring(3, 5));
  284.   info.setMobileCountryCode(tm.getNetworkOperator().substring(0, 3));
  285.   info.setRadioType("gsm");
  286.   cellInfos.add(info);
  287.    
  288.   //前面获取到的都是单个基站的信息,接下来再获取周围邻近基站信息以辅助通过基站定位的精准性
  289.   // 获得邻近基站信息
  290.   List<NeighboringCellInfo> list = tm.getNeighboringCellInfo();
  291.   int size = list.size();
  292.   for (int i = 0; i < size; i++) {
  293.    CellInfo cell = new CellInfo();
  294.    cell.setCellId(list.get(i).getCid());
  295.    cell.setLocationAreaCode(location.getLac());
  296.    cell.setMobileNetworkCode(tm.getNetworkOperator().substring(3, 5));
  297.    cell.setMobileCountryCode(tm.getNetworkOperator().substring(0, 3));
  298.    cell.setRadioType("gsm");
  299.    cellInfos.add(cell);
  300.   }
  301. }


  302. /**
  303.   *  联通
  304.   *  
  305.   * @param cellInfos
  306.   * @param tm
  307.   */
  308. private static void union(ArrayList<CellInfo> cellInfos, TelephonyManager tm) {
  309.   GsmCellLocation location = (GsmCellLocation)tm.getCellLocation();  
  310.   CellInfo info = new CellInfo();
  311.   //经过测试,获取联通数据以下两行必须去掉,否则会出现错误,错误类型为JSON Parsing Error
  312.   //info.setMobileNetworkCode(tm.getNetworkOperator().substring(3, 5));  
  313.   //info.setMobileCountryCode(tm.getNetworkOperator().substring(0, 3));
  314.   info.setCellId(location.getCid());
  315.   info.setLocationAreaCode(location.getLac());
  316.   info.setMobileNetworkCode("");
  317.   info.setMobileCountryCode("");
  318.   info.setRadioType("gsm");
  319.   cellInfos.add(info);
  320.    
  321.   //前面获取到的都是单个基站的信息,接下来再获取周围邻近基站信息以辅助通过基站定位的精准性
  322.   // 获得邻近基站信息
  323.   List<NeighboringCellInfo> list = tm.getNeighboringCellInfo();
  324.   int size = list.size();
  325.   for (int i = 0; i < size; i++) {
  326.    CellInfo cell = new CellInfo();
  327.    cell.setCellId(list.get(i).getCid());
  328.    cell.setLocationAreaCode(location.getLac());
  329.    cell.setMobileNetworkCode("");
  330.    cell.setMobileCountryCode("");
  331.    cell.setRadioType("gsm");
  332.    cellInfos.add(cell);
  333.   }
  334. }
  335. /**
  336.   * 提示
  337.   *
  338.   * @param ctx
  339.   * @param msg
  340.   */
  341. public static void alert(Context ctx,String msg){
  342.   Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show();
  343. }
  344.   
  345. /**
  346.   * 发送post请求,返回输入流
  347.   *
  348.   * @param path 访问路径
  349.   * @param params json数据格式
  350.   * @param encoding 编码
  351.   * @return
  352.   * @throws UnsupportedEncodingException
  353.   * @throws MalformedURLException
  354.   * @throws IOException
  355.   * @throws ProtocolException
  356.   */
  357. public static InputStream sendPostRequest(String path, String params, String encoding)
  358. throws UnsupportedEncodingException, MalformedURLException,
  359. IOException, ProtocolException {
  360.   byte[] data = params.getBytes(encoding);
  361.   URL url = new URL(path);
  362.   HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  363.   conn.setRequestMethod("POST");
  364.   conn.setDoOutput(true);
  365.   //application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据
  366.   conn.setRequestProperty("Content-Type", "application/x-javascript; charset="+ encoding);
  367.   conn.setRequestProperty("Content-Length", String.valueOf(data.length));
  368.   conn.setConnectTimeout(5 * 1000);
  369.   OutputStream outStream = conn.getOutputStream();
  370.   outStream.write(data);
  371.   outStream.flush();
  372.   outStream.close();
  373.   if(conn.getResponseCode()==200)
  374.    return conn.getInputStream();
  375.   return null;
  376. }
  377.   
  378. /**
  379.   * 发送get请求
  380.   *
  381.   * @param path 请求路径
  382.   * @return
  383.   * @throws Exception
  384.   */
  385. public static String sendGetRequest(String path) throws Exception {
  386.   URL url = new URL(path);
  387.   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  388.   conn.setConnectTimeout(5 * 1000);
  389.   conn.setRequestMethod("GET");
  390.   InputStream inStream = conn.getInputStream();
  391.   byte[] data = readInputStream(inStream);
  392.   String result = new String(data, "UTF-8");
  393.   return result;
  394. }
  395.   
  396. /**
  397.   * 从输入流中读取数据
  398.   * @param inStream
  399.   * @return
  400.   * @throws Exception
  401.   */
  402. public static byte[] readInputStream(InputStream inStream) throws Exception{
  403.   ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  404.   byte[] buffer = new byte[1024];
  405.   int len = 0;
  406.   while( (len = inStream.read(buffer)) !=-1 ){
  407.    outStream.write(buffer, 0, len);
  408.   }
  409.   byte[] data = outStream.toByteArray();//网页的二进制数据
  410.   outStream.close();
  411.   inStream.close();
  412.   return data;
  413. }

  414.   
  415. }
复制代码
6、main.xml–>布局文件
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas./apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent">
  6.     <EditText android:layout_width="fill_parent"
  7.         android:layout_height="wrap_content"
  8.         android:cursorVisible="false"
  9.         android:editable="false"
  10.         android:id="@+id/editText"/>

  11. </LinearLayout>
复制代码
7、清单文件
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas./apk/res/android"
  3. package="com.ljq.activity" android:versionCode="1"
  4. android:versionName="1.0">
  5. <application android:icon="@drawable/icon"
  6.   android:label="@string/app_name">
  7.   <activity android:name=".GpsActivity"
  8.    android:label="@string/app_name">
  9.    <intent-filter>
  10.     <action android:name="android.intent.action.MAIN" />
  11.     <category
  12.      android:name="android.intent.category.LAUNCHER" />
  13.    </intent-filter>
  14.   </activity>
  15.   <service android:label="GPS服务" android:name=".GpsService" />

  16. </application>
  17. <uses-sdk android:minSdkVersion="7" />
  18. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  19. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  20. <uses-permission android:name="android.permission.INTERNET" />
  21. <uses-permission android:name="android.permission.READ_PHONE_STATE" />
  22. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
  23. </manifest>
复制代码
效果如下:


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多