Unity获取安卓电量和时间

本文主要是解决了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;
    }
}

  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值