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();
        }
    }
}  
相关文章
Flutter 与原生模块(Android 和 iOS)之间的通信机制,包括方法调用、事件传递等,分析了通信的必要性、主要方式、数据传递、性能优化及错误处理,并通过实际案例展示了其应用效果,展望了未来的发展趋势
本文深入探讨了 Flutter 与原生模块(Android 和 iOS)之间的通信机制,包括方法调用、事件传递等,分析了通信的必要性、主要方式、数据传递、性能优化及错误处理,并通过实际案例展示了其应用效果,展望了未来的发展趋势。这对于实现高效的跨平台移动应用开发具有重要指导意义。
625 4
如何查看Flutter应用在Android设备上已被撤销的权限?
如何查看Flutter应用在Android设备上已被撤销的权限?
25 7
【08】flutter完成屏幕适配-重建Android,增加GetX路由,屏幕适配,基础导航栏-多版本SDK以及gradle造成的关于fvm的使用(flutter version manage)-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
【08】flutter完成屏幕适配-重建Android,增加GetX路由,屏幕适配,基础导航栏-多版本SDK以及gradle造成的关于fvm的使用(flutter version manage)-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
227 20
【08】flutter完成屏幕适配-重建Android,增加GetX路由,屏幕适配,基础导航栏-多版本SDK以及gradle造成的关于fvm的使用(flutter version manage)-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
【09】flutter首页进行了完善-采用android studio 进行真机调试开发-增加了直播间列表和短视频人物列表-增加了用户中心-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
【09】flutter首页进行了完善-采用android studio 进行真机调试开发-增加了直播间列表和短视频人物列表-增加了用户中心-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
74 4
【09】flutter首页进行了完善-采用android studio 进行真机调试开发-增加了直播间列表和短视频人物列表-增加了用户中心-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
探索安卓开发:打造你的首个天气应用
在这篇技术指南中,我们将一起潜入安卓开发的海洋,学习如何从零开始构建一个简单的天气应用。通过这个实践项目,你将掌握安卓开发的核心概念、界面设计、网络编程以及数据解析等技能。无论你是初学者还是有一定基础的开发者,这篇文章都将为你提供一个清晰的路线图和实用的代码示例,帮助你在安卓开发的道路上迈出坚实的一步。让我们一起开始这段旅程,打造属于你自己的第一个安卓应用吧!
145 14
探索安卓开发:打造你的第一款应用
在数字时代的浪潮中,每个人都有机会成为创意的实现者。本文将带你走进安卓开发的奇妙世界,通过浅显易懂的语言和实际代码示例,引导你从零开始构建自己的第一款安卓应用。无论你是编程新手还是希望拓展技术的开发者,这篇文章都将为你打开一扇门,让你的创意和技术一起飞扬。
101 13
打造个性化安卓应用:从设计到开发的全面指南
在这个数字时代,拥有一个定制的移动应用不仅是一种趋势,更是个人或企业品牌的重要延伸。本文将引导你通过一系列简单易懂的步骤,从构思你的应用理念开始,直至实现一个功能齐全的安卓应用。无论你是编程新手还是希望拓展技能的开发者,这篇文章都将为你提供必要的工具和知识,帮助你将创意转化为现实。
探索安卓开发之旅:打造你的第一个天气应用
【10月更文挑战第30天】在这个数字时代,掌握移动应用开发技能无疑是进入IT行业的敲门砖。本文将引导你开启安卓开发的奇妙之旅,通过构建一个简易的天气应用来实践你的编程技能。无论你是初学者还是有一定经验的开发者,这篇文章都将成为你宝贵的学习资源。我们将一步步地深入到安卓开发的世界中,从搭建开发环境到实现核心功能,每个环节都充满了发现和创造的乐趣。让我们开始吧,一起在代码的海洋中航行!
打造个性化安卓应用:从设计到实现
【10月更文挑战第30天】在数字化时代,拥有一个个性化的安卓应用不仅能够提升用户体验,还能加强品牌识别度。本文将引导您了解如何从零开始设计和实现一个安卓应用,涵盖用户界面设计、功能开发和性能优化等关键环节。我们将以一个简单的记事本应用为例,展示如何通过Android Studio工具和Java语言实现基本功能,同时确保应用流畅运行。无论您是初学者还是希望提升现有技能的开发者,这篇文章都将为您提供宝贵的见解和实用的技巧。
探索安卓开发:构建你的第一个“Hello World”应用
在安卓开发的浩瀚海洋中,每个新手都渴望扬帆起航。本文将作为你的指南针,引领你通过创建一个简单的“Hello World”应用,迈出安卓开发的第一步。我们将一起搭建开发环境、了解基本概念,并编写第一行代码。就像印度圣雄甘地所说:“你必须成为你希望在世界上看到的改变。”让我们一起开始这段旅程,成为我们想要见到的开发者吧!
118 0

热门文章

最新文章

下一篇
oss创建bucket
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等