unity如何获取安卓手机的时间电量网络信息

来源:互联网 发布:on淘宝旗舰店 编辑:程序博客网 时间:2024/04/30 15:07

unity5.x版本后,可以直接用代码来调取api获得安卓手机上的时间、电量、网络信息

下面是我经过测试调试好的代码  直接贴上就可使用  


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


public class BatteryAndTime : MonoBehaviour
{
public Text textlog;
//定义一个测试text来显示信息


void Start ()
{
StartCoroutine ("UpdataTime");//时间
StartCoroutine ("UpdataBattery");//电量
StartCoroutine ("UpdataNetWorker");//网络
}


 
//更新时间
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 += "当用户使用移动网络时";
}
}
     
}


demo下载地址:http://download.csdn.net/download/qq_37367472/9943512



原创粉丝点击