unity 获取电量;

2019-07-14 03:17发布

/ 开始接收电量广播; private void StartReceiveBatteryBroadcast()
    {
        registerReceiver( mBatInfoReceiver, new IntentFilter( Intent.ACTION_BATTERY_CHANGED ) );
    }

    // 停止接收电量广播;
    private void StopReceiveBatteryBroadcast()
    {
    unregisterReceiver( mBatInfoReceiver );
    }
    private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver()   
    {  
        @Override
public void onReceive( Context context, Intent intent )   
        {  
            String action = intent.getAction();  
         
            if ( Intent.ACTION_BATTERY_CHANGED.equals( action ) )   
            {  
                int NowBattery = intent.getIntExtra( "level", 0 );   
                UnityPlayer.UnitySendMessage( "GameManager", "AndroidBatteryPower", String.valueOf( NowBattery ) );
                  
                switch ( intent.getIntExtra( "status", BatteryManager.BATTERY_STATUS_UNKNOWN ) )   
                {  
                case BatteryManager.BATTERY_STATUS_CHARGING:  
                    // "充电状态";  
                    break;    
                default:
                break; 
                }  
            }  
        }  
    };

ios C# [DllImport("__Internal")]
private static extern float getiOSBatteryLevel ();

public static string GetBatteryPower()
{
if ( Application.platform != RuntimePlatform.OSXEditor )
{
return ( getiOSBatteryLevel() * 100 ).ToString();
}
return "";
}

// . h . m #import
#import
#import "Reachability.h"
//#import "UnityAppController.h"
#import
#import
#import


#import
#import


@interface SystemInfo : NSObject
- (NSString *)getNetWorkStates;
- (NSString *)getcarrieName;
- (NSString *)getIPAddress;
@end


extern "C"
{
    // 获取电池电量,范围0到1.0。-1表示电量未知。
    float getiOSBatteryLevel();
}
extern void UnitySendMessage(const char *,const char *,const char *);

#import "SystemInfo.h"






static struct utsname systemInfo;


static SystemInfo *mySystemInfo;

float getiOSBatteryLevel()
{
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
return [[UIDevice currentDevice] batteryLevel];
}