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;
    }

}  

 

IAddressTask  apn、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();
        }
    }

}  

时间: 2024-09-19 09:09:01

Android之应用APN、WIFI、GPS定位小例子的相关文章

Android开发获取GPS位置,包含apn\wifi\gps 几种方法

一部分:几种定位简述 1.gps定位:   优点:最简单的手机定位方式当然是通过GPS模块(现在大部分的智能机应该都有了).GPS方式准确度是最高的 缺点1.比较耗电:        2.绝大部分用户默认不开启GPS模块:        3.从GPS模块启动到获取第一次定位数据,可能需要比较长的时间:        4.室内几乎无法使用. 这其中,缺点2,3都是比较致命的.需要指出的是,GPS走的是卫星通信的通道,在没有网络连接的情况下也能用.   有网络.室内不可用.定位时间长.位置精确  

Flex AIR应用GPS定位功能(Android和IOS)

说明:使用AIR进行GPS定位功能实现时,会经常判断GPS是否打开.一般的官方或者书上的介绍的方法,测试后,只能对Android系统进行判断,而对ios系统则无法进行判断. 经过研究测试,终于解决实现了能够同时适应于Android和ios系统的GPS定位功能.   实现:  1) 实例化Geolocation类,并添加监听,用于获取经纬度信息   注:geolocation = new Geolocation(); 该实例对象是全局声明,但必须是局部实例化,而不能把它声明为全局的变量实例化(即不

android开发教程之wifi开发示例

1. WIFI网卡的状态WIFI网卡的状态信息都以整型变量的形式存放在 android.net.wifi.WifiManager 类中,有以下状态:WIFI_STATE_DISABLEDWIFI网卡不可用WIFI_STATE_DISABLINGWIFI网卡正在关闭WIFI_STATE_ENABLEDWIFI网卡可用WIFI_STATE_ENABLINGWIFI网卡正在打开WIFI_STATE_UNKNOWNWIFI网卡状态未知2. 操作WIFI 网卡所需的权限CHANGE_NETWORK_STA

Android中实现GPS定位的简单例子_Android

今天弄了一个多小时,写了一个GPS获取地理位置代码的小例子,包括参考了网上的一些代码,并且对代码进行了一些修改,希望对大家的帮助.具体代码如下:  要实用Adnroid平台的GPS设备,首先需要添加上权限,所以需要添加如下权限:  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission> 具体实现代码如下: 首先判断GPS模块是否存在或者是

Android GPS定位详解及实例代码_Android

      GPS定位是智能手机上一个比较有意思的功能,LBS等服务都有效的利用了GPS定位功能.本文就跟大家分享下Android开发中的GPS定位知识.        一.Android基础知识准备        1.Activity类        每一种移动开发环境都有自己的基类.如J2ME应用程序的基类是midlets,BREW的基类是applets,而Android程序的基类是Activity.这个activity为我们提供了对移动操作系统的基本功能和事件的访问.这个类包含了基本的构造

Android中GPS定位的用法实例_Android

GPS定位是目前很多手机都有的功能,且非常实用.本文以实例形式讲述了Android中GPS定位的用法.分享给大家供大家参考之用.具体方法如下: 一般在Android中通过GPS获得当前位置,首先要获得一个LocationManager实例,通过该实例的getLastKnownLocation()方法获得第一个的位置,该方法的说明如下: void android.location.LocationManager.requestLocationUpdates(String provider, lon

Android GPS定位测试(附效果图和示例)

本人做了GPS相关的嵌入式软件已经几年了,所以说起要做个测试GPS定位模块的程序,第一反应就是串口读取GPS模块的数据,然后解析GPS的NMEA格式数据   今天因为工作需要,把以前编写的一个GPS测试程序拿出来重新修改了一下.这个程序说起来有些历史了,是我11年编写的,那时候学了Android 开发没多久,算是一个实验性的作品.现在工作需要,重新拿出来修整.同时发现我对android的GPS服务了解并不深,所以今天特意阅读了有关GPS服 务的一些资料,把相关知识点记录下来. 本人做了GPS相关

Android GPS定位测试(附效果图和示例)_Android

今天因为工作需要,把以前编写的一个GPS测试程序拿出来重新修改了一下.这个程序说起来有些历史了,是我11年编写的,那时候学了Android开发没多久,算是一个实验性的作品.现在工作需要,重新拿出来修整.同时发现我对android的GPS服务了解并不深,所以今天特意阅读了有关GPS服务的一些资料,把相关知识点记录下来. 本人做了GPS相关的嵌入式软件已经几年了,所以说起要做个测试GPS定位模块的程序,第一反应就是串口读取GPS模块的数据,然后解析GPS的NMEA格式数据.NMEA是一种标准化数据格

Android中GPS定位的用法实例

GPS定位是目前很多手机都有的功能,且非常实用.本文以实例形式讲述了Android中GPS定位的用法.分享给大家供大家参考之用.具体方法如下: 一般在Android中通过GPS获得当前位置,首先要获得一个LocationManager实例,通过该实例的getLastKnownLocation()方法获得第一个的位置,该方法的说明如下: void android.location.LocationManager.requestLocationUpdates(String provider, lon