乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      Android Service獲取當(dāng)前位置(GPS+基站)

       QCamera 2014-12-15

      需求詳情:

      1)、Service中每隔1秒執(zhí)行一次定位操作(GPS+基站)
      2)、定位的結(jié)果實(shí)時(shí)顯示在界面上(要求得到經(jīng)度、緯度)
      技術(shù)支持:
      1)、獲取經(jīng)緯度
      通過(guò)GPS+基站獲取經(jīng)緯度,先通過(guò)GPS來(lái)獲取,如果為空改用基站進(jìn)行獲取–>GPS+基站(基站獲取支持聯(lián)通、電信、移動(dòng))。
      2)、實(shí)時(shí)獲取經(jīng)緯度
      為了達(dá)到實(shí)時(shí)獲取經(jīng)緯度,需在后臺(tái)啟動(dòng)獲取經(jīng)緯度的Service,然后把經(jīng)緯度數(shù)據(jù)通過(guò)廣播發(fā)送出去,在需要的地方進(jìn)行廣播注冊(cè)(比如在Activity中注冊(cè)廣播,顯示在界面中)–>涉及到Service+BroadcastReceiver+Activity+Thread等知識(shí)點(diǎn)。
      備注:本文注重實(shí)踐,如有看不懂的,先去鞏固下知識(shí)點(diǎn),可以去看看我前面寫(xiě)的幾篇文章。
      1、CellInfo實(shí)體類(lèi)–>基站信息
      1. package com.ljq.activity;

      2. /**
      3. * 基站信息
      4. *
      5. * @author jiqinlin
      6. *
      7. */
      8. public class CellInfo {
      9. /** 基站id,用來(lái)找到基站的位置 */
      10. private int cellId;
      11. /** 移動(dòng)國(guó)家碼,共3位,中國(guó)為460,即imsi前3位 */
      12. private String mobileCountryCode="460";
      13. /** 移動(dòng)網(wǎng)絡(luò)碼,共2位,在中國(guó),移動(dòng)的代碼為00和02,聯(lián)通的代碼為01,電信的代碼為03,即imsi第4~5位 */
      14. private String mobileNetworkCode="0";
      15. /** 地區(qū)區(qū)域碼 */
      16. private int locationAreaCode;
      17. /** 信號(hào)類(lèi)型[選 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. }
      復(fù)制代碼
      2、Gps類(lèi)–>Gps封裝類(lèi),用來(lái)獲取經(jīng)緯度
      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.   // 構(gòu)建位置查詢條件
      26.   Criteria criteria = new Criteria();
      27.   // 查詢精度:高
      28.   criteria.setAccuracy(Criteria.ACCURACY_FINE);
      29.   // 是否查詢海撥:否
      30.   criteria.setAltitudeRequired(false);
      31.   // 是否查詢方位角 : 否
      32.   criteria.setBearingRequired(false);
      33.   // 是否允許付費(fèi):是
      34.   criteria.setCostAllowed(true);
      35.   // 電量要求:低
      36.   criteria.setPowerRequirement(Criteria.POWER_LOW);
      37.   // 返回最合適的符合條件的provider,第2個(gè)參數(shù)為true說(shuō)明 , 如果只有一個(gè)provider是有效的,則返回當(dāng)前provider
      38.   return locationManager.getBestProvider(criteria, true);
      39. }

      40. private LocationListener locationListener = new LocationListener() {
      41.   // 位置發(fā)生改變后調(diào)用
      42.   public void onLocationChanged(Location l) {
      43.    if(l!=null){
      44.     location=l;
      45.    }
      46.   }

      47.   // provider 被用戶關(guān)閉后調(diào)用
      48.   public void onProviderDisabled(String provider) {
      49.    location=null;
      50.   }

      51.   // provider 被用戶開(kāi)啟后調(diào)用
      52.   public void onProviderEnabled(String provider) {
      53.    Location l = locationManager.getLastKnownLocation(provider);
      54.    if(l!=null){
      55.     location=l;
      56.    }
      57.      
      58.   }

      59.   // provider 狀態(tài)變化時(shí)調(diào)用
      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. }
      復(fù)制代碼
      3、GpsService服務(wù)類(lèi)
      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){ //當(dāng)結(jié)束服務(wù)時(shí)gps為空
      31.       //獲取經(jīng)緯度
      32.       Location location=gps.getLocation();
      33.       //如果gps無(wú)法獲取經(jīng)緯度,改用基站定位獲取
      34.       if(location==null){
      35.        Log.v(TAG, "gps location null");
      36.        //2.根據(jù)基站信息獲取經(jīng)緯度
      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.       //發(fā)送廣播
      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. }
      復(fù)制代碼
      4、GpsActivity–>在界面上實(shí)時(shí)顯示經(jīng)緯度數(shù)據(jù)
      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; //宿舍經(jīng)度
      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當(dāng)前已禁用,請(qǐng)?jiān)谀南到y(tǒng)設(shè)置屏幕啟動(dòng)。", Toast.LENGTH_LONG).show();
      30.    Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);  
      31.    startActivity(callGPSSettingIntent);
      32.             return;
      33.   }   
      34.    
      35.   //啟動(dòng)服務(wù)
      36.   startService(new Intent(this, GpsService.class));
      37.    
      38.   //注冊(cè)廣播
      39.   receiver=new MyReceiver();
      40.   IntentFilter filter=new IntentFilter();
      41.   filter.addAction("com.ljq.activity.GpsService");
      42.   registerReceiver(receiver, filter);
      43. }
      44.   
      45. //獲取廣播數(shù)據(jù)
      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("目前經(jīng)緯度\n經(jīng)度:"+lon+"\n緯度:"+lat+"\n離宿舍距離:"+java.lang.Math.abs(distance));
      56.    }else{
      57.     editText.setText("目前經(jīng)緯度\n經(jīng)度:"+lon+"\n緯度:"+lat);
      58.    }
      59.   }
      60. }
      61.   
      62. @Override
      63. protected void onDestroy() {
      64.   //注銷(xiāo)服務(wù)
      65.   unregisterReceiver(receiver);
      66.   //結(jié)束服務(wù),如果想讓服務(wù)一直運(yùn)行就注銷(xiāo)此句
      67.   stopService(new Intent(this, GpsService.class));
      68.   super.onDestroy();
      69. }
      70.   
      71. /**
      72.   * 把經(jīng)緯度換算成距離
      73.   *
      74.   * @param lat1 開(kāi)始緯度
      75.   * @param lon1 開(kāi)始經(jīng)度
      76.   * @param lat2 結(jié)束緯度
      77.   * @param lon2 結(jié)束經(jīng)度
      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. }
      復(fù)制代碼
      5、UtilTool–>工具類(lèi)
      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.      * 根據(jù)基站信息獲取經(jīng)緯度
      39.      *
      40.      * 原理向http://www.google.com/loc/json發(fā)送http的post請(qǐng)求,根據(jù)google返回的結(jié)果獲取經(jīng)緯度
      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返回的數(shù)據(jù)格式
      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.   * 請(qǐng)求路徑: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);//服務(wù)器返回的結(jié)果信息
      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請(qǐng)求參數(shù),拼裝基站信息
      124.   *
      125.   * 入?yún)ⅲ簕'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',"); //服務(wù)器域名[必]
      138.    sb.append("'home_mobile_country_code': "+cellInfos.get(0).getMobileCountryCode()+","); //移動(dòng)用戶所屬?lài)?guó)家代號(hào)[選 中國(guó)460]
      139.    sb.append("'home_mobile_network_code': "+cellInfos.get(0).getMobileNetworkCode()+","); //移動(dòng)系統(tǒng)號(hào)碼[默認(rèn)0]
      140.    sb.append("'radio_type': '"+cellInfos.get(0).getRadioType()+"',"); //信號(hào)類(lèi)型[選 gsm|cdma|wcdma]
      141.    sb.append("'request_address': true,"); //是否返回?cái)?shù)據(jù)[必]
      142.    sb.append("'address_language': 'zh_CN',"); //反饋數(shù)據(jù)語(yǔ)言[選 中國(guó) zh_CN]
      143.    sb.append("'cell_towers':["); //移動(dòng)基站參數(shù)對(duì)象[必]
      144.    for(CellInfo cellInfo:cellInfos){
      145.     sb.append("{");
      146.     sb.append("'cell_id': '"+cellInfo.getCellId()+"',"); //基站ID[必]
      147.     sb.append("'location_area_code': "+cellInfo.getLocationAreaCode()+","); //地區(qū)區(qū)域碼[必]
      148.     sb.append("'mobile_country_code': "+cellInfo.getMobileCountryCode()+",");
      149.     sb.append("'mobile_network_code': "+cellInfo.getMobileNetworkCode()+",");
      150.     sb.append("'age': 0"); //使用好久的數(shù)據(jù)庫(kù)[選 默認(rèn)0表示使用最新的數(shù)據(jù)庫(kù)]
      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時(shí)間
      162.   *
      163.   * UTC + 時(shí)區(qū)差 = 本地時(shí)間(北京為東八區(qū))
      164.   *
      165.   * @return
      166.   */
      167. public static long getUTCTime() {
      168.      //取得本地時(shí)間
      169.         Calendar cal = Calendar.getInstance(Locale.CHINA);
      170.         //取得時(shí)間偏移量
      171.         int zoneOffset = cal.get(java.util.Calendar.ZONE_OFFSET);
      172.         //取得夏令時(shí)差
      173.         int dstOffset = cal.get(java.util.Calendar.DST_OFFSET);
      174.         //從本地時(shí)間里扣除這些差量,即可以取得UTC時(shí)間
      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.   //網(wǎng)絡(luò)制式
      188.   int type = tm.getNetworkType();
      189.       /**
      190.      * 獲取SIM卡的IMSI碼
      191.      * SIM卡唯一標(biāo)識(shí):IMSI 國(guó)際移動(dòng)用戶識(shí)別碼(IMSI:International Mobile Subscriber Identification Number)是區(qū)別移動(dòng)用戶的標(biāo)志,
      192.      * 儲(chǔ)存在SIM卡中,可用于區(qū)別移動(dòng)用戶的有效信息。IMSI由MCC、MNC、MSIN組成,其中MCC為移動(dòng)國(guó)家號(hào)碼,由3位數(shù)字組成,
      193.      * 唯一地識(shí)別移動(dòng)客戶所屬的國(guó)家,我國(guó)為460;MNC為網(wǎng)絡(luò)id,由2位數(shù)字組成,
      194.      * 用于識(shí)別移動(dòng)客戶所歸屬的移動(dòng)網(wǎng)絡(luò),中國(guó)移動(dòng)為00,中國(guó)聯(lián)通為01,中國(guó)電信為03;MSIN為移動(dòng)客戶識(shí)別碼,采用等長(zhǎng)11位數(shù)字構(gòu)成。
      195.      * 唯一地識(shí)別國(guó)內(nèi)GSM移動(dòng)通信網(wǎng)中移動(dòng)客戶。所以要區(qū)分是移動(dòng)還是聯(lián)通,只需取得SIM卡中的MNC字段即可
      196.    */
      197.   String imsi = tm.getSubscriberId();
      198.   alert(ctx, "imsi: "+imsi);
      199.   //為了區(qū)分移動(dòng)、聯(lián)通還是電信,推薦使用imsi來(lái)判斷(萬(wàn)不得己的情況下用getNetworkType()判斷,比如imsi為空時(shí))
      200.   if(imsi!=null&&!"".equals(imsi)){
      201.    alert(ctx, "imsi");
      202.    if (imsi.startsWith("46000") || imsi.startsWith("46002")) {// 因?yàn)橐苿?dòng)網(wǎng)絡(luò)編號(hào)46000下的IMSI已經(jīng)用完,所以虛擬了一個(gè)46002編號(hào),134/159號(hào)段使用了此編號(hào)
      203.     // 中國(guó)移動(dòng)
      204.     mobile(cellInfos, tm);
      205.    } else if (imsi.startsWith("46001")) {
      206.     // 中國(guó)聯(lián)通
      207.     union(cellInfos, tm);
      208.    } else if (imsi.startsWith("46003")) {
      209.     // 中國(guó)電信
      210.     cdma(cellInfos, tm);
      211.    }   
      212.   }else{
      213.    alert(ctx, "type");
      214.    // 在中國(guó),聯(lián)通的3G為UMTS或HSDPA,電信的3G為EVDO
      215.    // 在中國(guó),移動(dòng)的2G是EGDE,聯(lián)通的2G為GPRS,電信的2G為CDMA
      216.    // String OperatorName = tm.getNetworkOperatorName();
      217.    
      218.    //中國(guó)電信
      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.    //移動(dòng)(EDGE(2.75G)是GPRS(2.5G)的升級(jí)版,速度比GPRS要快。目前移動(dòng)基本在國(guó)內(nèi)升級(jí)普及EDGE,聯(lián)通則在大城市部署EDGE。)
      226.    else if(type == TelephonyManager.NETWORK_TYPE_EDGE
      227.      || type == TelephonyManager.NETWORK_TYPE_GPRS ){
      228.     mobile(cellInfos, tm);
      229.    }
      230.    //聯(lián)通(EDGE(2.75G)是GPRS(2.5G)的升級(jí)版,速度比GPRS要快。目前移動(dòng)基本在國(guó)內(nèi)升級(jí)普及EDGE,聯(lián)通則在大城市部署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.   //前面獲取到的都是單個(gè)基站的信息,接下來(lái)再獲取周?chē)徑拘畔⒁暂o助通過(guò)基站定位的精準(zhǔn)性
      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.   * 移動(dòng)
      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.   //前面獲取到的都是單個(gè)基站的信息,接下來(lái)再獲取周?chē)徑拘畔⒁暂o助通過(guò)基站定位的精準(zhǔn)性
      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.   *  聯(lián)通
      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.   //經(jīng)過(guò)測(cè)試,獲取聯(lián)通數(shù)據(jù)以下兩行必須去掉,否則會(huì)出現(xiàn)錯(cuò)誤,錯(cuò)誤類(lèi)型為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.   //前面獲取到的都是單個(gè)基站的信息,接下來(lái)再獲取周?chē)徑拘畔⒁暂o助通過(guò)基站定位的精準(zhǔn)性
      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.   * 發(fā)送post請(qǐng)求,返回輸入流
      347.   *
      348.   * @param path 訪問(wèn)路徑
      349.   * @param params json數(shù)據(jù)格式
      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數(shù)據(jù) application/x-javascript->json對(duì)象 application/x-www-form-urlencoded->表單數(shù)據(jù)
      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.   * 發(fā)送get請(qǐng)求
      380.   *
      381.   * @param path 請(qǐng)求路徑
      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.   * 從輸入流中讀取數(shù)據(jù)
      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();//網(wǎng)頁(yè)的二進(jìn)制數(shù)據(jù)
      410.   outStream.close();
      411.   inStream.close();
      412.   return data;
      413. }

      414.   
      415. }
      復(fù)制代碼
      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>
      復(fù)制代碼
      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服務(wù)" 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>
      復(fù)制代碼
      效果如下:


        本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買(mǎi)等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
        轉(zhuǎn)藏 分享 獻(xiàn)花(0

        0條評(píng)論

        發(fā)表

        請(qǐng)遵守用戶 評(píng)論公約

        類(lèi)似文章 更多