本文主要是解决了Unity获取安卓电量的问题,顺便也把获取时间代码完善了。
Unity想获取电量很多人是Unity跟安卓互发消息并且还要导入jar包,我在项目的时候老大发了一段神奇代码可以直接获取安卓手机电量,主要代码是GetBatteryLevel()。
下面我贴出了整个代码。
还有整个测试工程的Unity导出包unitypackage,测试apk。下载地址:http://download.csdn.net/detail/bill501y/9246719
</pre><pre name="code" class="csharp">using UnityEngine;using System.Collections;using System;public class BatteryAndTime : MonoBehaviour{ string _time = string.Empty; string _battery = string.Empty; void Start() { StartCoroutine("UpdataTime"); StartCoroutine("UpdataBattery"); } void OnGUI() { GUILayout.Label(_time, GUILayout.Width(100), GUILayout.Height(100)); GUILayout.Label(_battery, GUILayout.Width(100), GUILayout.Height(100)); } IEnumerator UpdataTime() { DateTime now = DateTime.Now; _time = string.Format("{0}:{1}", now.Hour, now.Minute); yield return new WaitForSeconds(60f - now.Second); while (true) { now = DateTime.Now; _time = string.Format("{0}:{1}", now.Hour, now.Minute); yield return new WaitForSeconds(60f); } } IEnumerator UpdataBattery() { while (true) { _battery = GetBatteryLevel().ToString(); yield return new WaitForSeconds(300f); } } int GetBatteryLevel() { try { string CapacityString = System.IO.File.ReadAllText("/sys/class/power_supply/battery/capacity"); return int.Parse(CapacityString); } catch (Exception e) { Debug.Log("Failed to read battery power; " + e.Message); } return -1; }}