网络延迟获取
这个其实很简单,在客户端发送消息的时候,记录一个时间start_timeStamp,消息返回的时候,记录一个时间end_timeStamp,end_timeStamp-start_timeStamp得到的就是本条消息的网络延迟(时间单位要精确到毫秒)。对于手机游戏,显示网络延迟没有pc端的需求刚,所以不去高频率获取延迟从而得到高精确的延迟数值。可以固定几秒获取一次(心跳包可以做这个工作),或者在发送接受消息和接受消息的总接口进行计算,记录一下网络延迟,每发送一个消息就更新一次网络延迟。
这样下来,没有平台之分,android,ios各种系统基本上都可以,简单又方便。
手机电量获取
Android
先上代码
声明变量
private BroadcastReceiver batteryLevelRcvr;
private IntentFilter batteryLevelFilter;
public static String batteryLevel;
注册电量监听
private void monitorBatteryState() {
batteryLevelRcvr = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
StringBuilder sb = new StringBuilder();
int rawlevel = intent.getIntExtra("level", -1);
int scale = intent.getIntExtra("scale", -1);
if (rawlevel >= 0 && scale > 0) {
batteryLevel = ((rawlevel * 100) / scale) + "";
}
}
};
batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelRcvr, batteryLevelFilter);
}
当程序退出的时候,我们要取消对电池电量广播的监听,在Activity的onDestroy方法里添加如下代码:
unregisterReceiver(batteryLevelRcvr)
这里面主要的是BroadcastReceiver和Intent.ACTION_BATTERY_CHANGED。安卓没办法直接进行电量的获取,它的电量变化以广播的形式发送出来,我们使用BroadcastReceiver接收广播,使用Intent.ACTION_BATTERY_CHANGED来过滤出电量变化的广播。这样我们就得到了Android手机的电量。
IOS
导入文件
#import "IOPSKeys.h"
#import "IOPowerSources.h"
实现代码
+(double)getCurrentBatteryLevel
{
//Returns a blob of Power Source information in an opaque CFTypeRef.
CFTypeRef blob = IOPSCopyPowerSourcesInfo();
//Returns a CFArray of Power Source handles, each of type CFTypeRef.
CFArrayRef sources = IOPSCopyPowerSourcesList(blob);
CFDictionaryRef pSource = NULL;
const void *psValue;
//Returns the number of values currently in an array.
int numOfSources = CFArrayGetCount(sources);
//Error in CFArrayGetCount
if (numOfSources == 0)
{
NSLog(@"Error in CFArrayGetCount");
return -1.0f;
}
//Calculating the remaining energy
for (int i = 0 ; i < numOfSources ; i++)
{
//Returns a CFDictionary with readable information about the specific power source.
pSource = IOPSGetPowerSourceDescription(blob, CFArrayGetValueAtIndex(sources, i));
if (!pSource)
{
NSLog(@"Error in IOPSGetPowerSourceDescription");
return -1.0f;
}
psValue = (CFStringRef)CFDictionaryGetValue(pSource, CFSTR(kIOPSNameKey));
int curCapacity = 0;
int maxCapacity = 0;
double percent;
psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSCurrentCapacityKey));
CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &curCapacity);
psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSMaxCapacityKey));
CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &maxCapacity);
percent = ((double)curCapacity/(double)maxCapacity * 100.0f);
return percent;
}
return -1.0f;
}