hao0089 发表于 2015-9-30 13:35:28

Android之应用APN、WIFI、GPS定位小例子

  转自一个网上项目,由于是例子打包下载,出处不详。例子中自我写入注释。
  
  Activity类:


package com.maxtech.common;
import com.maxtech.common.gps.GpsTask;
import com.maxtech.common.gps.GpsTaskCallBack;
import com.maxtech.common.gps.GpsTask.GpsData;
import com.maxtech.common.gps.IAddressTask.MLocation;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class GpsActivity extends Activity implements OnClickListener {
    private TextView gps_tip = null;
    //声明AlertDialog
    private AlertDialog dialog = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      //布局主要就是三个按钮与一个Textview
      gps_tip = (TextView) findViewById(R.id.gps_tip);
      findViewById(R.id.do_gps).setOnClickListener(GpsActivity.this);
      findViewById(R.id.do_apn).setOnClickListener(GpsActivity.this);
      findViewById(R.id.do_wifi).setOnClickListener(GpsActivity.this);
      
      //这个ProgressDialog是用于读取数据时显示
      dialog = new ProgressDialog(GpsActivity.this);
      dialog.setTitle("请稍等...");
      dialog.setMessage("正在定位...");
    }
    //各个按钮的工作
    @SuppressWarnings("unchecked")
    @Override
    public void onClick(View v) {
      gps_tip.setText("");
      switch (v.getId()) {
      case R.id.do_apn:
            //进行apn的定位
            do_apn();
            break;
      case R.id.do_gps:
            //进行gps定位
            GpsTask gpstask = new GpsTask(GpsActivity.this,
                  new GpsTaskCallBack() {
                        @Override
                        public void gpsConnectedTimeOut() {
                            gps_tip.setText("获取GPS超时了");
                        }
                        @Override
                        public void gpsConnected(GpsData gpsdata) {
                            do_gps(gpsdata);
                        }
                  }, 30 * 1000);
            gpstask.execute();
            break;
      //进行wifi定位
      case R.id.do_wifi:
            do_wifi();
            break;
      }
    }
    private void do_apn() {
      //异步
      new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                MLocation location = null;
                try {
                  //具体操作
                  location = new AddressTask(GpsActivity.this,
                            AddressTask.DO_APN).doApnPost();
                } catch (Exception e) {
                  e.printStackTrace();
                }
                if(location == null)
                  return null;
                return location.toString();
            }
            //异步操作前执行dialog显示
            @Override
            protected void onPreExecute() {
                dialog.show();
                super.onPreExecute();
            }
            //异步操作后显示相关信息并且关闭dialog
            @Override
            protected void onPostExecute(String result) {
                if(result == null){
                  gps_tip.setText("基站定位失败了...");                  
                }else {
                  gps_tip.setText(result);
                }
                dialog.dismiss();
                super.onPostExecute(result);
            }
            
      }.execute();
    }
    private void do_gps(final GpsData gpsdata) {
      new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                MLocation location = null;
                try {
                  Log.i("do_gpspost", "经纬度" + gpsdata.getLatitude() + "----" + gpsdata.getLongitude());
                  //gps定位具体操作
                  location = new AddressTask(GpsActivity.this,
                            AddressTask.DO_GPS).doGpsPost(gpsdata.getLatitude(),
                                    gpsdata.getLongitude());
                } catch (Exception e) {
                  e.printStackTrace();
                }
                if(location == null)
                  return "GPS信息获取错误";
                return location.toString();
            }
            @Override
            protected void onPreExecute() {
                dialog.show();
                super.onPreExecute();
            }
            @Override
            protected void onPostExecute(String result) {
                gps_tip.setText(result);
                dialog.dismiss();
                super.onPostExecute(result);
            }
            
      }.execute();
    }
    private void do_wifi() {
      new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                MLocation location = null;
                try {
                  location = new AddressTask(GpsActivity.this,
                            AddressTask.DO_WIFI).doWifiPost();
                } catch (Exception e) {
                  e.printStackTrace();
                }
                if(location == null)
                  return null;
                return location.toString();
            }
            @Override
            protected void onPreExecute() {
                dialog.show();
                super.onPreExecute();
            }
            @Override
            protected void onPostExecute(String result) {
                if(result != null){
                  gps_tip.setText(result);
                }else {
                  gps_tip.setText("WIFI定位失败了...");
                }
               
                dialog.dismiss();
                super.onPostExecute(result);
            }
            
      }.execute();
    }

}  

  GPS接口:


package com.maxtech.common.gps;
import com.maxtech.common.gps.GpsTask.GpsData;
public interface GpsTaskCallBack {
    public void gpsConnected(GpsData gpsdata);
   
    public void gpsConnectedTimeOut();
}     

  GpsTask gps的具体实现类:


package com.maxtech.common.gps;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
@SuppressWarnings("rawtypes")
public class GpsTask extends AsyncTask {
    private GpsTaskCallBack callBk = null;
    private Activity context = null;
    private LocationManager locationManager = null;
    private LocationListener locationListener = null;
    private Location location = null;
    private boolean TIME_OUT = false;
    private boolean DATA_CONNTECTED = false;
    private long TIME_DURATION = 5000;
    private GpsHandler handler = null;
            private class GpsHandler extends Handler {
      
                @Override
                public void handleMessage(Message msg) {
                  super.handleMessage(msg);
                  if(callBk == null)
                        return;
                  switch (msg.what) {
                  case 0:
                        callBk.gpsConnected((GpsData)msg.obj);
                        break;
                  case 1:
                        callBk.gpsConnectedTimeOut();
                        break;
                  }
                }
               
            }
    public GpsTask(Activity context, GpsTaskCallBack callBk) {
      this.callBk = callBk;
      this.context = context;
      gpsInit();
    }
    public GpsTask(Activity context, GpsTaskCallBack callBk, long time_out) {
      this.callBk = callBk;
      this.context = context;
      this.TIME_DURATION = time_out;
      gpsInit();
    }
    private void gpsInit() {
      locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
      handler = new GpsHandler();
      if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            
      } else {
            //GPSû�д�
            
            TIME_OUT = true;
      }
      locationListener = new LocationListener() {
            @Override
            public void onStatusChanged(String provider, int status,
                  Bundle extras) {
            }
            @Override
            public void onProviderEnabled(String provider) {
            }
            @Override
            public void onProviderDisabled(String provider) {
            }
            //位置改变才会调用
            @Override
            public void onLocationChanged(Location l) {
                DATA_CONNTECTED = true;
                Message msg = handler.obtainMessage();
                msg.what = 0;
                msg.obj = transData(l);
                handler.sendMessage(msg);
            }
      };
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
                100, locationListener);
    }
    @Override
    protected Object doInBackground(Object... params) {
      while (!TIME_OUT && !DATA_CONNTECTED) {
            location = locationManager
                  .getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (location != null && callBk != null) {
                //�����һ�����
                Message msg = handler.obtainMessage();
                msg.what = 0;
                msg.obj = transData(location);
                handler.sendMessage(msg);
                break;
            }
      }
      return null;
    }
    @Override
    protected void onPreExecute() {
      super.onPreExecute();
      //Timer是自动另外开的一条线程
      Timer timer = new Timer();
      timer.schedule(new TimerTask() {
            @Override
            public void run() {
                TIME_OUT = true;
               
            }
      }, TIME_DURATION);
    }
    @SuppressWarnings("unchecked")
    @Override
    protected void onPostExecute(Object result) {
      locationManager.removeUpdates(locationListener);
      // ��ȡ��ʱ
      if (TIME_OUT && callBk != null){
            handler.sendEmptyMessage(1);
      }
      super.onPostExecute(result);
    }
    private GpsData transData(Location location) {
      GpsData gpsData = new GpsData();
      gpsData.setAccuracy(location.getAccuracy());
      gpsData.setAltitude(location.getAltitude());
      gpsData.setBearing(location.getBearing());
      gpsData.setLatitude(location.getLatitude());
      gpsData.setLongitude(location.getLongitude());
      gpsData.setSpeed(location.getSpeed());
      gpsData.setTime(location.getTime());
      return gpsData;
    }
    public static class GpsData {
      private double latitude = 0;
      private double longitude = 0;
      private float accuracy = 0;
      private double altitude = 0;
      private float bearing = 0;
      private float speed = 0;
      private long time = 0;
      public double getLatitude() {
            return latitude;
      }
      public void setLatitude(double latitude) {
            this.latitude = latitude;
      }
      public double getLongitude() {
            return longitude;
      }
      public void setLongitude(double longitude) {
            this.longitude = longitude;
      }
      public float getAccuracy() {
            return accuracy;
      }
      public void setAccuracy(float accuracy) {
            this.accuracy = accuracy;
      }
      public double getAltitude() {
            return altitude;
      }
      public void setAltitude(double altitude) {
            this.altitude = altitude;
      }
      public float getBearing() {
            return bearing;
      }
      public void setBearing(float bearing) {
            this.bearing = bearing;
      }
      public float getSpeed() {
            return speed;
      }
      public void setSpeed(float speed) {
            this.speed = speed;
      }
      public long getTime() {
            return time;
      }
      public void setTime(long time) {
            this.time = time;
      }
    }

}  
  AddressTask 使用post访问的参数设置


package com.maxtech.common;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONObject;
import android.app.Activity;
import android.net.Proxy;
import com.maxtech.common.gps.IAddressTask;
public class AddressTask extends IAddressTask {
    public static final int DO_APN = 0;
    public static final int DO_WIFI = 1;
    public static final int DO_GPS = 2;
    private int postType = -1;
   
    public AddressTask(Activity context, int postType) {
      super(context);
      this.postType = postType;
    }
   
    @Override
    public HttpResponse execute(JSONObject params) throws Exception {
      HttpClient httpClient = new DefaultHttpClient();
      HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),
                20 * 1000);
      HttpConnectionParams.setSoTimeout(httpClient.getParams(), 20 * 1000);
      
      //访问json
      HttpPost post = new HttpPost("http://74.125.71.147/loc/json");
      // 设置代理
      if (postType == DO_APN) {
            String proxyHost = Proxy.getDefaultHost();
            if(proxyHost != null) {
                HttpHost proxy = new HttpHost(proxyHost, 80);
                httpClient.getParams().setParameter(
                        ConnRouteParams.DEFAULT_PROXY, proxy);
            }
      }
      //请求一系列的参数
      StringEntity se = new StringEntity(params.toString());
      post.setEntity(se);
      HttpResponse response = httpClient.execute(post);
      return response;
    }

}  
  IAddressTaskapn、wifi、gps具体实现类:


package com.maxtech.common.gps;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
public abstract class IAddressTask {
    protected Activity context;
   
    public IAddressTask(Activity context) {
      this.context = context;
    }
   
    public abstract HttpResponse execute(JSONObject params) throws Exception;
   
    public MLocation doWifiPost() throws Exception {
      return transResponse(execute(doWifi()));
    }
   
    public MLocation doApnPost() throws Exception{
      return transResponse(execute(doApn()));
    }
   
    public MLocation doGpsPost(double lat, double lng) throws Exception {
      return transResponse(execute(doGps(lat, lng)));
    }
    private MLocation transResponse(HttpResponse response) {
      MLocation location = null;
      if (response.getStatusLine().getStatusCode() == 200) {
            location = new MLocation();
            HttpEntity entity = response.getEntity();
            BufferedReader br;
            try {
                br = new BufferedReader(new InputStreamReader(
                        entity.getContent()));
                StringBuffer sb = new StringBuffer();
                String result = br.readLine();
                while (result != null) {
                  sb.append(result);
                  result = br.readLine();
                }
                JSONObject json = new JSONObject(sb.toString());
                JSONObject lca = json.getJSONObject("location");
                location.Access_token = json.getString("access_token");
                if (lca != null) {
                  if(lca.has("accuracy"))
                        location.Accuracy = lca.getString("accuracy");
                  if(lca.has("longitude"))
                        location.Longitude = lca.getDouble("longitude");
                  if(lca.has("latitude"))
                        location.Latitude = lca.getDouble("latitude");
                  if(lca.has("address")) {
                        JSONObject address = lca.getJSONObject("address");
                        if (address != null) {
                            if(address.has("region"))
                              location.Region = address.getString("region");
                            if(address.has("street_number"))
                              location.Street_number = address
                                        .getString("street_number");
                            if(address.has("country_code"))
                              location.Country_code = address
                                        .getString("country_code");
                            if(address.has("street"))
                              location.Street = address.getString("street");
                            if(address.has("city"))
                              location.City = address.getString("city");
                            if(address.has("country"))
                              location.Country = address.getString("country");
                        }
                  }
                }
            } catch (Exception e) {
                e.printStackTrace();
                location = null;
            }
      }
      return location;
    }
    private JSONObject doGps(double lat, double lng) throws Exception {
      JSONObject holder = new JSONObject();
      holder.put("version", "1.1.0");
      holder.put("host", "maps.google.com");
      holder.put("address_language", "zh_CN");
      holder.put("request_address", true);
      
      JSONObject data = new JSONObject();
      data.put("latitude", lat);
      data.put("longitude", lng);
      holder.put("location", data);
      return holder;
    }
   
    private JSONObject doApn() throws Exception {
      JSONObject holder = new JSONObject();
      holder.put("version", "1.1.0");
      holder.put("host", "maps.google.com");
      holder.put("address_language", "zh_CN");
      holder.put("request_address", true);
      
      //获得GSM相关信息
      TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
      GsmCellLocation gcl = (GsmCellLocation) tm.getCellLocation();
      int cid = gcl.getCid();
      int lac = gcl.getLac();
      int mcc = Integer.valueOf(tm.getNetworkOperator().substring(0,
                3));
      int mnc = Integer.valueOf(tm.getNetworkOperator().substring(3,
                5));
      //请求参数
      JSONArray array = new JSONArray();
      JSONObject data = new JSONObject();
      data.put("cell_id", cid);
      data.put("location_area_code", lac);
      data.put("mobile_country_code", mcc);
      data.put("mobile_network_code", mnc);
      array.put(data);
      holder.put("cell_towers", array);
      
      return holder;
    }
   
    private JSONObject doWifi() throws Exception {
      JSONObject holder = new JSONObject();
      holder.put("version", "1.1.0");
      holder.put("host", "maps.google.com");
      holder.put("address_language", "zh_CN");
      holder.put("request_address", true);
      
      //获得wifi相关信息
      WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
      
      if(wifiManager.getConnectionInfo().getBSSID() == null) {
            throw new RuntimeException("bssid is null");
      }
      
      JSONArray array = new JSONArray();
      JSONObject data = new JSONObject();
      data.put("mac_address", wifiManager.getConnectionInfo().getBSSID());
      data.put("signal_strength", 8);
      data.put("age", 0);
      array.put(data);
      holder.put("wifi_towers", array);
      
      return holder;
    }
    public static class MLocation {
      public String Access_token;
      public double Latitude;
      public double Longitude;
      public String Accuracy;
      public String Region;
      public String Street_number;
      public String Country_code;
      public String Street;
      public String City;
      public String Country;
      @Override
      public String toString() {
            StringBuffer buffer = new StringBuffer();
            buffer.append("Access_token:" + Access_token + "\n");
            buffer.append("Region:" + Region + "\n");
            buffer.append("Accuracy:" + Accuracy + "\n");
            buffer.append("Latitude:" + Latitude + "\n");
            buffer.append("Longitude:" + Longitude + "\n");
            buffer.append("Country_code:" + Country_code + "\n");
            buffer.append("Country:" + Country + "\n");
            buffer.append("City:" + City + "\n");
            buffer.append("Street:" + Street + "\n");
            buffer.append("Street_number:" + Street_number + "\n");
            return buffer.toString();
      }
    }

}  
页: [1]
查看完整版本: Android之应用APN、WIFI、GPS定位小例子