https://blog.csdn.net/unity_http/article/details/79929454
https://blog.csdn.net/why1happy/article/details/105765140
https://www.jianshu.com/p/1adbf9091575
https://blog.csdn.net/m0_37583098/article/details/78604329 接入ios可以参考
https://blog.csdn.net/qq_37310110/article/details/83145193 无需jar包
https://blog.csdn.net/qq_35080168/article/details/103425746
https://www.cnblogs.com/herenzhiming/articles/8334117.html android 调用unity的方法
https://lbs.amap.com/api/android-location-sdk/guide/utilities/errorcode/ 高德错误码返回参考

本篇主要介绍在unity中接入高德定位sdk。

方法1、不用接入sdk,直接使用unity原生的方法,获得经纬度之后,以get请求得到城市相关信息。
代码如下:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using UnityEngine;public class GPSDemo : MonoBehaviour
{private AndroidJavaClass unity;IEnumerator Start(){if (unity == null){unity = new AndroidJavaClass("com.unity3d.player.UnityPlayer");}if (!Input.location.isEnabledByUser){Input.location.Start();yield break;}// Start service before querying locationInput.location.Start();// Wait until service initializesint maxWait = 20;while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0){yield return new WaitForSeconds(1);maxWait--;}// Service didn't initialize in 20 secondsif (maxWait < 1){print("Timed out");yield break;}// Connection has failedif (Input.location.status == LocationServiceStatus.Failed){print("Unable to determine device location");yield break;}else{// Access granted and location value could be retrievedDebug.LogError("Location: " + Input.location.lastData.latitude + " " + Input.location.lastData.longitude + " " + Input.location.lastData.altitude + " " + Input.location.lastData.horizontalAccuracy + " " + Input.location.lastData.timestamp);//取出位置的经纬度string str = Input.location.lastData.longitude + "," + Input.location.lastData.latitude;Debug.Log("定位信息" + GetLocationByLngLat(str));}// Stop service if there is no need to query location updates continuouslyInput.location.Stop();}const string key = "6bda73179a87a92394489045b32a0f46";       //去高德地图开发者申请 这个key的流量不知道被哪位同学用完了,/// <summary>/// 根据经纬度获取地址/// </summary>/// <param name="LngLatStr">经度纬度组成的字符串 例如:"113.692100,34.752853"</param>/// <param name="timeout">超时时间默认10秒</param>/// <returns>失败返回"" </returns>public string GetLocationByLngLat(string LngLatStr, int timeout = 10000){string url = $"http://restapi.amap.com/v3/geocode/regeo?key={key}&location={LngLatStr}";return GetLocationByURL(url, timeout);}public string GetLocationByLngLat(double lng, double lat, int timeout = 10000){string url = $"http://restapi.amap.com/v3/geocode/regeo?key={key}&location={lng},{lat}";Debug.LogError("url = " + url);return GetLocationByURL(url, timeout);}private string GetLocationByURL(string url, int timeout = 10000){string strResult = "";try{HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;req.ContentType = "multipart/form-data";req.Accept = "*/*";//req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)";req.UserAgent = "";req.Timeout = timeout;req.Method = "GET";req.KeepAlive = true;HttpWebResponse response = req.GetResponse() as HttpWebResponse;using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8)){strResult = sr.ReadToEnd();}Debug.LogError("xxx123" + strResult);}catch (Exception ex){Debug.LogError("ex = " + ex.ToString());strResult = "";}return strResult;}

这个就可以了。
你可以在web浏览器直接如下格式的请求:
http://restapi.amap.com/v3/geocode/regeo?key=6bda73179a87a92394489045b32a0f46&location=74,40
74,40是经纬度,逗号隔开。
key=6bda73179a87a92394489045b32a0f46 是人家的web开发的key。自己可以自己申请,申请的过程后文会介绍。这里先暂时用别人的。

2、使用sdk的接入
这里介绍的是android平台下接入高德sdk。
下载sdk:
https://lbs.amap.com/api/android-navi-sdk/download/


key的获取。
首先德注册高德开发账号,网址:https://lbs.amap.com/
注册之后,到达控制台:https://console.amap.com/dev/key/app

点击管理Key


创建新应用,随便起个名字。

1:起个刚才创建新应用的名字
2:服务平台选择android
3、发布版安全码SHA1获取方式:
3.1到达unity的项目:

选择keystore存放的路径,我这里选择在D盘了。

记住你的密码,这个在打包的时候会用到。
3.2到android studio中敲入如下命令:keytool -list -v -keystore D:\user.keystore
D:\user.keystore就是我们刚才的那个keystore文件。

得到:

ok,把这个SHA1,复制给上面的那个4开发SHA1中即可。

调试版的也用此命令:keytool -list -v -keystore debug.keystore
debug.keystore是android studio自带的:
在下:这个在安装了android studio之后就有了。


ok,同样也会得到:

将其复制到5:

4、最后一步是packageName:这个名字是你的android的应用包名:

ok,有了这个key之后,就可以了。

下面是代码部分:
android部分:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="demo.xiaoming.com.xiaominglib"><applicationandroid:allowBackup="true"android:label="@string/app_name"android:supportsRtl="true"><activity android:name=".MainActivity2" android:label="@string/app_name"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><meta-data android:name="com.amap.api.v2.apikey" android:value="你的那个key"></meta-data>
<service android:name="com.amap.api.location.APSService"></service></application><!--用于进行网络定位--><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission><!--用于访问GPS定位--><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission><!--获取运营商信息,用于支持提供运营商信息相关的接口--><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission><!--用于访问wifi网络信息,wifi信息会用于进行网络定位--><uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission><!--这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位--><uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission><!--用于访问网络,网络定位需要上网--><uses-permission android:name="android.permission.INTERNET"></uses-permission><!--用于读取手机当前的状态--><uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission><!--写入扩展存储,向扩展卡写入数据,用于写入缓存定位数据--><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission><!--用于申请调用A-GPS模块--><uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"></uses-permission><!--用于申请获取蓝牙信息进行室内定位--><uses-permission android:name="android.permission.BLUETOOTH"></uses-permission><uses-permission android:name="android.permission.BLUETOOTH_ADMIN"></uses-permission>
</manifest>

Activity类:

package demo.xiaoming.com.xiaominglib;import android.os.Debug;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.unity3d.player.UnityPlayerActivity;import java.text.SimpleDateFormat;
import java.util.Date;public class MainActivity2 extends UnityPlayerActivity
{public  XiaomingInterface xiaomingInterface;public  int Add(int a, int b){return  a+b;}//声明mLocationClient对象public AMapLocationClient mLocationClient = null;public AMapLocationClientOption mLocationOption = null;private String LocationInfo;private String ErrorInfo="";//获取定位信息public String[] GetInfo(){String[] a=new String[2];a[0]=this.LocationInfo;a[1]=this.ErrorInfo;Log.i("startget", "star get");startLocation();Log.i("endget", "endget");return a;}private void startLocation(){this.mLocationClient = new AMapLocationClient(getApplicationContext());//回调监听this.mLocationClient.setLocationListener(this.mLocationListener);//初始化定位参数this.mLocationOption = new AMapLocationClientOption();this.mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);this.mLocationOption.setInterval(1000L);this.mLocationOption.setHttpTimeOut(10000l);this.mLocationOption.setNeedAddress(true);this.mLocationClient.setLocationOption(this.mLocationOption);this.mLocationClient.startLocation();}public AMapLocationListener mLocationListener = new AMapLocationListener(){@Overridepublic void onLocationChanged(AMapLocation location){Log.d("location xxxx = ", location.getAddress());if (location != null){if (location.getErrorCode() == 0){StringBuffer sb = new StringBuffer(256);SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date date = new Date(location.getTime());String time=df.format(date);sb.append("时间: " + time);sb.append("\n纬度:" + location.getLatitude());sb.append("\n经度:" + location.getLongitude());sb.append("\n精度:" + location.getAccuracy());sb.append("\n地址:" + location.getAddress());sb.append("\n国家信息:" + location.getCountry());sb.append("\n省信息:" + location.getProvince());sb.append("\n城市信息:" + location.getCity());sb.append("\n城区信息:" + location.getDistrict());sb.append("\n街道信息:" + location.getStreet());sb.append("\n街道门牌号信息:" + location.getStreetNum());sb.append("\n城市编码:" + location.getCityCode());sb.append("\n地区编码:" + location.getAdCode());LocationInfo = sb.toString();Log.d("LocationInfo = ", LocationInfo);}else{StringBuffer errorinfo = new StringBuffer(256);errorinfo.append("错误代码:"+location.getErrorCode());errorinfo.append("\n"+location.getErrorInfo());ErrorInfo=errorinfo.toString();Log.d("ErrorInfo = ", ErrorInfo);}mLocationClient.stopLocation();mLocationClient.unRegisterLocationListener(mLocationListener);Log.d("ErrorInfo = ", "stopLocation");if(xiaomingInterface != null){String[] res=new String[2];res[0]=LocationInfo;res[1]=ErrorInfo;Log.d("ErrorInfoxxxx1", res[0]);Log.d("ErrorInfoxxxx1", res[1]);xiaomingInterface.FinishLocation(res);Log.d("ErrorInfoxxxx2", ErrorInfo);}}}};public  void SetInterface(XiaomingInterface xx){this.xiaomingInterface = xx;if(this.xiaomingInterface != null){Log.d("setinterface", "xiaomingInterface");}}
}

buildgradle:

apply plugin: 'com.android.library'android {compileSdkVersion 28defaultConfig {minSdkVersion 23targetSdkVersion 28versionCode 1versionName "1.0"testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"}buildTypes {release {minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'}}}dependencies {implementation fileTree(include: ['*.jar'], dir: 'libs')implementation 'com.android.support:appcompat-v7:28.0.0'implementation 'com.android.support.constraint:constraint-layout:1.1.3'testImplementation 'junit:junit:4.12'androidTestImplementation 'com.android.support.test:runner:1.0.2'androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'implementation files('libs/AMap_Location_V5.0.0_20200609.jar')
}afterEvaluate { //这个加入之后不会产生多个BuildConfiggenerateReleaseBuildConfig.enabled = falsegenerateDebugBuildConfig.enabled = false
}//task to delete the old jar(删除之前的.jar)
task deleteOldJar(type: Delete) {delete 'release/AndroidPlugin.jar'
}//task to export contents as jar(拷贝到指定目录 并修改名)
task exportJar(type: Copy) {from('build/intermediates/bundles/release/')into('release/')include('classes.jar')///Rename the jarrename('classes.jar', 'AndroidPlugin.jar')
}
exportJar.dependsOn(deleteOldJar, build)

再次之前,还要导入jar包:

一个untiy的,一个是高度sdk的jar包。

rebuild失败,可以换代理:这是整个工程的build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript {repositories {maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }maven { url 'http://maven.aliyun.com/nexus/content/repositories/jcenter' }maven { url 'http://maven.aliyun.com/nexus/content/repositories/google' }maven { url 'http://maven.aliyun.com/nexus/content/repositories/gradle-plugin' }maven { url "https://jitpack.io" }google()jcenter()}dependencies {classpath 'com.android.tools.build:gradle:3.2.1'// NOTE: Do not place your application dependencies here; they belong// in the individual module build.gradle files}
}allprojects {repositories {maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }maven { url 'http://maven.aliyun.com/nexus/content/repositories/jcenter' }maven { url 'http://maven.aliyun.com/nexus/content/repositories/google' }maven { url 'http://maven.aliyun.com/nexus/content/repositories/gradle-plugin' }maven { url "https://jitpack.io" }google()jcenter()}
}task clean(type: Delete) {delete rootProject.buildDir
}

ok,这个之后:

就得到jar包了:

下面是在unity中使用:

测试代码:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using UnityEngine;public class UnityCallback : AndroidJavaProxy
{public UnityCallback() : base("demo.xiaoming.com.xiaominglib.XiaomingInterface"){}void FinishLocation(string[] strs){Debug.LogError("xxxxx============");for(int i=0;i<strs.Length;++i){Debug.LogError("info=" + strs[i]);}}
}public class GPSDemo : MonoBehaviour
{private AndroidJavaClass unity;IEnumerator Start(){if (unity == null){unity = new AndroidJavaClass("com.unity3d.player.UnityPlayer");}for (int i = 0; i < 5; ++i){Debug.LogError("startxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx " + i);}Debug.LogError("start isEnabledByUser" + Input.location.isEnabledByUser);if (!Input.location.isEnabledByUser){Debug.LogError("start isEnabledByUser");Input.location.Start();yield break;}// Start service before querying locationInput.location.Start();// Wait until service initializesint maxWait = 20;while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0){yield return new WaitForSeconds(1);maxWait--;}// Service didn't initialize in 20 secondsif (maxWait < 1){print("Timed out");yield break;}// Connection has failedif (Input.location.status == LocationServiceStatus.Failed){print("Unable to determine device location");yield break;}else{// Access granted and location value could be retrievedDebug.LogError("Location: " + Input.location.lastData.latitude + " " + Input.location.lastData.longitude + " " + Input.location.lastData.altitude + " " + Input.location.lastData.horizontalAccuracy + " " + Input.location.lastData.timestamp);//取出位置的经纬度string str = Input.location.lastData.longitude + "," + Input.location.lastData.latitude;Debug.Log("定位信息" + GetLocationByLngLat(str));}// Stop service if there is no need to query location updates continuouslyInput.location.Stop();}const string key = "6bda73179a87a92394489045b32a0f46";       //去高德地图开发者申请 这个key的流量不知道被哪位同学用完了,/// <summary>/// 根据经纬度获取地址/// </summary>/// <param name="LngLatStr">经度纬度组成的字符串 例如:"113.692100,34.752853"</param>/// <param name="timeout">超时时间默认10秒</param>/// <returns>失败返回"" </returns>public string GetLocationByLngLat(string LngLatStr, int timeout = 10000){string url = $"http://restapi.amap.com/v3/geocode/regeo?key={key}&location={LngLatStr}";return GetLocationByURL(url, timeout);}/// <summary>/// 根据经纬度获取地址/// </summary>/// <param name="lng">经度 例如:113.692100</param>/// <param name="lat">维度 例如:34.752853</param>/// <param name="timeout">超时时间默认10秒</param>/// <returns>失败返回"" </returns>public string GetLocationByLngLat(double lng, double lat, int timeout = 10000){string url = $"http://restapi.amap.com/v3/geocode/regeo?key={key}&location={lng},{lat}";Debug.LogError("url = " + url);return GetLocationByURL(url, timeout);}/// <summary>/// 根据URL获取地址/// </summary>/// <param name="url">Get方法的URL</param>/// <param name="timeout">超时时间默认10秒</param>/// <returns></returns>private string GetLocationByURL(string url, int timeout = 10000){string strResult = "";try{HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;req.ContentType = "multipart/form-data";req.Accept = "*/*";//req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)";req.UserAgent = "";req.Timeout = timeout;req.Method = "GET";req.KeepAlive = true;HttpWebResponse response = req.GetResponse() as HttpWebResponse;using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8)){strResult = sr.ReadToEnd();}Debug.LogError("xxx123" + strResult);}catch (Exception ex){Debug.LogError("ex = " + ex.ToString());strResult = "";}return strResult;}public void OnClickButton(){UseSDK();}private void UseSDK(){AndroidJavaObject currentActivity = unity.GetStatic<AndroidJavaObject>("currentActivity");int a = currentActivity.Call<int>("Add", 2, 5);Debug.LogError("add = " + a);//注册回调接口UnityCallback callback = new UnityCallback();currentActivity.Call("SetInterface", callback);string[] strs = currentActivity.Call<string[]>("GetInfo");//Debug.LogError("map = ");//for (int i = 0; i < strs.Length; ++i)//{//    Debug.LogError("i = " + i + "  " + strs[i]);//}//Debug.LogError("3333333333333333333333333333333");//StartCoroutine(Sxxx());}private IEnumerator Sxxx(){if (!Input.location.isEnabledByUser){Debug.LogError("start isEnabledByUser " + Input.location.isEnabledByUser);Input.location.Start();yield break;}}
}

ok,结束。

android打包jar包给unity使用接入高德sdk,实现定位。相关推荐

  1. android 打包jar包

    昨天,自己用到别人的jar包的内容,后来,公司要求在之前的基础上增加几个功能,所以需要修改jar包的内容.别人的源代码给了我,我修改后进行打包成jar包.不过自己却不会用android studio ...

  2. Unity接入高德SDK实现定位

    一.在高德官网下载需要对应的SDK  http://lbs.amap.com/api/android-location-sdk 通过SHA1值获取对应的key值 a.SHA1值得获取:  1.在cmd ...

  3. AndroidStudio3.4+Unity2018.3,导出JAR包给UNITY使用

    AndroidStudio3.4+Unity2018.3,导出JAR包给UNITY使用 环境 Android studio 3.4 + unity2018.3 1,android studio 新建空 ...

  4. 教你快速高效接入SDK——Unity统一接入渠道SDK(Android篇)

    U8SDK技术博客:http://www.uustory.com/,欢迎来坐坐. 百度传课已经停运,最新U8SDK视频教程已经转移至B站:U8SDK最新视频教程 U8SDK的设计之初,就是为了能够支持 ...

  5. Android 系统(137)---android打包解包boot.img,system.img

    android打包解包boot.img,system.img 2017年04月28日 15:00:36 阅读数:1822 原帖地址:http://www.52pojie.cn/thread-48802 ...

  6. android jar 包 意见反馈功能,android重点jar包详解.docx

    android重点jar包详解 深入理解View(一):从setContentView谈起 我们都知道?MVC,在Android中,这个?V?即指View,那我们今天就来探探View的究竟.在onCr ...

  7. Android 系统(138 )---Mtk平台 Android 打包解包*.img ,修改system.img 参数

    Mtk平台 Android 打包解包*.img ,修改system.img 参数 MTK 升级包文件如下: 若存在软件版本号存在错误或需要修改,重新编译则需要几个小时,或者要几天的测试 若可以直接修改 ...

  8. 打包jar包时文件读取和第三方jar包的问题

    本人自己遇到的问题.自己写的一个项目,想要打包成jar包放在定时器里去调用,遇到了如下问题 1.xml文件和properties文件读取问题 2.第三方jar包读取不到 解决方案: 1 我是在读取xm ...

  9. MapReduce打包jar包并运行的步骤操作以及重要的注意事项

    目录 一.打包jar包以及上传的步骤 在eclipse把mapreduce程序进行打包 通过Xshell把JAR包上传到linux 二.执行jar包的注意事项 出现jdk版本异常的问题 情况描述 原因 ...

最新文章

  1. mybatis 报错最终解决 :argument type mismatch
  2. E. Turn Off The TV Educational Codeforces Round 29
  3. 后端学习 - 计算机网络
  4. Python项目实践:国家财政数据趋势演算
  5. html5 websocket 手机,HTML5 WebSocket 示范
  6. python点击按钮弹出新窗口_PyQt5点击button如何弹出新窗口?
  7. TypeError: Layout of the output array image is incompatible with cv::Mat
  8. (6)数据结构-共享栈
  9. java 读文件 解析
  10. MATLAB卷积conv、conv2、convn详解
  11. python数据挖掘学习路线
  12. 电容触摸屏测试软件,大规模生产中如何测量触摸屏电容值
  13. FreeRADIUS介绍
  14. Android实现多国语言适配:app名称随系统的语言而更换
  15. Mac CAD 安装完成后,打开注册机时出现 应用程序“02_注册机”不能打开。
  16. 005 偶数分频,奇数分频,倍频
  17. 文本长度过长时隐藏并显示省略号“...”,以及鼠标停留时悬浮显示全部文本(兼容IE)
  18. Johnson-Trotter算法求全排列
  19. 计算机的网络设置在哪里,笔记本无线设置在哪里_笔记本电脑设置无线网络的步骤-win7之家...
  20. 有序Map集合:LinkedHashMap和TreeMap该如何选用

热门文章

  1. 1040 Longest Symmetric String
  2. 在KVM中部署嵌套版本的VMware ESXi 6.7
  3. 目标检测:1. R-CNN
  4. Android逆向工程:大显神通的Xposed,利用报错机制快速获取程序运行过程
  5. 华胜天成与IBM将展开深度合作
  6. 求助Latex标题如何加粗?
  7. 5方面认识LED透明屏显示屏 生产|原理|技术|应用
  8. 六级Translation
  9. JustAuth于2019年7月21日正式喜提码云【GVP 】称号!
  10. 【电源设计】02Buck开关电源