Unity获取手机电量 网络和时间

来源:互联网 发布:安卓是linux系统吗 编辑:程序博客网 时间:2024/04/28 08:30

废话不多说 直接上脚本

using UnityEngine;
using System.Collections;
using System;
using UnityEngine.UI;


public class BatteryAndTime : MonoBehaviour
{
    public Text textlog;


    void Start()
    {
        StartCoroutine("UpdataTime");
        StartCoroutine("UpdataBattery");
        StartCoroutine("UpdataNetWorker");
    }


    void OnGUI()
    {
       
    }


    //更新时间
    IEnumerator UpdataTime()
    {
        DateTime now = DateTime.Now;
        textlog.text += string.Format("{0}:{1}", now.Hour, now.Minute);
        yield return new WaitForSeconds(60f - now.Second);
        while (true)
        {
            now = DateTime.Now;
            textlog.text +="\n当前系统时间:"+string.Format("{0}:{1}", now.Hour, now.Minute);
            yield return new WaitForSeconds(60f);
        }
    }


    //更新手机电量
    IEnumerator UpdataBattery()
    {
        while (true)
        {
            textlog.text += "\n当前手机电量:" + GetBatteryLevel().ToString();
            yield return new WaitForSeconds(300f);
        }
    }
    //更新手机状态
    IEnumerator UpdataNetWorker()
    {
        while (true)
        {
            GetNetWoker();
            yield return new WaitForSeconds(300f);
        }
    }


    #region 读取手机电量


    #endregion
    //读取手机电量
    int GetBatteryLevel()
    {
        try
        {
            
            string CapacityString = System.IO.File.ReadAllText("/sys/class/power_supply/battery/capacity");
            return int.Parse(CapacityString);


        }
        catch (Exception e)
        {
            Debug.Log("读取失败; " + e.Message);
        }
        return -1;
    }


    //读取手机网络状态
    void GetNetWoker()
    {
        //网络不可用状态
        if (Application.internetReachability == NetworkReachability.NotReachable)
        {
            textlog.text += "网络不可用状态";
        }
        //当用户使用WiFi时    
        else if (Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork)
        {
            textlog.text += "当用户使用WiFi或网线时";
        }
        //当用户使用移动网络时    
        else if (Application.internetReachability == NetworkReachability.ReachableViaCarrierDataNetwork)
        {
            textlog.text += "当用户使用移动网络时";
        }
    }
     
}



测试的话 建立一个text 挂到脚本上 显示网络状态  以上方法亲测可以使用  电量的获取 华为手机无效

项目地址:http://pan.baidu.com/s/1o82q7cm