Unity获取电量和充电状态

label显示电量,spBattery电量图标用来切换充电状态。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System.Linq;
using System.Text;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GUIMainSystemInfo : MonoBehaviour
{
// Start is called before the first frame update
[SerializeField]
UILabel labelBattery;
[SerializeField]
UISprite spBattery;
private float batteryLevel = 0;
private float prevBatteryLevel = 0;
private BatteryStatus batteryStatus;
private BatteryStatus prevBatteryStatus;
StringBuilder sb = new StringBuilder();
void Start()
{
if (labelBattery)
{
StartCoroutine("UpdataBattery");
}
}

    //更新手机电量
    IEnumerator UpdataBattery()
    {
        while (true)
        {
batteryLevel = SystemInfo.batteryLevel;
batteryStatus = SystemInfo.batteryStatus;
if (batteryLevel != prevBatteryLevel || batteryStatus != prevBatteryStatus)
{
prevBatteryLevel = SystemInfo.batteryLevel;
prevBatteryStatus = SystemInfo.batteryStatus;
if (batteryStatus == BatteryStatus.Charging)
{
labelBattery.text = "";
spBattery.spriteName = "btnbatty2";
}else
{
labelBattery.text = GetBatteryLevel();
spBattery.spriteName = "btnbatty";
}
}
            yield return new WaitForSeconds(300f);
        }
    }
//读取手机电量
    string GetBatteryLevel()
    {
sb.Remove(0, sb.Length);
sb.Append( Mathf.CeilToInt(SystemInfo.batteryLevel*100));
sb.Append("%");
        return sb.ToString();
    }
}
如果您觉得我的文章对您有所帮助,不妨小额捐助一下,您的鼓励是我长期坚持的动力。