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







相关文章
|
3天前
|
Linux 编译器 Android开发
FFmpeg开发笔记(九)Linux交叉编译Android的x265库
在Linux环境下,本文指导如何交叉编译x265的so库以适应Android。首先,需安装cmake和下载android-ndk-r21e。接着,下载x265源码,修改crosscompile.cmake的编译器设置。配置x265源码,使用指定的NDK路径,并在配置界面修改相关选项。随后,修改编译规则,编译并安装x265,调整pc描述文件并更新PKG_CONFIG_PATH。最后,修改FFmpeg配置脚本启用x265支持,编译安装FFmpeg,将生成的so文件导入Android工程,调整gradle配置以确保顺利运行。
24 1
FFmpeg开发笔记(九)Linux交叉编译Android的x265库
|
26天前
|
Java Android开发
Android 开发获取通知栏权限时会出现两个应用图标
Android 开发获取通知栏权限时会出现两个应用图标
12 0
|
1月前
|
XML 缓存 Android开发
Android开发,使用kotlin学习多媒体功能(详细)
Android开发,使用kotlin学习多媒体功能(详细)
102 0
|
1月前
|
设计模式 人工智能 开发工具
安卓应用开发:构建未来移动体验
【2月更文挑战第17天】 随着智能手机的普及和移动互联网技术的不断进步,安卓应用开发已成为一个热门领域。本文将深入探讨安卓平台的应用开发流程、关键技术以及未来发展趋势。通过分析安卓系统的架构、开发工具和框架,本文旨在为开发者提供全面的技术指导,帮助他们构建高效、创新的移动应用,以满足不断变化的市场需求。
18 1
|
1月前
|
机器学习/深度学习 调度 Android开发
安卓应用开发:打造高效通知管理系统
【2月更文挑战第14天】 在移动操作系统中,通知管理是影响用户体验的关键因素之一。本文将探讨如何在安卓平台上构建一个高效的通知管理系统,包括服务、频道和通知的优化策略。我们将讨论最新的安卓开发工具和技术,以及如何通过这些工具提高通知的可见性和用户互动性,同时确保不会对用户造成干扰。
33 1
|
17天前
|
XML 开发工具 Android开发
构建高效的安卓应用:使用Jetpack Compose优化UI开发
【4月更文挑战第7天】 随着Android开发不断进化,开发者面临着提高应用性能与简化UI构建流程的双重挑战。本文将探讨如何使用Jetpack Compose这一现代UI工具包来优化安卓应用的开发流程,并提升用户界面的流畅性与一致性。通过介绍Jetpack Compose的核心概念、与传统方法的区别以及实际集成步骤,我们旨在提供一种高效且可靠的解决方案,以帮助开发者构建响应迅速且用户体验优良的安卓应用。
|
19天前
|
监控 算法 Android开发
安卓应用开发:打造高效启动流程
【4月更文挑战第5天】 在移动应用的世界中,用户的第一印象至关重要。特别是对于安卓应用而言,启动时间是用户体验的关键指标之一。本文将深入探讨如何优化安卓应用的启动流程,从而减少启动时间,提升用户满意度。我们将从分析应用启动流程的各个阶段入手,提出一系列实用的技术策略,包括代码层面的优化、资源加载的管理以及异步初始化等,帮助开发者构建快速响应的安卓应用。
|
19天前
|
Java Android开发
Android开发之使用OpenGL实现翻书动画
本文讲述了如何使用OpenGL实现更平滑、逼真的电子书翻页动画,以解决传统贝塞尔曲线方法存在的卡顿和阴影问题。作者分享了一个改造后的外国代码示例,提供了从前往后和从后往前的翻页效果动图。文章附带了`GlTurnActivity`的Java代码片段,展示如何加载和显示书籍图片。完整工程代码可在作者的GitHub找到:https://github.com/aqi00/note/tree/master/ExmOpenGL。
21 1
Android开发之使用OpenGL实现翻书动画
|
19天前
|
Android开发 开发者
Android开发之OpenGL的画笔工具GL10
这篇文章简述了OpenGL通过GL10进行三维图形绘制,强调颜色取值范围为0.0到1.0,背景和画笔颜色设置方法;介绍了三维坐标系及与之相关的旋转、平移和缩放操作;最后探讨了坐标矩阵变换,包括设置绘图区域、调整镜头参数和改变观测方位。示例代码展示了如何使用这些方法创建简单的三维立方体。
15 1
Android开发之OpenGL的画笔工具GL10
|
22天前
|
Android开发
Android调用相机与相册的方法2
Android调用相机与相册的方法
17 0