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

偏执的太偏执、 2022-06-14 07:40 327阅读 0赞

废话不多说 直接上脚本

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

public class BatteryAndTime : MonoBehaviour
{
public Text textlog;

  1. void Start()
  2. \{
  3. StartCoroutine("UpdataTime");
  4. StartCoroutine("UpdataBattery");
  5. StartCoroutine("UpdataNetWorker");
  6. \}
  7. void OnGUI()
  8. \{
  9. \}
  10. //更新时间
  11. IEnumerator UpdataTime()
  12. \{
  13. DateTime now = DateTime.Now;
  14. textlog.text += string.Format("\{0\}:\{1\}", now.Hour, now.Minute);
  15. yield return new WaitForSeconds(60f - now.Second);
  16. while (true)
  17. \{
  18. now = DateTime.Now;
  19. textlog.text +="\\n当前系统时间:"+string.Format("\{0\}:\{1\}", now.Hour, now.Minute);
  20. yield return new WaitForSeconds(60f);
  21. \}
  22. \}
  23. //更新手机电量
  24. IEnumerator UpdataBattery()
  25. \{
  26. while (true)
  27. \{
  28. textlog.text += "\\n当前手机电量:" + GetBatteryLevel().ToString();
  29. yield return new WaitForSeconds(300f);
  30. \}
  31. \}
  32. //更新手机状态
  33. IEnumerator UpdataNetWorker()
  34. \{
  35. while (true)
  36. \{
  37. GetNetWoker();
  38. yield return new WaitForSeconds(300f);
  39. \}
  40. \}
  41. \#region 读取手机电量
  42. \#endregion
  43. //读取手机电量
  44. int GetBatteryLevel()
  45. \{
  46. try
  47. \{
  48. string CapacityString = System.IO.File.ReadAllText("/sys/class/power\_supply/battery/capacity");
  49. return int.Parse(CapacityString);
  50. \}
  51. catch (Exception e)
  52. \{
  53. Debug.Log("读取失败; " + e.Message);
  54. \}
  55. return -1;
  56. \}
  57. //读取手机网络状态
  58. void GetNetWoker()
  59. \{
  60. //网络不可用状态
  61. if (Application.internetReachability == NetworkReachability.NotReachable)
  62. \{
  63. textlog.text += "网络不可用状态";
  64. \}
  65. //当用户使用WiFi时
  66. else if (Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork)
  67. \{
  68. textlog.text += "当用户使用WiFi或网线时";
  69. \}
  70. //当用户使用移动网络时
  71. else if (Application.internetReachability == NetworkReachability.ReachableViaCarrierDataNetwork)
  72. \{
  73. textlog.text += "当用户使用移动网络时";
  74. \}
  75. \}

}

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

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

发表评论

表情:
评论列表 (有 0 条评论,327人围观)

还没有评论,来说两句吧...

相关阅读