天天看點

Unity擷取手機電量 網絡和時間

廢話不多說 直接上腳本

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

繼續閱讀