BatteryPlugin.java 836 B

1234567891011121314151617181920212223
  1. package com.example.androidbatteryplugin;
  2. import android.content.BroadcastReceiver;
  3. import android.content.Context;
  4. import android.content.Intent;
  5. import android.content.IntentFilter;
  6. import android.os.BatteryManager;
  7. import com.unity3d.player.UnityPlayer;
  8. import com.unity3d.player.UnityPlayerActivity;
  9. public class BatteryPlugin extends UnityPlayerActivity {
  10. public static int GetBatteryLevel() {
  11. IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
  12. Intent batteryStatus = UnityPlayer.currentActivity.registerReceiver(null, ifilter);
  13. int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
  14. int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
  15. float batteryPct = (level / (float) scale) * 100;
  16. return (int)batteryPct;
  17. }
  18. }