工作需要使用Unity制作launcher,需要获取Android系统中的时间与电量。期初打算使用jar包来实现,但发现了一些方法可以直接在Unity中获取。经过尝试,最终使用的方法如下:
时间
时间通过DateTime.Now()获取:
时:DateTime.Now.Hour();
分:DateTime.Now.Month();
秒:DateTime.Now.Second();
电量
电量通过Unity自带的SystemInfo.batteryLevel获取,注意该函数的取值范围为[0,1],所以要乘以100。
具体代码如下:
using System.Collections;
using UnityEngine;
using System;
public class TopMenu : MonoBehaviour
{
// Start is called before the first frame update
public TextMesh _time;
public TextMesh _buttery;
void Start()
{
Time.timeScale = 1;
StartCoroutine("UpdataTime");
StartCoroutine("UpdataBattery");
}
// Update is called once per frame
void Update()
{
}
IEnumerator UpdataTime()
{
while (true)
{
string h = DateTime.Now.Hour < 10 ? "0" + DateTime.Now.Hour.ToString() : DateTime.Now.Hour.ToString();
string m = DateTime.Now.Month < 10 ? "0" + DateTime.Now.Month.ToString() : DateTime.Now.Month.ToString();
string s = DateTime.Now.Second < 10 ? "0" + DateTime.Now.Second.ToString() : DateTime.Now.Second.ToString();
_time.text = h + ":" + m + ":" + s;
yield return new WaitForSeconds(1f);
}
}
IEnumerator UpdataBattery()
{
while (true)
{
_buttery.text = (SystemInfo.batteryLevel*100).ToString()+"%";
yield return new WaitForSeconds(1f);
}
}
}