4创建unity工程
unity需要的资源
此项目要用到高德web围栏功能,因为web围栏功能返回的信息是一个Json类型的,所以要用到SimpleJSON.cs功能脚本,这个脚本是由SimpleJSON官方提供,非常好用,此脚本要放在Plugin文件夹下。
unity-Android.cs脚本是逻辑脚本,挂在Driver上。
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using SimpleJSON;
using System;
public class unity_Android : MonoBehaviour {
public Text text;
//获取手机的序列号
string imei0 = "";
string imei1 = "";
string meid = "";
//GPS定位信息
string GpsInfo = "";
//获取经纬度
string longitude= "";
string latitude= "";
//时间戳
string time= "";
//围栏Key
string key="创建web围栏项目申请的key,高德地图开放平台获取";
private string url;//围栏的返回结果地址
JSONNode Node;
string isIn = "";
string fence_gid = "";
string fence_name = "";
private AndroidJavaObject m_AndroidJavaObject = null;
string[] a = new string[4];
void Start()
{
Debug.Log("Unity Call");
GetDeviceIMEI();
OnStart();
}
//获取是否在围栏的返回信息
private IEnumerator GetJson()
{
WWW getData = new WWW(url);
yield return getData;
if (getData.error != null)
{
Debug.Log(getData.error);
}
else
{
Debug.Log(getData.text);
text.text = getData.text;
}
Node = JSON.Parse(getData.text);
isIn = Node["data"]["fencing_event_list"][0]["client_status"];
fence_gid = Node["data"]["fencing_event_list"][0]["fence_info"]["fence_gid"];
fence_name = Node["data"]["fencing_event_list"][0]["fence_info"]["fence_name"];
string nearest_fence_distance = Node["data"]["nearest_fence_distance"];
text.text = "isIn:" + isIn + "\t\nGid:" + fence_gid + "\t\nfence_name:" + fence_name+ "\t\n不在服务区,距离还有:" + nearest_fence_distance
+"定位信息:"+GpsInfo;
StopLocation();
}
void OnStart()
{
AndroidJavaClass androidJavaClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
m_AndroidJavaObject = androidJavaClass.GetStatic("currentActivity");
}
//获取手机的序列号
void GetDeviceIMEI()
{
var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
var context = unityPlayer.GetStatic("currentActivity");
var telephoneyManager = context.Call("getSystemService", "phone");
imei0 = telephoneyManager.Call("getImei", 0);//如果手机双卡 双待 就会有两个MIEI号
imei1 = telephoneyManager.Call("getImei", 1);
meid = telephoneyManager.Call("getMeid");//电信的手机 是MEID
text.text= "IMEI0:" + imei0+ "\r\n" + "IMEI1:" + imei1+ "\r\n" + "MEID:" + meid;
}
//测试定位和是否在围栏内的方法,点击button调用触发
public void startLocation()
{
OnStart();
m_AndroidJavaObject.Call("GetInfo");
}
public void checkFenca(string a)
{
text.text = "jinlaile";
string[] sArray = a.Split(',');
longitude = sArray[0];
latitude = sArray[1];
time = sArray[2].Substring(0, 10);
GpsInfo = sArray[3];
isIn = "";
fence_gid = "";
fence_name = "";
url = "https://restapi.amap.com/v4/geofence/status?key=" + key + "&diu=" + imei0 + "&locations=" + longitude + "," + latitude + "," + time;
StartCoroutine(GetJson());
}
//停止定位
public void StopLocation()
{
OnStart();
m_AndroidJavaObject.Call("stopLocation");
}
}
5创建围栏
按照高德官方的说明:请将json参数添加到body体中发送。