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

简介:
一部分:几种定位简述
1.gps定位:
 
优点:最简单的手机定位方式当然是通过GPS模块(现在大部分的智能机应该都有了)。GPS方式准确度是最高的
缺点1.比较耗电;
       2.绝大部分用户默认不开启GPS模块;
       3.从GPS模块启动到获取第一次定位数据,可能需要比较长的时间;
       4.室内几乎无法使用。
这其中,缺点2,3都是比较致命的。需要指出的是,GPS走的是卫星通信的通道,在没有网络连接的情况下也能用。
 
有网络、室内不可用、定位时间长、位置精确
 
2.基站定位
大致思路就是采集到手机上的基站ID号(cellid)和其它的一些信息(MNC,MCC,LAC等等),然后通过网络访问一些定位服务,获取 并返回对应的经纬度坐标。基站定位的精确度不如GPS,好处是能够在室内用,只要网络通畅就行。
 
有网络 室内可用 定位方式不精确
 
3.WIFI定位
和基站定位类似,这种方式是通过获取当前所用的wifi的一些信息,然后访问网络上的定位服务以获得经纬度坐标。因为它和基站定位其实都需要使 用网络,所以在Android也统称为Network方式。
 
与基站定位类似
 
4.AGPS定位
最后需要解释一点的是AGPS方式。很多人将它和基站定位混为一谈,但其实AGPS的本质仍然是GPS,只是它会使用基站信息对获取GPS进行辅助,然后 还能对获取到的GPS结果进行修正,所以AGPS要比传统的GPS更快,准确度略高。
 
有网络、类似gps定位、但比传统Gps定位更快,准确度略高
 
第二部分:
locationManager.getLastKnownLocation()总是会出现取不到数据的情况,所以这里没有使用这个方法,避免 了取不到数据的问题
 
第三部分:使用异步加载,提高性能
 
================================代码===========================
 

\  \

 

 

1.Activity

package com.example.gpsdemo;  
 
import com.example.gpsdemo.util.GetLocation;  
import com.example.gpsdemo.util.LMLocation;  
 
import android.app.Activity;  
import android.app.AlertDialog;  
import android.app.ProgressDialog;  
import android.os.Bundle;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.widget.Button;  
import android.widget.TextView;  
 
public class MainActivity extends Activity {  
    LMLocation lmLocation;  
    TextView textView;  
    public MainActivity instance;  
    private AlertDialog dialog;  
    @Override
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        textView = (TextView) findViewById(R.id.textView2);  
        instance = this;  
        dialog = new ProgressDialog(MainActivity.this);  
        dialog.setTitle("请稍等...");  
        dialog.setMessage("正在定位...");  
        Button button = (Button) findViewById(R.id.button1);  
        button.setOnClickListener(new OnClickListener() {  
 
            @Override
            public void onClick(View v) {  
                // TODO Auto-generated method stub
                new GetLocation(dialog, textView, instance).DisplayLocation();  
            }  
        });  
 
    }  
 
}  

2.与MainActivity对应的布局

<xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
     
       <android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:padding="@dimen/padding_medium"
        android:text="@string/hello_world"
        tools:context=".MainActivity" />
 
     
        <android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/textView2"
        android:layout_marginRight="52dp"
        android:text="定位" />

3.AndroidManifest.xml

  1. package="com.example.gpsdemo"
  2.     android:versionCode="1"
  3.     android:versionName="1.0" >
  4.  
  5.     <uses-sdk< li="">
  6.         android:minSdkVersion="8"
  7.         android:targetSdkVersion="15" />
  8.  
  9.     <application< li="">
  10.         android:icon="@drawable/ic_launcher"
  11.         android:label="@string/app_name"
  12.         android:theme="@style/AppTheme" >
  13.         <activity< li="">
  14.             android:name=".MainActivity"
  15.             android:label="@string/title_activity_main" >
4.工具类两个:(1)

package com.example.gpsdemo.util;  
 
import android.app.AlertDialog;  
import android.content.Context;  
import android.os.AsyncTask;  
import android.util.Log;  
import android.widget.TextView;  
 
public class GetLocation {  
    AlertDialog dialog;  
    TextView textView;  
    Context context;  
 
    public GetLocation(AlertDialog dialog, TextView textView, Context context) {  
        this.dialog = dialog;  
        this.textView = textView;  
        this.context = context;  
 
    }  
 
    public void DisplayLocation() {  
        new AsyncTask() {  
 
            @Override
            protected String doInBackground=\'#\'"  
                LMLocation location = null;  
                try {  
                    location = new GPSLocation().getGPSInfo(context);  
                } catch (Exception e) {  
                    // TODO Auto-generated catch block
                    e.printStackTrace();  
                }  
                if (location == null)  
                    return null;  
                Log.d("debug", location.toString());  
                return location.toString();  
 
            }  
 
            @Override
            protected void onPreExecute() {  
                dialog.show();  
                super.onPreExecute();  
            }  
 
            @Override
            protected void onPostExecute(String result) {  
                if (result == null) {  
                    textView.setText("定位失败了...");  
                } else {  
                    textView.setText(result);  
                }  
                dialog.dismiss();  
                super.onPostExecute(result);  
            }  
 
        }.execute();  
    }  
 
}  

2.

package com.example.gpsdemo.util;  
 
import java.io.BufferedReader;  
import java.io.InputStreamReader;  
 
import org.apache.http.HttpEntity;  
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.JSONArray;  
import org.json.JSONObject;  
 
import android.content.Context;  
import android.database.Cursor;  
import android.net.ConnectivityManager;  
import android.net.NetworkInfo.State;  
import android.net.Uri;  
import android.net.wifi.WifiManager;  
import android.telephony.TelephonyManager;  
import android.telephony.gsm.GsmCellLocation;  
import android.util.Log;  
 
/**
 * ******************************************
 * 描述::GPS信息获取
 * @version 2.0
 ******************************************** 
 */
public class GPSLocation {  
    private static int postType = -1;  
    public static final int DO_3G = 0;  
    public static final int DO_WIFI = 1;  
    public static final int NO_CONNECTION = 2;  
 
    /**
     * 网络方式检查
     */
    private static int netCheck(Context context) {  
        ConnectivityManager conMan = (ConnectivityManager) context  
                .getSystemService(Context.CONNECTIVITY_SERVICE);  
        State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)  
                .getState();  
        State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI)  
                .getState();  
        if (wifi.equals(State.CONNECTED)) {  
            return DO_WIFI;  
        } else if (mobile.equals(State.CONNECTED)) {  
            return DO_3G;  
        } else {  
            return NO_CONNECTION;  
        }  
    }  
 
    /**
     * 获取WifiManager获取信息
     */
    private static JSONObject getInfoByWifiManager(Context context)  
            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);  
 
        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;  
    }  
 
    /**
     * 获取TelephoneManager获取信息
     */
    private static JSONObject getInfoByTelephoneManager(Context context)  
            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);  
        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;  
    }  
 
    /**
     * 通过wifi获取GPS信息
     */
    private static HttpResponse connectionForGPS(Context context)  
            throws Exception {  
        HttpResponse httpResponse = null;  
        postType = netCheck(context);  
        if (postType == NO_CONNECTION) {  
            return null;  
        } else {  
            if (postType == DO_WIFI) {  
                if ((httpResponse = doOrdinary(context,  
                        getInfoByWifiManager(context))) != null) {  
                    return httpResponse;  
                } else if ((httpResponse = doAPN(context,  
                        getInfoByWifiManager(context))) != null) {  
                    return httpResponse;  
                } else if ((httpResponse = doOrdinary(context,  
                        getInfoByTelephoneManager(context))) != null) {  
                    return httpResponse;  
                } else if ((httpResponse = doAPN(context,  
                        getInfoByTelephoneManager(context))) != null) {  
                    return httpResponse;  
                }  
            }  
            if (postType == DO_3G) {  
                if ((httpResponse = doOrdinary(context,  
                        getInfoByTelephoneManager(context))) != null) {  
                    return httpResponse;  
                } else if ((httpResponse = doAPN(context,  
                        getInfoByTelephoneManager(context))) != null) {  
                    return httpResponse;  
                }  
            }  
            return null;  
        }  
    }  
 
    /**
     * 通过普通方式定位
     */
    private static HttpResponse doOrdinary(Context context, JSONObject holder) {  
        HttpResponse response = null;  
        try {  
            HttpClient httpClient = new DefaultHttpClient();  
            HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),  
                    20 * 1000);  
            HttpConnectionParams  
                    .setSoTimeout(httpClient.getParams(), 20 * 1000);  
            HttpPost post = new HttpPost("http://74.125.71.147/loc/json");  
            StringEntity se = new StringEntity(holder.toString());  
            post.setEntity(se);  
            response = httpClient.execute(post);  
        } catch (Exception e) {  
            e.printStackTrace();  
            return null;  
        }  
        return response;  
    }  
 
    /**
     * 通过基站定位
     */
    private static HttpResponse doAPN(Context context, JSONObject holder) {  
        HttpResponse response = null;  
        try {  
            HttpClient httpClient = new DefaultHttpClient();  
            HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),  
                    20 * 1000);  
            HttpConnectionParams  
                    .setSoTimeout(httpClient.getParams(), 20 * 1000);  
            HttpPost post = new HttpPost("http://74.125.71.147/loc/json");  
            // 设置代理
            Uri uri = Uri.parse("content://telephony/carriers/preferapn"); // 获取当前正在使用的APN接入点  
            Cursor mCursor = context.getContentResolver().query(uri, null,  
                    null, null, null);  
            if (mCursor != null) {  
                if (mCursor.moveToFirst()) {  
                    String proxyStr = mCursor.getString(mCursor  
                            .getColumnIndex("proxy"));  
                    if (proxyStr != null && proxyStr.trim().length() > 0) {  
                        HttpHost proxy = new HttpHost(proxyStr, 80);  
                        httpClient.getParams().setParameter(  
                                ConnRouteParams.DEFAULT_PROXY, proxy);  
                    }  
                }  
            }  
            StringEntity se = new StringEntity(holder.toString());  
            post.setEntity(se);  
            response = httpClient.execute(post);  
        } catch (Exception e) {  
            e.printStackTrace();  
            return null;  
        }  
        return response;  
    }  
 
    /**
     * GPS信息解析
     */
    public static LMLocation getGPSInfo(Context context) throws Exception {  
        HttpResponse response = connectionForGPS(context);  
        if (response == null) {  
            Log.d("GPSLocation", "response == null");  
            return null;  
        }  
        LMLocation location = null;  
        if (response.getStatusLine().getStatusCode() == 200) {  
            location = new LMLocation();  
            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.setAccess_token(json.getString("access_token"));  
                if (lca != null) {  
                    if (lca.has("accuracy"))  
                        location.setAccuracy(lca.getString("accuracy"));  
                    if (lca.has("longitude"))  
                        location.setLatitude(lca.getDouble("longitude"));  
                    if (lca.has("latitude"))  
                        location.setLongitude(lca.getDouble("latitude"));  
                    if (lca.has("address")) {  
                        JSONObject address = lca.getJSONObject("address");  
                        if (address != null) {  
                            if (address.has("region"))  
                                location.setRegion(address.getString("region"));  
                            if (address.has("street_number"))  
                                location.setStreet_number(address  
                                        .getString("street_number"));  
                            if (address.has("country_code"))  
                                location.setCountry_code(address  
                                        .getString("country_code"));  
                            if (address.has("street"))  
                                location.setStreet(address.getString("street"));  
                            if (address.has("city"))  
                                location.setCity(address.getString("city"));  
                            if (address.has("country"))  
                                location.setCountry(address  
                                        .getString("country"));  
                        }  
                    }  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
                location = null;  
            }  
        }  
        return location;  
    }  
 
}  
)







相关文章
|
8天前
|
IDE Android开发 iOS开发
探索Android与iOS开发的差异:平台选择对项目成功的影响
【9月更文挑战第27天】在移动应用开发的世界中,Android和iOS是两个主要的操作系统平台。每个系统都有其独特的开发环境、工具和用户群体。本文将深入探讨这两个平台的关键差异点,并分析这些差异如何影响应用的性能、用户体验和最终的市场表现。通过对比分析,我们将揭示选择正确的开发平台对于确保项目成功的重要作用。
|
5天前
|
开发框架 移动开发 Android开发
安卓与iOS开发中的跨平台解决方案:Flutter入门
【9月更文挑战第30天】在移动应用开发的广阔舞台上,安卓和iOS两大操作系统各自占据半壁江山。开发者们常常面临着选择:是专注于单一平台深耕细作,还是寻找一种能够横跨两大系统的开发方案?Flutter,作为一种新兴的跨平台UI工具包,正以其现代、响应式的特点赢得开发者的青睐。本文将带你一探究竟,从Flutter的基础概念到实战应用,深入浅出地介绍这一技术的魅力所在。
22 7
|
8天前
|
开发框架 前端开发 Android开发
安卓与iOS开发中的跨平台解决方案
【9月更文挑战第27天】在移动应用开发的广阔天地中,安卓和iOS两大操作系统如同双子星座般耀眼。开发者们在这两大平台上追逐着创新的梦想,却也面临着选择的难题。如何在保持高效的同时,实现跨平台的开发?本文将带你探索跨平台开发的魅力所在,揭示其背后的技术原理,并通过实际案例展示其应用场景。无论你是安卓的忠实拥趸,还是iOS的狂热粉丝,这篇文章都将为你打开一扇通往跨平台开发新世界的大门。
|
5天前
|
缓存 Java Linux
探索安卓开发:从新手到专家的旅程
【9月更文挑战第30天】在这篇文章中,我们将一起踏上一段激动人心的旅程,探索安卓开发的广阔世界。无论你是刚入门的新手,还是希望提升技能的开发者,本文都将为你提供宝贵的知识和指导。我们将深入探讨安卓开发的基础知识、关键概念、实用工具和最佳实践,帮助你在安卓开发领域取得更大的成功。让我们一起开启这段精彩的旅程吧!
|
6天前
|
监控 安全 Java
Kotlin 在公司上网监控中的安卓开发应用
在数字化办公环境中,公司对员工上网行为的监控日益重要。Kotlin 作为一种基于 JVM 的编程语言,具备简洁、安全、高效的特性,已成为安卓开发的首选语言之一。通过网络请求拦截,Kotlin 可实现网址监控、访问时间记录等功能,满足公司上网监控需求。其简洁性有助于快速构建强大的监控应用,并便于后续维护与扩展。因此,Kotlin 在安卓上网监控应用开发中展现出广阔前景。
9 1
|
9天前
|
存储 开发工具 Android开发
使用.NET MAUI开发第一个安卓APP
【9月更文挑战第24天】使用.NET MAUI开发首个安卓APP需完成以下步骤:首先,安装Visual Studio 2022并勾选“.NET Multi-platform App UI development”工作负载;接着,安装Android SDK。然后,创建新项目时选择“.NET Multi-platform App (MAUI)”模板,并仅针对Android平台进行配置。了解项目结构,包括`.csproj`配置文件、`Properties`配置文件夹、平台特定代码及共享代码等。
|
13天前
|
ARouter 测试技术 API
Android经典面试题之组件化原理、优缺点、实现方法?
本文介绍了组件化在Android开发中的应用,详细阐述了其原理、优缺点及实现方式,包括模块化、接口编程、依赖注入、路由机制等内容,并提供了具体代码示例。
30 2
|
15天前
|
存储 Java Android开发
🔥Android开发大神揭秘:从菜鸟到高手,你的代码为何总是慢人一步?💻
在Android开发中,每位开发者都渴望应用响应迅速、体验流畅。然而,代码执行缓慢却是常见问题。本文将跟随一位大神的脚步,剖析三大典型案例:主线程阻塞导致卡顿、内存泄漏引发性能下降及不合理布局引起的渲染问题,并提供优化方案。通过学习这些技巧,你将能够显著提升应用性能,从新手蜕变为高手。
16 2
|
16天前
|
Java Android开发 C++
🚀Android NDK开发实战!Java与C++混合编程,打造极致性能体验!📊
在Android应用开发中,追求卓越性能是不变的主题。本文介绍如何利用Android NDK(Native Development Kit)结合Java与C++进行混合编程,提升应用性能。从环境搭建到JNI接口设计,再到实战示例,全面展示NDK的优势与应用技巧,助你打造高性能应用。通过具体案例,如计算斐波那契数列,详细讲解Java与C++的协作流程,帮助开发者掌握NDK开发精髓,实现高效计算与硬件交互。
58 1
|
9天前
|
搜索推荐 前端开发 Android开发
安卓开发中的自定义视图:打造个性化用户界面
【9月更文挑战第26天】在移动应用开发的广阔天地中,定制性是提升用户体验的不二法宝。本文将带你深入了解安卓开发中自定义视图的魅力所在,通过简洁明了的语言和直观的代码示例,展示如何从零开始创建属于自己的控件,让你的应用界面与众不同。
下一篇
无影云桌面