package com.secondworld.sdk.utils;
|
|
import android.content.BroadcastReceiver;
|
import android.content.Context;
|
import android.content.Intent;
|
import android.content.IntentFilter;
|
import android.os.BatteryManager;
|
|
import com.secondworld.sdk.GameApp;
|
import com.secondworld.sdk.UnityMsgHandler;
|
|
import java.util.HashMap;
|
import java.util.Map;
|
import java.util.Objects;
|
|
/**
|
* Created by Administrator on 2018/7/15 0015.
|
*/
|
|
public class BatteryUtil {
|
private static BatteryUtil s_Instance = null;
|
|
public static BatteryUtil getInstance() {
|
if (s_Instance == null) {
|
s_Instance = new BatteryUtil();
|
}
|
return s_Instance;
|
}
|
|
private BatteryBroadCastReceiver m_BatteryBroadCastReceiver;
|
|
private BatteryUtil() {
|
}
|
|
public void start() {
|
m_BatteryBroadCastReceiver = new BatteryBroadCastReceiver();
|
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
|
GameApp.I.registerReceiver(m_BatteryBroadCastReceiver, filter);
|
}
|
|
public void stop() {
|
if (m_BatteryBroadCastReceiver != null) {
|
try {
|
GameApp.I.unregisterReceiver(m_BatteryBroadCastReceiver);
|
m_BatteryBroadCastReceiver = null;
|
} catch (IllegalArgumentException e) {
|
if (!Objects.requireNonNull(e.getMessage()).contains("Receiver not registered")) {
|
throw e;
|
}
|
}
|
}
|
}
|
|
private static class BatteryBroadCastReceiver extends BroadcastReceiver {
|
private int m_BatteryLevel;
|
private int m_Status;
|
|
public BatteryBroadCastReceiver() {
|
m_BatteryLevel = 0;
|
}
|
|
@Override
|
public void onReceive(Context context, Intent intent) {
|
if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
|
int _batteryLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
|
|
Map<String, Object> _msg = new HashMap<>();
|
|
if (_batteryLevel != m_BatteryLevel) {
|
try {
|
_msg.put("code", CodeA2U.BatteryLevel);
|
_msg.put("level", _batteryLevel);
|
|
UnityMsgHandler.sendMessageToUnity(_msg);
|
|
m_BatteryLevel = _batteryLevel;
|
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
}
|
|
int _status = intent.getIntExtra("status", 0);
|
|
if (_status != m_Status) {
|
_msg.clear();
|
|
int _transCode = 0;
|
if (_status == BatteryManager.BATTERY_STATUS_CHARGING) {
|
_transCode = 2;
|
} else if (_status == BatteryManager.BATTERY_STATUS_NOT_CHARGING ||
|
_status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
|
_transCode = 1;
|
} else if (_status == BatteryManager.BATTERY_STATUS_FULL) {
|
_transCode = 3;
|
}
|
|
_msg.put("code", CodeA2U.BatteryCharging);
|
_msg.put("status", _transCode);
|
|
UnityMsgHandler.sendMessageToUnity(_msg);
|
|
m_Status = _status;
|
}
|
}
|
}
|
}
|
}
|