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

本文转自:http://www.apkbus.com/forum.php?mod=viewthread&tid=130732

需求详情:

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. * @author jiqinlin

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

  17. public CellInfo() {
  18. }

  19. public int getCellId() {
  20.   return cellId;
  21. }

  22. public void setCellId(int cellId) {
  23.   this.cellId = cellId;
  24. }

  25. public String getMobileCountryCode() {
  26.   return mobileCountryCode;
  27. }

  28. public void setMobileCountryCode(String mobileCountryCode) {
  29.   this.mobileCountryCode = mobileCountryCode;
  30. }

  31. public String getMobileNetworkCode() {
  32.   return mobileNetworkCode;
  33. }

  34. public void setMobileNetworkCode(String mobileNetworkCode) {
  35.   this.mobileNetworkCode = mobileNetworkCode;
  36. }

  37. public int getLocationAreaCode() {
  38.   return locationAreaCode;
  39. }

  40. public void setLocationAreaCode(int locationAreaCode) {
  41.   this.locationAreaCode = locationAreaCode;
  42. }

  43. public String getRadioType() {
  44.   return radioType;
  45. }

  46. public void setRadioType(String radioType) {
  47.   this.radioType = radioType;
  48. }

  49. }
复制代码
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.      * 原理向http://www.google.com/loc/json发送http的post请求,根据google返回的结果获取经纬度
  40.      * 
  41.      * @param cellIds
  42.      * @return
  43.      * @throws Exception 
  44.      */
  45.     public static Location callGear(Context ctx, ArrayList<CellInfo> cellIds) throws Exception {
  46.      String result="";
  47.      JSONObject data=null;
  48.      if (cellIds == null||cellIds.size()==0) {
  49.       UtilTool.alert(ctx, "cell request param null");
  50.       return null;
  51.      };
  52.       
  53.   try {
  54.    result = UtilTool.getResponseResult(ctx, "http://www.google.com/loc/json", cellIds);
  55.     
  56.    if(result.length() <= 1)
  57.     return null;
  58.    data = new JSONObject(result);
  59.    data = (JSONObject) data.get("location");

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

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


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


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


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

  413.   
  414. }
复制代码
6、main.xml–>布局文件
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/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.android.com/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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值