• Unity与Android交互-Unity接入高德地图实现定位以及搜索周边的功能(使用Android Studio)详细操作


    刚进公司给安排的任务就是Unity接入高德地图,算是踩了不少坑总算做出来了,抽点时间写个博客记录一下

    废话不多说

    先上效果图

    获取定位并根据手机朝向显示周边信息

              

    使用的Unity版本为5.5,Androad Studio 2.3.1

    接下来开始讲具体操作

    首先是Androad Studio的基本配置


    1.创建工程,空白的就行,反正也用不到界面布局

    等待创建完成

    2.新建库模块:

    切换到Project视图

    右击你的项目 新建一个库模块-用来负责与Unity交互

    当然你也可以不选择新建库模块 直接在原生app模块进行操作

    选择Android Library

     

    等待生成完成

    你会看到多出来的

    3.创建MainActivity:我们新建的library中没有启动这个模块的Java类 所以需要手动创建一个

    切换到Android视窗下 选中此文件右键创建

    4.删除布局文件activity_main

    布局文件是用来管理Android界面布局的,我们并不需要,所以将它删除,防止发生一些没必要的错误

    5.修改配置文件:AndroidManifest

    为了能够正常发布 需要将AndroidManifest进行一些修改

    在这中间插入启动Activity的配置

            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>

     到这里基本配置就完了

    然后进行测试点击这个

    或许你会发现报错了 原因是我们在创建MainActivity的时候他自动引用了布局文件 所以这里应该将这一行删除

    然后再次更新 成功

    到这里基本配置以及完成

    引入Unity与高德地图的包

    下载高德地图包 这里有个定制选你要用的功能下载就好 这里我用到的是定位和搜索

     将下载好的包拖入libs中

    接下来是Unity的包

    新建Unity工程

    发布平台改Android 

    设置package name与你新建的library库一致

    然后发布系统ADT 导出

     在libs中找到

    复制进Android Sturio中的libs

    选中两个包Add As Library

    选library工程 OK

    等待加载完成

    到这里引入包的操作已经完成

    更改MainActivity并发布

    主要内容为

    获取当前定位信息

    获取查询指定字符串周边信息

      1 package com.example.autlibrary;
      2 
      3 import android.os.Bundle;
      4 import android.util.Log;
      5 import android.widget.Toast;
      6 import com.amap.api.location.AMapLocation;
      7 import com.amap.api.location.AMapLocationClient;
      8 import com.amap.api.location.AMapLocationClientOption;
      9 import com.amap.api.location.AMapLocationListener;
     10 import com.amap.api.services.core.LatLonPoint;
     11 import com.amap.api.services.core.PoiItem;
     12 import com.amap.api.services.poisearch.PoiResult;
     13 import com.amap.api.services.poisearch.PoiSearch;
     14 import com.unity3d.player.UnityPlayerActivity;
     15 
     16 public class MainActivity
     17         extends UnityPlayerActivity
     18         implements PoiSearch.OnPoiSearchListener
     19 {
     20     public AMapLocationClient mLocationClient = null;
     21     public AMapLocationClientOption mLocationOption = null;
     22     private String LocationInfo;
     23     private String strRerurnInfo;
     24     private PoiSearch.Query query;
     25     private PoiResult poir;
     26     private double Latitude;
     27     private double Longitude;
     28     private boolean bolIsPoi = false;
     29 
     30     protected void onCreate(Bundle savedInstanceState)
     31     {
     32         super.onCreate(savedInstanceState);
     33     }
     34     //获取定位信息
     35     public String GetInfo()
     36     {
     37         startLocation();
     38         this.bolIsPoi = true;
     39         return this.LocationInfo;
     40     }
     41     //获取周边POI信息
     42     public String GetPoi(String content, String val, int index)
     43     {
     44         startLocation();
     45         search(content, val, index);
     46         return this.strRerurnInfo;
     47     }
     48 
     49     protected void onStart()
     50     {
     51         super.onStart();
     52     }
     53 
     54     private void startLocation()
     55     {
     56         this.mLocationClient = new AMapLocationClient(getApplicationContext());
     57         this.mLocationClient.setLocationListener(this.mLocationListener);
     58         this.mLocationOption = new AMapLocationClientOption();
     59         this.mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
     60         this.mLocationOption.setInterval(2000L);
     61         this.mLocationClient.setLocationOption(this.mLocationOption);
     62         this.mLocationClient.startLocation();
     63     }
     64 
     65     //三个参数分别为搜索字符串、搜索类型、查询第几页
     66     //前两个参数选其一
     67     //如:酒店、""、1
     68     //第二个参数为poi搜索类型:
     69     //汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|
     70     // 医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|
     71     // 交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施
     72     public void search(String content, String val, int index)
     73     {
     74         if (this.bolIsPoi) {
     75             if (content == null)
     76             {
     77                 Toast.makeText(this, "输入为空", Toast.LENGTH_SHORT).show();
     78             }
     79             else
     80             {
     81                 this.query = new PoiSearch.Query(content, val, "");
     82                 this.query.setPageSize(30);
     83                 this.query.setPageNum(index);
     84                 PoiSearch poiSearch = new PoiSearch(this, this.query);
     85                 if ((this.Latitude != 0.0D) && (this.Longitude != 0.0D))
     86                 {
     87                     poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(this.Latitude, this.Longitude), 6000));
     88 
     89                     poiSearch.setOnPoiSearchListener(this);
     90                     poiSearch.searchPOIAsyn();
     91                 }
     92                 else
     93                 {
     94                     Toast.makeText(this, "定位失败", Toast.LENGTH_SHORT).show();
     95                 }
     96             }
     97         }
     98     }
     99 
    100     public void onPoiSearched(PoiResult result, int code)
    101     {
    102         this.bolIsPoi = false;
    103         System.out.println("Result" + (result.getPois().get(0)).getLatLonPoint());
    104         System.out.println("Code" + code);
    105         this.poir = result;
    106         StringBuffer sb = new StringBuffer(256);
    107         for (int j = 0; j < this.poir.getPois().size(); j++)
    108         {
    109             sb.append("
    名字:");
    110             sb.append((this.poir.getPois().get(j)).getTitle());
    111             sb.append("
    >地址:");
    112             sb.append((this.poir.getPois().get(j)).getSnippet());
    113             sb.append("
    >距离:");
    114             sb.append((this.poir.getPois().get(j)).getDistance());
    115         }
    116         this.strRerurnInfo = sb.toString();
    117     }
    118 
    119     @Override
    120     public void onPoiItemSearched(PoiItem poiItem, int i) {
    121 
    122     }
    123 
    124     public AMapLocationListener mLocationListener = new AMapLocationListener() {
    125         @Override
    126         public void onLocationChanged(AMapLocation location) {
    127             if (location != null) {
    128                 if (location.getErrorCode() == 0) {
    129                     //获取坐标信息
    130                     Latitude = location.getLatitude();
    131                     Longitude = location.getLongitude();
    132 
    133                     StringBuffer sb = new StringBuffer(256);
    134                     sb.append("时间: " + location.getTime());
    135                     sb.append("
    纬度:" + location.getLatitude());
    136                     sb.append("
    经度:" + location.getLongitude());
    137                     sb.append("
    精度:" + location.getAccuracy());
    138                     sb.append("
    地址:" + location.getAddress());
    139                     sb.append("
    国家信息:" + location.getCountry());
    140                     sb.append("
    省信息:" + location.getProvince());
    141                     sb.append("
    城市信息:" + location.getCity());
    142                     sb.append("
    城区信息:" + location.getDistrict());
    143                     sb.append("
    街道信息:" + location.getStreet());
    144                     sb.append("
    街道门牌号信息:" + location.getStreetNum());
    145                     sb.append("
    城市编码:" + location.getCityCode());
    146                     sb.append("
    地区编码:" + location.getAdCode());
    147                     sb.append("
    定位点AOI信息:" + location.getAoiName());
    148                     LocationInfo = sb.toString();
    149                 }else {
    150                     Log.e("AmapError","location Error, ErrCode:"
    151                             + location.getErrorCode() + ", errInfo:"
    152                             + location.getErrorInfo());
    153                 }
    154             }
    155         }
    156     };
    157 }
    MainActivity

    修改完MainActivity 无错误的话 就可以发布了

    发布到library库中

    然后你在

    “你的工程目录”autlibraryuildintermediatesundlesdebug中会有这些

    右键Show in Exploer   并在文件夹中找到他们

    这样就发布成功了

    与Unity间的交互

    上一步我们导出了工程包

    我们需要将它修改为Unity可用的工程

    复制classes.jar

    粘贴到libs 

    删除libs中的unity-classes.jar

    -

    -

     

    这样的话就修改成功了  然后我们将它导入Unity

    复制libs和res文件夹到Unity

    需要创建Plugins和Android文件夹 复制过后是这样的关系

    这样就成功导入进了Unity

    配置AndroidManifest.Xml文件,并创建C#脚本

    不知道你还记不记得我们在Unity中导出的包 找到它!我们需要里面的Xml文件

    将它复制到AssetsPluginsAndroid下

    接着就要对它进行修改了

     1 <?xml version="1.0" encoding="utf-8"?>
     2 <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.autlibrary" xmlns:tools="http://schemas.android.com/tools" android:versionName="1.0" android:versionCode="1" android:installLocation="preferExternal">
     3   <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />
     4   <application android:theme="@style/UnityThemeSelector" android:icon="@drawable/app_icon" android:label="@string/app_name" android:debuggable="false" android:isGame="true" android:banner="@drawable/app_banner">
     5       <meta-data
     6         android:name="com.amap.api.v2.apikey"
     7         android:value="64c821ae174ab7429fa45535d01f20ae"/>
     8       <activity 
     9         android:label="@string/app_name" android:screenOrientation="fullSensor" 
    10         android:launchMode="singleTask" 
    11         android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale" 
    12         android:name="com.example.autlibrary.MainActivity">
    13       <service android:name="com.amap.api.location.APSService" ></service>
    14       <intent-filter>
    15         <action android:name="android.intent.action.MAIN" />
    16         <category android:name="android.intent.category.LAUNCHER" />
    17         <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
    18       </intent-filter>
    19       <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
    20     </activity>
    21   </application>
    22   <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="25" />
    23   <uses-feature android:glEsVersion="0x00020000" />
    24   <uses-feature android:name="android.hardware.touchscreen" android:required="false" />
    25   <uses-feature android:name="android.hardware.touchscreen.multitouch" android:required="false" />
    26   <uses-feature android:name="android.hardware.touchscreen.multitouch.distinct" android:required="false" />
    27   <uses-permission android:name="android.permission.INTERNET" />
    28   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    29   <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    30   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    31   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    32   <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    33   <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    34   <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    35   <uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
    36   <uses-permission android:name="android.permission.WAKE_LOCK" />
    37   <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    38 </manifest>
    AndroidManifest

    配置完毕就可以搭界面和写C#逻辑了

    新建GetLocationAndPoiInfo脚本

     1 using System.Collections;
     2 using System.Collections.Generic;
     3 using UnityEngine;
     4 using UnityEngine.UI;
     5 
     6 public class GetLocationAndPoiInfo : MonoBehaviour {
     7 
     8     public Text locText;
     9     public Text poiText;
    10     public Button locBtn;
    11     public Button poiBtn;
    12 
    13     AndroidJavaClass jc;
    14     AndroidJavaObject jo;
    15 
    16     // Use this for initialization
    17     void Start () {
    18         OnStart();
    19         locBtn.onClick.AddListener(() => { GetLocationInfo(); });
    20         poiBtn.onClick.AddListener(() => { GetPoiInfo(); });
    21     }
    22     void OnStart() {
    23         jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    24         jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
    25     }
    26 
    27     void GetLocationInfo() {
    28         locText.text = "";
    29         OnStart();
    30         locText.text = jo.Call<string>("GetInfo");
    31     }
    32 
    33     void GetPoiInfo() {
    34         locText.text = "";
    35         OnStart();
    36         poiText.text = jo.Call<string>("GetPoi", "酒店", "", 1);
    37     }
    38 }
    GetLocationAndPoiInfo

    将脚本挂在任何一个物体上

    布置界面

    因为是Android工程发布到手机(或模拟器)才能运行

    上成果图

    到这里接高德地图SDK的工作就做完了

    根据手机朝向显示不同店家的逻辑我就不写了 挺麻烦的

    我说一下思路:

    在AndroidStudio中获取各个店家的经纬度与自身坐标点的相对位置信息并输出

    在Unity中获取到这个信息、解析、并转换为角度、再转换为匹配Input.compass指南针坐标系的角度

    然后设置一个视野范围(度数)

    最后根据手机朝向显示视野范围内不同的店家

    这么做有什么用处呢

    做类似pokemon go这样的东西时候这些信息就有用了

    写在最后:第一次公开写博,如有不妥之处请多指教

  • 相关阅读:
    Win10LTSC无法下载新版Microsoft Edge浏览器
    python识别视频黑屏或者低清晰度
    python提取视频第一帧图片
    盘点一下lua脚本和python的区别(基础)
    selenium控制已打开的页面
    frida- registernatives获取so层动态注册函数
    剑指 Offer 53
    剑指 Offer 52. 两个链表的第一个公共节点
    单链表中的环涉及到的6个相关问题
    剑指 Offer 51. 数组中的逆序对
  • 原文地址:https://www.cnblogs.com/sangblog/p/6942369.html
Copyright © 2020-2023  润新知