导航菜单

页面标题

页面副标题

xDrip+ v04633772025.07.16 - JoH.java 源代码

正在查看: xDrip+ v04633772025.07.16 应用的 JoH.java JAVA 源代码文件

本页面展示 JAVA 反编译生成的源代码文件,支持语法高亮显示。 仅供安全研究与技术分析使用,严禁用于任何非法用途。请遵守相关法律法规。


package com.eveningoutpost.dexdrip.models;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.Signature;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.ParcelFileDescriptor;
import android.os.PowerManager;
import android.os.Process;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.format.DateFormat;
import android.text.method.DigitsKeyListener;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.ContextThemeWrapper;
import androidx.core.app.NotificationCompat;
import androidx.core.content.FileProvider;
import androidx.health.platform.client.error.ErrorCode;
import androidx.loader.content.CursorLoader;
import androidx.recyclerview.widget.RecyclerView;
import ar.com.hjg.pngj.chunks.ChunkCopyBehaviour;
import com.activeandroid.ActiveAndroid;
import com.eveningoutpost.dexdrip.Home;
import com.eveningoutpost.dexdrip.importedlibraries.usbserial.driver.UsbId;
import com.eveningoutpost.dexdrip.models.UserError;
import com.eveningoutpost.dexdrip.utilitymodels.PersistentStore;
import com.eveningoutpost.dexdrip.utilitymodels.Pref;
import com.eveningoutpost.dexdrip.utilitymodels.XdripNotificationCompat;
import com.eveningoutpost.dexdrip.utils.BestGZIPOutputStream;
import com.eveningoutpost.dexdrip.utils.CipherUtils;
import com.eveningoutpost.dexdrip.utils.framework.BuggySamsung;
import com.eveningoutpost.dexdrip.xdrip;
import com.google.common.primitives.Bytes;
import com.google.common.primitives.UnsignedInts;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.Semaphore;
import java.util.zip.CRC32;
import java.util.zip.Deflater;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;

public class JoH {
    private static final String BUGGY_SAMSUNG_ENABLED = "buggy-samsung-enabled";
    private static final int PAIRING_VARIANT_PASSKEY = 1;
    private static final String TAG = "jamorham JoH";
    private static DecimalFormat df;
    private static DecimalFormatSymbols dfs;
    private static Gson gson_instance;
    private static volatile MediaPlayer player;
    private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
    private static double benchmark_time = BgReading.BESTOFFSET;
    private static Map<String, Double> benchmarks = new HashMap();
    private static final Map<String, Long> rateLimits = new HashMap();
    private static final boolean debug_wakelocks = false;
    public static boolean buggy_samsung = debug_wakelocks;
    private static final Semaphore playerLock = new Semaphore(1);

    public static long msSince(long j, long j2) {
        return j - j2;
    }

    public static String qs0(double d, int i) {
        String qs = qs(d, i);
        if (!qs.startsWith(".")) {
            return qs;
        }
        return "0" + qs;
    }

    public static String qs(double d) {
        return qs(d, 2);
    }

    public static String qs(double d, int i) {
        DecimalFormat decimalFormat;
        if (i == -1) {
            int i2 = (int) d;
            i = ((double) i2) != d ? ((double) ((i2 * 10) / 10)) != d ? ((double) ((i2 * 100) / 100)) != d ? 3 : 2 : 1 : 0;
        }
        if (dfs == null) {
            DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
            decimalFormatSymbols.setDecimalSeparator('.');
            dfs = decimalFormatSymbols;
        }
        if (Thread.currentThread().getId() == 1) {
            if (df == null) {
                DecimalFormat decimalFormat2 = new DecimalFormat("#", dfs);
                decimalFormat2.setMinimumIntegerDigits(1);
                df = decimalFormat2;
            }
            decimalFormat = df;
        } else {
            decimalFormat = new DecimalFormat("#", dfs);
        }
        decimalFormat.setMaximumFractionDigits(i);
        return decimalFormat.format(d);
    }

    public static double ts() {
        return new Date().getTime();
    }

    public static long tsl() {
        return System.currentTimeMillis();
    }

    public static long uptime() {
        return SystemClock.elapsedRealtime();
    }

    public static boolean upForAtLeastMins(int i) {
        if (uptime() > i * 60000) {
            return true;
        }
        return debug_wakelocks;
    }

    public static long msSince(long j) {
        return tsl() - j;
    }

    public static long msTill(long j) {
        return j - tsl();
    }

    public static long absMsSince(long j) {
        return Math.abs(tsl() - j);
    }

    public static String bytesToHex(byte[] bArr) {
        if (bArr == null) {
            return "<empty>";
        }
        char[] cArr = new char[bArr.length * 2];
        for (int i = 0; i < bArr.length; i++) {
            int i2 = bArr[i] & 255;
            int i3 = i * 2;
            char[] cArr2 = hexArray;
            cArr[i3] = cArr2[i2 >>> 4];
            cArr[i3 + 1] = cArr2[i2 & 15];
        }
        return new String(cArr);
    }

    public static String bytesToHexMacFormat(byte[] bArr) {
        if (bArr == null || bArr.length == 0) {
            return "NoMac";
        }
        String bytesToHex = bytesToHex(bArr);
        StringBuilder sb = new StringBuilder();
        int i = 0;
        while (i < bytesToHex.length()) {
            if (sb.length() > 0) {
                sb.append(":");
            }
            int i2 = i + 2;
            sb.append(bytesToHex.substring(i, i2));
            i = i2;
        }
        return sb.toString();
    }

    public static byte[] reverseBytes(byte[] bArr) {
        byte[] bArr2 = new byte[bArr.length];
        for (int i = 0; i < bArr.length; i++) {
            bArr2[(bArr.length - i) - 1] = bArr[i];
        }
        return bArr2;
    }

    public static byte[] tolerantHexStringToByteArray(String str) {
        return hexStringToByteArray(str.toUpperCase().replaceAll("[^A-F0-9]", ""));
    }

    public static byte[] hexStringToByteArray(String str) {
        try {
            String trim = str.toUpperCase().trim();
            if (trim.length() == 0) {
                return null;
            }
            int length = trim.length();
            byte[] bArr = new byte[length / 2];
            for (int i = 0; i < length; i += 2) {
                bArr[i / 2] = (byte) ((Character.digit(trim.charAt(i), 16) << 4) + Character.digit(trim.charAt(i + 1), 16));
            }
            return bArr;
        } catch (Exception e) {
            Log.e(TAG, "Exception processing hexString: " + e);
            return null;
        }
    }

    public static String macFormat(String str) {
        if (str == null) {
            return null;
        }
        try {
            return str.replaceAll("[^a-fA-F0-9]", "").replaceAll("(.{2})", "$1:").substring(0, 17);
        } catch (Exception unused) {
            return null;
        }
    }

    public static <K, V extends Comparable<? super V>> SortedSet<Map.Entry<K, V>> mapSortedByValue(Map<K, V> map, final boolean z) {
        TreeSet treeSet = new TreeSet(new Comparator() {
            @Override
            public final int compare(Object obj, Object obj2) {
                int lambda$mapSortedByValue$0;
                lambda$mapSortedByValue$0 = JoH.lambda$mapSortedByValue$0(z, (Map.Entry) obj, (Map.Entry) obj2);
                return lambda$mapSortedByValue$0;
            }
        });
        treeSet.addAll(map.entrySet());
        return treeSet;
    }

    public static int lambda$mapSortedByValue$0(boolean z, Map.Entry entry, Map.Entry entry2) {
        int compareTo;
        if (z) {
            compareTo = ((Comparable) entry2.getValue()).compareTo(entry.getValue());
        } else {
            compareTo = ((Comparable) entry.getValue()).compareTo(entry2.getValue());
        }
        if (compareTo != 0) {
            return compareTo;
        }
        return 1;
    }

    public static String compressString(String str) {
        try {
            Deflater deflater = new Deflater();
            deflater.setInput(str.getBytes(Charset.forName("UTF-8")));
            deflater.finish();
            byte[] bArr = new byte[str.length() + ChunkCopyBehaviour.COPY_ALMOSTALL];
            int deflate = deflater.deflate(bArr);
            deflater.end();
            return Base64.encodeToString(bArr, 0, deflate, 2);
        } catch (Exception unused) {
            return null;
        }
    }

    public static byte[] compressStringToBytes(String str) {
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(str.length());
            BestGZIPOutputStream bestGZIPOutputStream = new BestGZIPOutputStream(byteArrayOutputStream);
            bestGZIPOutputStream.write(str.getBytes(Charset.forName("UTF-8")));
            bestGZIPOutputStream.close();
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            byteArrayOutputStream.close();
            return byteArray;
        } catch (Exception e) {
            Log.e(TAG, "Exception in compress: " + e.toString());
            return new byte[0];
        }
    }

    public static byte[] compressBytesforPayload(byte[] bArr) {
        return compressBytesToBytes(Bytes.concat(bArr, bchecksum(bArr)));
    }

    public static byte[] compressBytesToBytes(byte[] bArr) {
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(bArr.length);
            BestGZIPOutputStream bestGZIPOutputStream = new BestGZIPOutputStream(byteArrayOutputStream);
            bestGZIPOutputStream.write(bArr);
            bestGZIPOutputStream.close();
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            byteArrayOutputStream.close();
            return byteArray;
        } catch (Exception e) {
            Log.e(TAG, "Exception in compress: " + e.toString());
            return new byte[0];
        }
    }

    public static byte[] decompressBytesToBytes(byte[] bArr) {
        try {
            Log.d(TAG, "Decompressing  bytes size: " + bArr.length);
            byte[] bArr2 = new byte[8192];
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bArr);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(bArr.length);
            GZIPInputStream gZIPInputStream = new GZIPInputStream(byteArrayInputStream, 8192);
            while (true) {
                int read = gZIPInputStream.read(bArr2);
                if (read != -1) {
                    byteArrayOutputStream.write(bArr2, 0, read);
                } else {
                    gZIPInputStream.close();
                    byteArrayInputStream.close();
                    return byteArrayOutputStream.toByteArray();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Exception in decompress: " + e.toString());
            return new byte[0];
        }
    }

    public static String uncompressString(String str) {
        try {
            byte[] decode = Base64.decode(str, 2);
            Inflater inflater = new Inflater();
            inflater.setInput(decode);
            inflater.finished();
            byte[] bArr = new byte[ErrorCode.INVALID_OWNERSHIP];
            int inflate = inflater.inflate(bArr);
            inflater.end();
            Log.d(TAG, "Inflated bytes: " + inflate);
            return new String(bArr, 0, inflate, "UTF-8");
        } catch (Exception unused) {
            Log.e(TAG, "Got exception uncompressing string");
            return null;
        }
    }

    public static String base64encode(String str) {
        try {
            return new String(Base64.encode(str.getBytes("UTF-8"), 2), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            Log.e(TAG, "Got unsupported encoding: " + e);
            return "encode-error";
        }
    }

    public static String base64decode(String str) {
        try {
            return new String(Base64.decode(str.getBytes("UTF-8"), 2), "UTF-8");
        } catch (UnsupportedEncodingException | IllegalArgumentException e) {
            Log.e(TAG, "Got unsupported encoding: " + e);
            return "decode-error";
        }
    }

    public static String base64encodeBytes(byte[] bArr) {
        try {
            return new String(Base64.encode(bArr, 2), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            Log.e(TAG, "Got unsupported encoding: " + e);
            return "encode-error";
        }
    }

    public static byte[] base64decodeBytes(String str) {
        try {
            return Base64.decode(str.getBytes("UTF-8"), 2);
        } catch (UnsupportedEncodingException | IllegalArgumentException e) {
            Log.e(TAG, "Got unsupported encoding: " + e);
            return new byte[0];
        }
    }

    public static String ucFirst(String str) {
        return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
    }

    public static String readLine(InputStream inputStream) {
        try {
            byte[] bArr = new byte[512];
            for (int i = 0; i < 512; i++) {
                int read = inputStream.read();
                if (read == -1) {
                    return null;
                }
                if (read == 10) {
                    return new String(bArr, 0, i, StandardCharsets.UTF_8);
                }
                bArr[i] = (byte) read;
            }
        } catch (IOException e) {
            UserError.Log.e(TAG, "Error reading line: " + e);
        }
        return null;
    }

    public static boolean isSamsung() {
        return BuggySamsung.isSamsung();
    }

    public static void persistentBuggySamsungCheck() {
        if (buggy_samsung || !isSamsung() || PersistentStore.getLong(BUGGY_SAMSUNG_ENABLED) <= 4) {
            return;
        }
        buggy_samsung = true;
        UserError.Log.d(TAG, "Enabling wake workaround mode due to historical pattern");
    }

    public static void setBuggySamsungEnabled() {
        if (buggy_samsung) {
            return;
        }
        buggy_samsung = true;
        PersistentStore.incrementLong(BUGGY_SAMSUNG_ENABLED);
    }

    public static String getFieldFromURI(String str, Uri uri) {
        try {
            Cursor loadInBackground = new CursorLoader(xdrip.getAppContext(), uri, new String[]{str}, null, null, null).loadInBackground();
            int columnIndexOrThrow = loadInBackground.getColumnIndexOrThrow(str);
            loadInBackground.moveToFirst();
            String string = loadInBackground.getString(columnIndexOrThrow);
            loadInBackground.close();
            return string;
        } catch (Exception e) {
            UserError.Log.d(TAG, "Got exception extracting data for uri " + e);
            return null;
        }
    }

    public static class DecimalKeyListener extends DigitsKeyListener {
        private final char[] acceptedCharacters = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', new DecimalFormat().getDecimalFormatSymbols().getDecimalSeparator()};

        @Override
        public int getInputType() {
            return 2;
        }

        @Override
        protected char[] getAcceptedChars() {
            return this.acceptedCharacters;
        }
    }

    public static String backTrace() {
        return backTrace(1);
    }

    public static String backTrace(int i) {
        try {
            StackTraceElement stackTraceElement = new Exception().getStackTrace()[i + 2];
            StackTraceElement stackTraceElement2 = new Exception().getStackTrace()[i + 3];
            String[] split = stackTraceElement.getClassName().split("\\.");
            return stackTraceElement2.getClassName().split("\\.")[r1.length - 1] + "::" + stackTraceElement2.getMethodName() + " -> " + split[split.length - 1] + "::" + stackTraceElement.getMethodName();
        } catch (Exception e) {
            return "unknown backtrace: " + e.toString();
        }
    }

    public static String backTraceShort(int i) {
        try {
            return new Exception().getStackTrace()[i + 3].getMethodName();
        } catch (Exception e) {
            return "unknown backtrace: " + e.toString();
        }
    }

    public static void benchmark(String str) {
        if (str == null) {
            if (benchmark_time == BgReading.BESTOFFSET) {
                benchmark_time = ts();
                return;
            } else {
                Log.e(TAG, "Cannot start a benchmark as one is already running - cancelling");
                benchmark_time = BgReading.BESTOFFSET;
                return;
            }
        }
        if (benchmark_time == BgReading.BESTOFFSET) {
            Log.e(TAG, "Benchmark: " + str + " no benchmark set!");
            return;
        }
        Log.i(TAG, "Benchmark: " + str + " " + (ts() - benchmark_time) + " ms");
        benchmark_time = BgReading.BESTOFFSET;
    }

    public static void dumpBundle(Bundle bundle, String str) {
        if (bundle != null) {
            for (String str2 : bundle.keySet()) {
                Object obj = bundle.get(str2);
                if (obj != null) {
                    UserError.Log.d(str, String.format("%s %s (%s)", str2, obj.toString(), obj.getClass().getName()));
                    if (obj instanceof Bundle) {
                        dumpBundle((Bundle) obj, str + "::" + str2);
                    }
                }
            }
            return;
        }
        UserError.Log.d(str, "Bundle is empty");
    }

    public static synchronized boolean differentBytes(String str, byte[] bArr) {
        synchronized (JoH.class) {
            String str2 = "differentBytes-" + str;
            String string = PersistentStore.getString(str2);
            String sha256 = CipherUtils.getSHA256(bArr);
            if (sha256.equals(string)) {
                return debug_wakelocks;
            }
            PersistentStore.setString(str2, sha256);
            return true;
        }
    }

    public static synchronized void clearRatelimit(String str) {
        synchronized (JoH.class) {
            if (PersistentStore.getLong(str) > 0) {
                PersistentStore.setLong(str, 0L);
            }
            Map<String, Long> map = rateLimits;
            if (map.containsKey(str)) {
                map.remove(str);
            }
        }
    }

    public static synchronized boolean pratelimit(String str, int i) {
        long longValue;
        synchronized (JoH.class) {
            long tsl = tsl();
            Map<String, Long> map = rateLimits;
            if (!map.containsKey(str)) {
                longValue = PersistentStore.getLong(str);
            } else {
                longValue = map.get(str).longValue();
            }
            if (longValue > 0 && tsl - longValue < i * 1000) {
                Log.d(TAG, str + " rate limited: " + i + " seconds");
                return debug_wakelocks;
            }
            map.put(str, Long.valueOf(tsl));
            PersistentStore.setLong(str, tsl);
            return true;
        }
    }

    public static synchronized boolean ratelimit(String str, int i) {
        synchronized (JoH.class) {
            Map<String, Long> map = rateLimits;
            if (map.containsKey(str) && tsl() - map.get(str).longValue() < i * 1000) {
                Log.d(TAG, str + " rate limited: " + i + " seconds");
                return debug_wakelocks;
            }
            map.put(str, Long.valueOf(tsl()));
            return true;
        }
    }

    public static synchronized boolean quietratelimit(String str, int i) {
        synchronized (JoH.class) {
            Map<String, Long> map = rateLimits;
            if (map.containsKey(str) && tsl() - map.get(str).longValue() < i * 1000) {
                return debug_wakelocks;
            }
            map.put(str, Long.valueOf(tsl()));
            return true;
        }
    }

    public static synchronized boolean ratelimitmilli(String str, int i) {
        synchronized (JoH.class) {
            Map<String, Long> map = rateLimits;
            if (map.containsKey(str) && tsl() - map.get(str).longValue() < i) {
                return debug_wakelocks;
            }
            map.put(str, Long.valueOf(tsl()));
            return true;
        }
    }

    public static String getDeviceDetails() {
        return Build.MANUFACTURER.replace(" ", "_") + " " + Build.MODEL.replace(" ", "_") + " " + (Integer.toString(Build.VERSION.SDK_INT) + " " + Build.VERSION.RELEASE + " " + Build.VERSION.INCREMENTAL);
    }

    public static String getVersionDetails() {
        try {
            return xdrip.getAppContext().getPackageManager().getPackageInfo(xdrip.getAppContext().getPackageName(), 128).versionName;
        } catch (Exception unused) {
            return "Unknown version";
        }
    }

    public static boolean isOldVersion(Context context) {
        try {
            Signature[] signatureArr = context.getPackageManager().getPackageInfo(context.getPackageName(), 64).signatures;
            if (signatureArr.length == 1) {
                CRC32 crc32 = new CRC32();
                byte[] byteArray = signatureArr[0].toByteArray();
                crc32.update(byteArray, 0, byteArray.length);
                if (crc32.getValue() == 2009579833) {
                    return true;
                }
            }
        } catch (Exception e) {
            Log.d(TAG, "exception: " + e);
        }
        return debug_wakelocks;
    }

    public static boolean getWifiSleepPolicyNever() {
        try {
            int i = Settings.Global.getInt(xdrip.getAppContext().getContentResolver(), "wifi_sleep_policy");
            StringBuilder sb = new StringBuilder();
            sb.append("Current WifiPolicy: ");
            sb.append(i == 2 ? "Never" : Integer.toString(i));
            sb.append(" ");
            sb.append(0);
            sb.append(" ");
            sb.append(1);
            Log.d(TAG, sb.toString());
            if (i == 2) {
                return true;
            }
            return debug_wakelocks;
        } catch (Exception unused) {
            Log.e(TAG, "Exception during global settings policy");
            return true;
        }
    }

    public static void benchmark_method_start() {
        benchmarks.put(backTrace(0), Double.valueOf(ts()));
    }

    public static void benchmark_method_end() {
        String backTrace = backTrace(0);
        try {
            Log.i(TAG, "Benchmark: " + backTrace + " " + (ts() - benchmarks.get(backTrace).doubleValue()) + "ms");
        } catch (Exception unused) {
            Log.e(TAG, "Benchmark: " + backTrace + " no benchmark set!");
        }
    }

    public static void fixActionBar(AppCompatActivity appCompatActivity) {
        try {
            appCompatActivity.getSupportActionBar().setDisplayShowHomeEnabled(true);
            appCompatActivity.getSupportActionBar().setIcon(2131230915);
        } catch (Exception e) {
            Log.e(TAG, "Got exception with supportactionbar: " + e.toString());
        }
    }

    public static HashMap<String, Object> JsonStringtoMap(String str) {
        return (HashMap) new Gson().fromJson(str, new TypeToken<HashMap<String, Object>>() {
        }.getType());
    }

    public static List<Float> JsonStringToFloatList(String str) {
        return (List) new Gson().fromJson(str, new TypeToken<ArrayList<Float>>() {
        }.getType());
    }

    public static Gson defaultGsonInstance() {
        if (gson_instance == null) {
            gson_instance = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        }
        return gson_instance;
    }

    public static String hourMinuteString() {
        return hourMinuteString(tsl());
    }

    public static String hourMinuteString(long j) {
        return DateFormat.format("kk:mm", j).toString();
    }

    public static String dateTimeText(long j) {
        return DateFormat.format("yyyy-MM-dd kk:mm:ss", j).toString();
    }

    public static String dateText(long j) {
        return DateFormat.format("yyyy-MM-dd", j).toString();
    }

    public static long getTimeZoneOffsetMs() {
        return new GregorianCalendar().getTimeZone().getRawOffset();
    }

    public static String niceTimeSince(long j) {
        return niceTimeScalar(msSince(j));
    }

    public static String niceTimeTill(long j) {
        return niceTimeScalar(-msSince(j));
    }

    public static String niceTimeScalar(long j) {
        String string = xdrip.getAppContext().getString(2131756935);
        long j2 = j / 1000;
        if (j2 != 1) {
            string = xdrip.getAppContext().getString(2131756936);
        }
        if (j2 > 59) {
            string = xdrip.getAppContext().getString(2131756933);
            j2 /= 60;
            if (j2 != 1) {
                string = xdrip.getAppContext().getString(2131756934);
            }
            if (j2 > 59) {
                string = xdrip.getAppContext().getString(2131756931);
                j2 /= 60;
                if (j2 != 1) {
                    string = xdrip.getAppContext().getString(2131756932);
                }
                if (j2 > 24) {
                    string = xdrip.getAppContext().getString(2131756929);
                    j2 /= 24;
                    if (j2 != 1) {
                        string = xdrip.getAppContext().getString(2131756930);
                    }
                    if (j2 > 28) {
                        string = xdrip.getAppContext().getString(2131756937);
                        j2 /= 7;
                        if (j2 != 1) {
                            string = xdrip.getAppContext().getString(2131756938);
                        }
                    }
                }
            }
        }
        return qs(j2, 0) + " " + string;
    }

    public static String niceTimeScalar(double d, int i) {
        String string = xdrip.getAppContext().getString(2131756935);
        double d2 = d / 1000.0d;
        if (d2 != 1.0d) {
            string = xdrip.getAppContext().getString(2131756936);
        }
        if (d2 > 59.0d) {
            string = xdrip.getAppContext().getString(2131756933);
            d2 /= 60.0d;
            if (d2 != 1.0d) {
                string = xdrip.getAppContext().getString(2131756934);
            }
            if (d2 > 59.0d) {
                string = xdrip.getAppContext().getString(2131756931);
                d2 /= 60.0d;
                if (d2 != 1.0d) {
                    string = xdrip.getAppContext().getString(2131756932);
                }
                if (d2 > 24.0d) {
                    string = xdrip.getAppContext().getString(2131756929);
                    d2 /= 24.0d;
                    if (d2 != 1.0d) {
                        string = xdrip.getAppContext().getString(2131756930);
                    }
                    if (d2 > 28.0d) {
                        string = xdrip.getAppContext().getString(2131756937);
                        d2 /= 7.0d;
                        if (d2 != 1.0d) {
                            string = xdrip.getAppContext().getString(2131756938);
                        }
                    }
                }
            }
        }
        return qs(d2, i) + " " + string;
    }

    public static String niceTimeScalarNatural(long j) {
        return niceTimeScalarNatural(j, 0);
    }

    public static String niceTimeScalarNatural(long j, int i) {
        if (j > 3000000) {
            j += 10000;
        }
        if (j > 86400000 && j < 1209600000) {
            String format = new SimpleDateFormat("EEEE", Locale.getDefault()).format(new Date(tsl() + j));
            StringBuilder sb = new StringBuilder();
            sb.append(j > 604800000 ? "next " : "");
            sb.append(format);
            return sb.toString();
        }
        return niceTimeScalar(j, i);
    }

    public static String niceTimeScalarRedux(long j) {
        return niceTimeScalar(j).replaceFirst("^1 ", "");
    }

    public static String niceTimeScalarShort(long j) {
        return niceTimeScalar(j).replaceFirst("([A-z]).*$", "$1");
    }

    public static String niceTimeScalarShortWithDecimalHours(long j) {
        if (j > 3600000) {
            return niceTimeScalar(j, 1).replaceFirst("([A-z]).*$", "$1");
        }
        return niceTimeScalar(j).replaceFirst("([A-z]).*$", "$1");
    }

    public static double tolerantParseDouble(String str) throws NumberFormatException {
        return Double.parseDouble(str.replace(",", "."));
    }

    public static double tolerantParseDouble(String str, double d) {
        if (str == null) {
            return d;
        }
        try {
            return Double.parseDouble(str.replace(",", "."));
        } catch (NumberFormatException unused) {
            return d;
        }
    }

    public static int tolerantParseInt(String str, int i) {
        if (str == null) {
            return i;
        }
        try {
            return Integer.parseInt(str);
        } catch (NumberFormatException unused) {
            return i;
        }
    }

    public static long tolerantParseLong(String str, long j) {
        if (str == null) {
            return j;
        }
        try {
            return Long.parseLong(str);
        } catch (NumberFormatException unused) {
            return j;
        }
    }

    public static String getRFC822String(long j) {
        return new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US).format(new Date(j));
    }

    public static PowerManager.WakeLock getWakeLock(String str, int i) {
        PowerManager.WakeLock newWakeLock = ((PowerManager) xdrip.getAppContext().getSystemService("power")).newWakeLock(1, str);
        newWakeLock.acquire(i);
        return newWakeLock;
    }

    public static synchronized void releaseWakeLock(PowerManager.WakeLock wakeLock) {
        synchronized (JoH.class) {
            if (wakeLock == null) {
                return;
            }
            if (wakeLock.isHeld()) {
                try {
                    wakeLock.release();
                } catch (Exception e) {
                    Log.e(TAG, "Error releasing wakelock: " + e);
                }
            }
        }
    }

    public static PowerManager.WakeLock fullWakeLock(String str, long j) {
        PowerManager.WakeLock newWakeLock = ((PowerManager) xdrip.getAppContext().getSystemService("power")).newWakeLock(805306394, str);
        newWakeLock.acquire(j);
        return newWakeLock;
    }

    public static void fullDatabaseReset() {
        try {
            clearCache();
            ActiveAndroid.dispose();
            ActiveAndroid.initialize(xdrip.getAppContext());
        } catch (Exception unused) {
            Log.e(TAG, "Error restarting active android db");
        }
    }

    public static void clearCache() {
        try {
            ActiveAndroid.clearCache();
        } catch (Exception e) {
            Log.e(TAG, "Error clearing active android cache: " + e);
        }
    }

    public static boolean isLANConnected() {
        NetworkInfo activeNetworkInfo = ((ConnectivityManager) xdrip.getAppContext().getSystemService("connectivity")).getActiveNetworkInfo();
        if (!(activeNetworkInfo != null && activeNetworkInfo.isConnected())) {
            return debug_wakelocks;
        }
        if (activeNetworkInfo.getType() == 1 || activeNetworkInfo.getType() == 9 || activeNetworkInfo.getType() == 7) {
            return true;
        }
        return debug_wakelocks;
    }

    public static boolean isMobileDataOrEthernetConnected() {
        NetworkInfo activeNetworkInfo = ((ConnectivityManager) xdrip.getAppContext().getSystemService("connectivity")).getActiveNetworkInfo();
        if ((activeNetworkInfo != null && activeNetworkInfo.isConnected()) && (activeNetworkInfo.getType() == 0 || activeNetworkInfo.getType() == 9)) {
            return true;
        }
        return debug_wakelocks;
    }

    public static boolean isAnyNetworkConnected() {
        NetworkInfo activeNetworkInfo = ((ConnectivityManager) xdrip.getAppContext().getSystemService("connectivity")).getActiveNetworkInfo();
        if (activeNetworkInfo == null || !activeNetworkInfo.isConnected()) {
            return debug_wakelocks;
        }
        return true;
    }

    public static boolean isScreenOn() {
        return ((PowerManager) xdrip.getAppContext().getSystemService("power")).isInteractive();
    }

    public static boolean isOngoingCall() {
        try {
            if (((AudioManager) xdrip.getAppContext().getSystemService("audio")).getMode() == 2) {
                return true;
            }
            return debug_wakelocks;
        } catch (Exception unused) {
            return debug_wakelocks;
        }
    }

    public static String getWifiSSID() {
        WifiInfo connectionInfo;
        NetworkInfo.DetailedState detailedStateOf;
        try {
            WifiManager wifiManager = (WifiManager) xdrip.getAppContext().getApplicationContext().getSystemService("wifi");
            if (wifiManager.isWifiEnabled() && (connectionInfo = wifiManager.getConnectionInfo()) != null && ((detailedStateOf = WifiInfo.getDetailedStateOf(connectionInfo.getSupplicantState())) == NetworkInfo.DetailedState.CONNECTED || detailedStateOf == NetworkInfo.DetailedState.OBTAINING_IPADDR || detailedStateOf == NetworkInfo.DetailedState.CAPTIVE_PORTAL_CHECK)) {
                String ssid = connectionInfo.getSSID();
                if (ssid.equals("<unknown ssid>")) {
                    return null;
                }
                if (ssid.charAt(0) == '\"') {
                    ssid = ssid.substring(1);
                }
                return ssid.charAt(ssid.length() - 1) == '\"' ? ssid.substring(0, ssid.length() - 1) : ssid;
            }
        } catch (Exception e) {
            Log.e(TAG, "Got exception in getWifiSSID: " + e);
        }
        return null;
    }

    public static boolean getWifiFuzzyMatch(String str, String str2) {
        boolean z = debug_wakelocks;
        if (str == null || str2 == null || str.length() == 0 || str2.length() == 0) {
            return debug_wakelocks;
        }
        int min = Math.min(str.length(), str2.length());
        int max = Math.max(str.length(), str2.length());
        int i = 0;
        for (int i2 = 0; i2 < min; i2++) {
            if (str.charAt(i2) == str2.charAt(i2)) {
                i++;
            }
        }
        if (i == min) {
            z = true;
        }
        double d = i / max;
        int i3 = max - i;
        if (min > 2) {
            if (i3 < 3) {
                z = true;
            }
            if (d > 0.8d) {
                return true;
            }
        }
        return z;
    }

    public static boolean runOnUiThread(Runnable runnable) {
        return new Handler(xdrip.getAppContext().getMainLooper()).post(runnable);
    }

    public static boolean runOnUiThreadDelayed(Runnable runnable, long j) {
        return new Handler(xdrip.getAppContext().getMainLooper()).postDelayed(runnable, j);
    }

    public static void removeUiThreadRunnable(Runnable runnable) {
        new Handler(xdrip.getAppContext().getMainLooper()).removeCallbacks(runnable);
    }

    public static void hardReset() {
        try {
            Process.killProcess(Process.myPid());
        } catch (Exception unused) {
        }
    }

    public static void static_toast(final Context context, final String str, final int i) {
        try {
            if (runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Toast.makeText(context, str, i).show();
                        Log.i(JoH.TAG, "Displaying toast using fallback");
                    } catch (Exception e) {
                        Log.e(JoH.TAG, "Exception processing runnable toast ui thread: " + e);
                        Home.toaststatic(str);
                    }
                }
            })) {
                return;
            }
            Log.e(TAG, "Couldn't display toast via ui thread: " + str);
            Home.toaststatic(str);
        } catch (Exception e) {
            Log.e(TAG, "Couldn't display toast due to exception: " + str + " e: " + e.toString());
            Home.toaststatic(str);
        }
    }

    public static void static_toast_long(String str) {
        static_toast(xdrip.getAppContext(), str, 1);
    }

    public static void static_toast_short(String str) {
        static_toast(xdrip.getAppContext(), str, 0);
    }

    public static void static_toast_long(Context context, String str) {
        static_toast(context, str, 1);
    }

    public static void show_ok_dialog(final Activity activity, final String str, final String str2, final Runnable runnable) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(activity, 2131820551));
                    builder.setTitle(str);
                    builder.setMessage(str2);
                    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            try {
                                dialogInterface.dismiss();
                            } catch (Exception unused) {
                            }
                            Runnable runnable2 = runnable;
                            if (runnable2 != null) {
                                JoH.runOnUiThreadDelayed(runnable2, 10L);
                            }
                        }
                    });
                    builder.create().show();
                } catch (Exception e) {
                    Log.wtf(JoH.TAG, "show_dialog exception: " + e);
                    JoH.static_toast_long(str2);
                }
            }
        });
    }

    public static synchronized void playResourceAudio(int i) {
        synchronized (JoH.class) {
            playSoundUri(getResourceURI(i));
        }
    }

    public static String getResourceURI(int i) {
        return "android.resource://" + xdrip.getAppContext().getPackageName() + "/" + i;
    }

    public static synchronized void stopAndReleasePlayer(MediaPlayer mediaPlayer) {
        synchronized (JoH.class) {
            if (mediaPlayer != null) {
                try {
                    if (mediaPlayer.isPlaying()) {
                        try {
                            mediaPlayer.stop();
                        } catch (IllegalStateException e) {
                            UserError.Log.e(TAG, "Exception when stopping sound media player: " + e);
                        }
                    }
                } catch (IllegalStateException e2) {
                    UserError.Log.d(TAG, "Exception when detecting if media player playing: " + e2);
                }
                try {
                    mediaPlayer.release();
                } catch (IllegalStateException unused) {
                    UserError.Log.d(TAG, "Exception when releasing media player");
                }
            }
        }
    }

    private static void stopReleaseAndNullPlayer() {
        try {
            Semaphore semaphore = playerLock;
            semaphore.acquire();
            try {
                try {
                    stopAndReleasePlayer(player);
                    player = null;
                } catch (Throwable th) {
                    playerLock.release();
                    throw th;
                }
            } catch (Exception e) {
                UserError.Log.e(TAG, "Got exception trying to stop and release player: " + e);
                semaphore = playerLock;
            }
            semaphore.release();
        } catch (InterruptedException e2) {
            UserError.Log.e(TAG, "Got interrupted exception with player semaphore wait 3 " + e2);
        }
    }

    public static void delayedMediaPlayerRelease(final MediaPlayer mediaPlayer) {
        new Thread(new Runnable() {
            @Override
            public final void run() {
                JoH.lambda$delayedMediaPlayerRelease$1(mediaPlayer);
            }
        }).start();
    }

    public static void lambda$delayedMediaPlayerRelease$1(MediaPlayer mediaPlayer) {
        threadSleep(200L);
        mediaPlayer.release();
    }

    public static boolean setMediaDataSource(Context context, MediaPlayer mediaPlayer, Uri uri) {
        try {
            if (uri.toString().startsWith("/")) {
                UserError.Log.d(TAG, "Setting old style uri: " + uri);
                mediaPlayer.setDataSource(context, uri);
                return true;
            }
            UserError.Log.d(TAG, "Setting new style uri: " + uri);
            ParcelFileDescriptor openFileDescriptor = context.getContentResolver().openFileDescriptor(uri, "r");
            mediaPlayer.setDataSource(openFileDescriptor.getFileDescriptor());
            openFileDescriptor.close();
            return true;
        } catch (IOException | IllegalArgumentException | NullPointerException | SecurityException e) {
            UserError.Log.e(TAG, "setMediaDataSource from uri failed: uri = " + uri.toString(), e);
            return debug_wakelocks;
        }
    }

    public static boolean setMediaDataSource(Context context, MediaPlayer mediaPlayer, int i) {
        try {
            AssetFileDescriptor openRawResourceFd = context.getResources().openRawResourceFd(i);
            if (openRawResourceFd == null) {
                return debug_wakelocks;
            }
            mediaPlayer.setDataSource(openRawResourceFd.getFileDescriptor(), openRawResourceFd.getStartOffset(), openRawResourceFd.getLength());
            openRawResourceFd.close();
            return true;
        } catch (IOException | IllegalArgumentException | NullPointerException | SecurityException e) {
            UserError.Log.e(TAG, "setMediaDataSource from resource id failed:", e);
            return debug_wakelocks;
        }
    }

    public static void playSoundUri(String str) {
        try {
            Semaphore semaphore = playerLock;
            semaphore.acquire();
            try {
                try {
                    getWakeLock("joh-playsound", ErrorCode.INVALID_OWNERSHIP);
                    player = MediaPlayer.create(xdrip.getAppContext(), Uri.parse(str));
                    if (player == null) {
                        player = new MediaPlayer();
                        if (!setMediaDataSource(xdrip.getAppContext(), player, Uri.parse(str))) {
                            UserError.Log.e(TAG, "Failed to set data source for " + str + " reverting to default");
                            player = MediaPlayer.create(xdrip.getAppContext(), Uri.parse(getResourceURI(2131689968)));
                            if (player == null) {
                                UserError.Log.wtf(TAG, "Can't even create media player for default sound");
                            }
                        }
                    }
                    player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public final void onCompletion(MediaPlayer mediaPlayer) {
                            JoH.lambda$playSoundUri$2(mediaPlayer);
                        }
                    });
                    player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                        @Override
                        public final boolean onError(MediaPlayer mediaPlayer, int i, int i2) {
                            boolean lambda$playSoundUri$3;
                            lambda$playSoundUri$3 = JoH.lambda$playSoundUri$3(mediaPlayer, i, i2);
                            return lambda$playSoundUri$3;
                        }
                    });
                    player.setLooping(debug_wakelocks);
                    player.start();
                    semaphore.release();
                } catch (Throwable th) {
                    playerLock.release();
                    throw th;
                }
            } catch (Exception e) {
                Log.wtf(TAG, "Failed to play audio: " + str + " exception:" + e);
                playerLock.release();
            }
        } catch (InterruptedException e2) {
            UserError.Log.e(TAG, "Got interrupted exception with player semaphore wait 1 " + e2);
        }
    }

    public static void lambda$playSoundUri$2(MediaPlayer mediaPlayer) {
        UserError.Log.i(TAG, "playSoundUri: onCompletion called (finished playing) ");
        delayedMediaPlayerRelease(mediaPlayer);
    }

    public static boolean lambda$playSoundUri$3(MediaPlayer mediaPlayer, int i, int i2) {
        UserError.Log.e(TAG, "playSoundUri: onError called (what: " + i + ", extra: " + i2);
        return debug_wakelocks;
    }

    public static void stopSoundUri() {
        UserError.Log.d(TAG, "stopSoundUri called");
        stopReleaseAndNullPlayer();
    }

    public static boolean validateMacAddress(String str) {
        if (str != null && str.length() == 17 && str.matches("([\\da-fA-F]{1,2}(?:\\:|$)){6}")) {
            return true;
        }
        return debug_wakelocks;
    }

    public static String urlEncode(String str) {
        try {
            return URLEncoder.encode(str, "UTF-8");
        } catch (Exception unused) {
            return "encoding-exception";
        }
    }

    public static Object cloneObject(Object obj) {
        try {
            Object newInstance = obj.getClass().newInstance();
            for (Field field : obj.getClass().getDeclaredFields()) {
                if (!Modifier.isFinal(field.getModifiers())) {
                    field.setAccessible(true);
                    field.set(newInstance, field.get(obj));
                }
            }
            return newInstance;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }

    public static void stopService(Class cls) {
        xdrip.getAppContext().stopService(new Intent(xdrip.getAppContext(), (Class<?>) cls));
    }

    public static void startService(Class cls) {
        xdrip.getAppContext().startService(new Intent(xdrip.getAppContext(), (Class<?>) cls));
    }

    public static void startService(Class cls, String... strArr) {
        startService(cls, null, strArr);
    }

    public static void startService(Class cls, byte[] bArr, String... strArr) {
        Intent intent = new Intent(xdrip.getAppContext(), (Class<?>) cls);
        if (bArr != null) {
            intent.putExtra("bytes_payload", bArr);
        }
        if (strArr.length % 2 == 1) {
            throw new RuntimeException("Odd number of args for JoH.startService");
        }
        for (int i = 0; i < strArr.length; i += 2) {
            intent.putExtra(strArr[i], strArr[i + 1]);
        }
        xdrip.getAppContext().startService(intent);
    }

    public static void startActivity(Class cls) {
        xdrip.getAppContext().startActivity(getStartActivityIntent(cls));
    }

    public static Intent getStartActivityIntent(Class cls) {
        return new Intent(xdrip.getAppContext(), (Class<?>) cls).setFlags(268435456);
    }

    public static void goFullScreen(boolean z, View view) {
        if (z) {
            view.setSystemUiVisibility(5894);
        } else {
            view.setSystemUiVisibility(0);
        }
    }

    public static Bitmap screenShot(View view, String str) {
        if (view == null) {
            static_toast_long("View is null in screenshot!");
            return null;
        }
        int width = view.getWidth();
        int height = view.getHeight();
        Log.d(TAG, "Screenshot called: " + width + "," + height);
        Bitmap createBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(createBitmap);
        if (Pref.getBooleanDefaultFalse("show_statistics_print_color")) {
            Paint paint = new Paint();
            paint.setColor(-1);
            paint.setStyle(Paint.Style.FILL);
            canvas.drawRect(0.0f, 0.0f, width, height, paint);
        }
        view.destroyDrawingCache();
        view.layout(0, 0, width, height);
        view.draw(canvas);
        if (str == null) {
            return createBitmap;
        }
        Bitmap createBitmap2 = Bitmap.createBitmap(width, height + 40, Bitmap.Config.ARGB_8888);
        Canvas canvas2 = new Canvas(createBitmap2);
        Paint paint2 = new Paint();
        if (Pref.getBooleanDefaultFalse("show_statistics_print_color")) {
            paint2.setColor(-1);
            paint2.setStyle(Paint.Style.FILL);
            canvas2.drawRect(0.0f, 0.0f, width, 40, paint2);
            paint2.setColor(-16777216);
        } else {
            paint2.setColor(-7829368);
        }
        paint2.setTextSize(20.0f);
        canvas2.drawBitmap(createBitmap, 0.0f, 40, paint2);
        canvas2.drawText(str, 50.0f, (40 / 2) + 5, paint2);
        createBitmap.recycle();
        return createBitmap2;
    }

    public static Bitmap screenShot2(View view) {
        Log.d(TAG, "Screenshot2 called: " + view.getWidth() + "," + view.getHeight());
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache(true);
        return view.getDrawingCache(true);
    }

    public static Bitmap getBitmapFromView(View view, int i, int i2) {
        view.setLayoutParams(new ViewGroup.LayoutParams(i, i2));
        int makeMeasureSpec = View.MeasureSpec.makeMeasureSpec(i, 1073741824);
        int makeMeasureSpec2 = View.MeasureSpec.makeMeasureSpec(i2, 1073741824);
        Bitmap createBitmap = Bitmap.createBitmap(i, i2, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(createBitmap);
        canvas.drawColor(-1);
        view.destroyDrawingCache();
        view.measure(makeMeasureSpec, makeMeasureSpec2);
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.draw(canvas);
        return createBitmap;
    }

    public static void bitmapToFile(Bitmap bitmap, String str, String str2) {
        if (bitmap == null) {
            return;
        }
        Log.d(TAG, "bitmapToFile: " + bitmap.getWidth() + "x" + bitmap.getHeight());
        File file = new File(str);
        if (!file.exists()) {
            file.mkdirs();
        }
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(new File(str, str2));
            boolean compress = bitmap.compress(Bitmap.CompressFormat.PNG, 80, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
            Log.d(TAG, "Bitmap compress result: " + compress);
        } catch (Exception e) {
            Log.e(TAG, "Got exception writing bitmap to file: " + e);
        }
    }

    public static void shareImage(Context context, File file) {
        Uri uriForFile = FileProvider.getUriForFile(context, "com.eveningoutpost.dexdrip.provider", file);
        Intent intent = new Intent();
        intent.setAction("android.intent.action.SEND");
        intent.setType("image/*");
        intent.putExtra("android.intent.extra.SUBJECT", "");
        intent.putExtra("android.intent.extra.TEXT", "");
        intent.putExtra("android.intent.extra.STREAM", uriForFile);
        intent.setFlags(1);
        try {
            context.startActivity(Intent.createChooser(intent, "Share"));
        } catch (ActivityNotFoundException unused) {
            static_toast_long("No suitable app to show an image!");
        }
    }

    public static void cancelAlarm(Context context, PendingIntent pendingIntent) {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService("alarm");
        if (pendingIntent != null) {
            Log.d(TAG, "Cancelling alarm " + pendingIntent.getCreatorPackage());
            alarmManager.cancel(pendingIntent);
            return;
        }
        Log.d(TAG, "Cancelling alarm: serviceIntent is null");
    }

    public static long wakeUpIntent(Context context, long j, PendingIntent pendingIntent) {
        long tsl = tsl() + j;
        if (pendingIntent != null) {
            Log.d(TAG, "Scheduling wakeup intent: " + dateTimeText(tsl));
            AlarmManager alarmManager = (AlarmManager) context.getSystemService("alarm");
            try {
                alarmManager.cancel(pendingIntent);
            } catch (Exception e) {
                Log.e(TAG, "Exception cancelling alarm in wakeUpIntent: " + e);
            }
            if (buggy_samsung && Pref.getBoolean("allow_samsung_workaround", true)) {
                alarmManager.setAlarmClock(new AlarmManager.AlarmClockInfo(tsl, null), pendingIntent);
            } else {
                alarmManager.setExactAndAllowWhileIdle(0, tsl, pendingIntent);
            }
        } else {
            Log.e(TAG, "wakeUpIntent - pending intent was null!");
        }
        return tsl;
    }

    public static void scheduleNotification(Context context, String str, String str2, int i, int i2) {
        PendingIntent activity = PendingIntent.getActivity(context, i2, new Intent(context, (Class<?>) Home.class).putExtra("SHOW_NOTIFICATION", str).putExtra("notification_body", str2).putExtra("notification_id", i2), 134217728);
        Log.d(TAG, "Scheduling notification: " + str + " / " + str2);
        wakeUpIntent(context, (long) (i * 1000), activity);
    }

    public static void cancelNotification(int i) {
        try {
            ((NotificationManager) xdrip.getAppContext().getSystemService("notification")).cancel(i);
        } catch (Exception unused) {
        }
    }

    public static void showNotification(String str, String str2, PendingIntent pendingIntent, int i, boolean z, boolean z2, boolean z3) {
        showNotification(str, str2, pendingIntent, i, z, z2, null, null);
    }

    public static void showNotification(String str, String str2, PendingIntent pendingIntent, int i, boolean z, boolean z2, PendingIntent pendingIntent2, Uri uri) {
        showNotification(str, str2, pendingIntent, i, null, z, z2, pendingIntent2, uri, null);
    }

    public static void showNotification(String str, String str2, PendingIntent pendingIntent, int i, boolean z, boolean z2, PendingIntent pendingIntent2, Uri uri, String str3) {
        showNotification(str, str2, pendingIntent, i, null, z, z2, pendingIntent2, uri, str3);
    }

    public static void showNotification(String str, String str2, PendingIntent pendingIntent, int i, String str3, boolean z, boolean z2, PendingIntent pendingIntent2, Uri uri, String str4) {
        showNotification(str, str2, pendingIntent, i, str3, z, z2, pendingIntent2, uri, str4, debug_wakelocks);
    }

    public static void showNotification(String str, String str2, PendingIntent pendingIntent, int i, String str3, boolean z, boolean z2, PendingIntent pendingIntent2, Uri uri, String str4, boolean z3) {
        NotificationCompat.Builder notificationBuilder = notificationBuilder(str, str2, pendingIntent, str3);
        long[] jArr = {0, 1000, 300, 1000, 300, 1000};
        if (z2) {
            notificationBuilder.setVibrate(jArr);
        }
        if (pendingIntent2 != null) {
            notificationBuilder.setDeleteIntent(pendingIntent2);
        }
        notificationBuilder.setLights(-16711936, 300, 1000);
        if (z) {
            if (uri == null) {
                uri = RingtoneManager.getDefaultUri(2);
            }
            notificationBuilder.setSound(uri);
        }
        if (str4 != null) {
            notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(str4));
        }
        if (z3) {
            notificationBuilder.setPriority(2);
        }
        ((NotificationManager) xdrip.getAppContext().getSystemService("notification")).notify(i, XdripNotificationCompat.build(notificationBuilder));
    }

    private static NotificationCompat.Builder notificationBuilder(String str, String str2, PendingIntent pendingIntent, String str3) {
        return new NotificationCompat.Builder(xdrip.getAppContext(), str3).setSmallIcon(2131230884).setContentTitle(str).setContentText(str2).setContentIntent(pendingIntent);
    }

    public static void releaseOrientation(Activity activity) {
        activity.setRequestedOrientation(-1);
    }

    @SuppressLint({"NewApi"})
    public static void lockOrientation(Activity activity) {
        Display defaultDisplay = activity.getWindowManager().getDefaultDisplay();
        int rotation = defaultDisplay.getRotation();
        Point point = new Point();
        defaultDisplay.getSize(point);
        int i = point.y;
        int i2 = point.x;
        if (rotation == 1) {
            if (i2 > i) {
                activity.setRequestedOrientation(0);
                return;
            } else {
                activity.setRequestedOrientation(9);
                return;
            }
        }
        if (rotation == 2) {
            if (i > i2) {
                activity.setRequestedOrientation(9);
                return;
            } else {
                activity.setRequestedOrientation(8);
                return;
            }
        }
        if (rotation != 3) {
            if (i > i2) {
                activity.setRequestedOrientation(1);
                return;
            } else {
                activity.setRequestedOrientation(0);
                return;
            }
        }
        if (i2 > i) {
            activity.setRequestedOrientation(8);
        } else {
            activity.setRequestedOrientation(1);
        }
    }

    public static boolean areWeRunningOnAndroidWear() {
        if (xdrip.getAppContext().getPackageManager().hasSystemFeature("android.hardware.type.watch")) {
            return true;
        }
        return debug_wakelocks;
    }

    public static boolean isAirplaneModeEnabled(Context context) {
        if (Settings.Global.getInt(context.getContentResolver(), "airplane_mode_on", 0) != 0) {
            return true;
        }
        return debug_wakelocks;
    }

    public static byte[] convertPinToBytes(String str) {
        if (str == null) {
            return null;
        }
        try {
            byte[] bytes = str.getBytes("UTF-8");
            if (bytes.length <= 0 || bytes.length > 16) {
                return null;
            }
            return bytes;
        } catch (UnsupportedEncodingException unused) {
            Log.e(TAG, "UTF-8 not supported?!?");
            return null;
        }
    }

    public static boolean doPairingRequest(Context context, BroadcastReceiver broadcastReceiver, Intent intent, String str) {
        return doPairingRequest(context, broadcastReceiver, intent, str, null);
    }

    @TargetApi(19)
    public static boolean doPairingRequest(Context context, BroadcastReceiver broadcastReceiver, Intent intent, String str, String str2) {
        if ("android.bluetooth.device.action.PAIRING_REQUEST".equals(intent.getAction())) {
            BluetoothDevice bluetoothDevice = (BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
            if (bluetoothDevice != null) {
                int intExtra = intent.getIntExtra("android.bluetooth.device.extra.PAIRING_VARIANT", RecyclerView.UNDEFINED_DURATION);
                if (str == null || !bluetoothDevice.getAddress().equals(str)) {
                    UserError.Log.e(TAG, "Received pairing request for not our device: " + bluetoothDevice.getAddress());
                } else {
                    if (intExtra == 1 && str2 != null) {
                        return debug_wakelocks;
                    }
                    if (intExtra == 0 && str2 != null) {
                        bluetoothDevice.setPin(convertPinToBytes(str2));
                        Log.d(TAG, "Setting pairing pin to " + str2);
                        broadcastReceiver.abortBroadcast();
                    }
                    try {
                        UserError.Log.e(TAG, "Pairing type: " + intExtra);
                        if (intExtra != 0 && intExtra != 1) {
                            bluetoothDevice.setPairingConfirmation(true);
                            static_toast_short("xDrip Pairing");
                            broadcastReceiver.abortBroadcast();
                        } else {
                            Log.d(TAG, "Attempting to passthrough PIN pairing");
                        }
                    } catch (Exception e) {
                        UserError.Log.e(TAG, "Could not set pairing confirmation due to exception: " + e);
                        if (ratelimit("failed pair confirmation", 200)) {
                            if (intExtra == 3) {
                                static_toast_long("Please confirm the bluetooth pairing request");
                                return debug_wakelocks;
                            }
                            static_toast_long("Failed to pair, may need to do it via Android Settings");
                            bluetoothDevice.createBond();
                            return debug_wakelocks;
                        }
                    }
                }
            } else {
                UserError.Log.e(TAG, "Device was null in pairing receiver");
            }
        }
        return true;
    }

    public static String getLocalBluetoothName() {
        try {
            String name = BluetoothAdapter.getDefaultAdapter().getName();
            return name == null ? "" : name;
        } catch (Exception unused) {
            return "";
        }
    }

    public static boolean refreshDeviceCache(String str, BluetoothGatt bluetoothGatt) {
        try {
            Method method = bluetoothGatt.getClass().getMethod("refresh", new Class[0]);
            if (method != null) {
                return ((Boolean) method.invoke(bluetoothGatt, new Object[0])).booleanValue();
            }
        } catch (Exception e) {
            Log.e(str, "An exception occured while refreshing gatt device cache: " + e);
        }
        return debug_wakelocks;
    }

    public static boolean createSpecialBond(String str, BluetoothDevice bluetoothDevice) {
        Method method;
        try {
            Log.e(str, "Attempting special bond");
            method = bluetoothDevice.getClass().getMethod("createBond", Integer.TYPE);
        } catch (Exception e) {
            Log.e(str, "An exception occured while creating special bond: " + e);
        }
        if (method != null) {
            return ((Boolean) method.invoke(bluetoothDevice, 2)).booleanValue();
        }
        Log.e(str, "CANNOT FIND SPECIAL BOND METHOD!!");
        return debug_wakelocks;
    }

    public static boolean isBluetoothEnabled(Context context) {
        try {
            return ((BluetoothManager) context.getSystemService("bluetooth")).getAdapter().isEnabled();
        } catch (Exception e) {
            UserError.Log.d(TAG, "isBluetoothEnabled() exception: " + e);
            return debug_wakelocks;
        }
    }

    public static synchronized void setBluetoothEnabled(Context context, boolean z) {
        synchronized (JoH.class) {
            BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService("bluetooth");
            if (bluetoothManager == null) {
                UserError.Log.e(TAG, "Couldn't get bluetooth in setBluetoothEnabled");
                return;
            }
            BluetoothAdapter adapter = bluetoothManager.getAdapter();
            if (adapter == null) {
                UserError.Log.e(TAG, "Couldn't get bluetooth adapter in setBluetoothEnabled");
                return;
            }
            try {
                if (z) {
                    UserError.Log.i(TAG, "Setting bluetooth enabled");
                    adapter.enable();
                } else {
                    UserError.Log.i(TAG, "Setting bluetooth disabled");
                    adapter.disable();
                }
            } catch (Exception e) {
                UserError.Log.e(TAG, "Exception when enabling/disabling bluetooth: " + e);
            }
        }
    }

    public static void niceRestartBluetooth(Context context) {
        if (isOngoingCall() || !ratelimit("joh-restart-bluetooth", 600)) {
            return;
        }
        restartBluetooth(context);
    }

    public static synchronized void restartBluetooth(Context context) {
        synchronized (JoH.class) {
            restartBluetooth(context, 0);
        }
    }

    public static synchronized void restartBluetooth(final Context context, final int i) {
        synchronized (JoH.class) {
            new Thread() {
                @Override
                public void run() {
                    PowerManager.WakeLock wakeLock = JoH.getWakeLock("restart-bluetooth", UsbId.SILABS_CP2102);
                    Log.d(JoH.TAG, "Restarting bluetooth");
                    try {
                        int i2 = i;
                        if (i2 > 0) {
                            try {
                                Thread.sleep(i2);
                            } catch (InterruptedException unused) {
                                Log.d(JoH.TAG, "Got interrupted waiting to start resetBluetooth");
                            }
                        }
                        JoH.setBluetoothEnabled(context, JoH.debug_wakelocks);
                        try {
                            Thread.sleep(6000L);
                        } catch (InterruptedException unused2) {
                            Log.d(JoH.TAG, "Got interrupted in resetBluetooth");
                        }
                        JoH.setBluetoothEnabled(context, true);
                    } finally {
                        JoH.releaseWakeLock(wakeLock);
                    }
                }
            }.start();
        }
    }

    public static synchronized void unBond(String str) {
        synchronized (JoH.class) {
            UserError.Log.d(TAG, "unBond() start");
            if (str == null) {
                return;
            }
            try {
                Set<BluetoothDevice> bondedDevices = ((BluetoothManager) xdrip.getAppContext().getSystemService("bluetooth")).getAdapter().getBondedDevices();
                if (bondedDevices.size() > 0) {
                    for (BluetoothDevice bluetoothDevice : bondedDevices) {
                        if (bluetoothDevice.getAddress() != null && bluetoothDevice.getAddress().equals(str)) {
                            try {
                                UserError.Log.e(TAG, "removingBond: " + str);
                                bluetoothDevice.getClass().getMethod("removeBond", null).invoke(bluetoothDevice, null);
                            } catch (Exception e) {
                                UserError.Log.e(TAG, e.getMessage(), e);
                            }
                        }
                    }
                }
            } catch (Exception e2) {
                UserError.Log.e(TAG, "Exception during unbond! " + str, e2);
            }
            UserError.Log.d(TAG, "unBond() finished");
        }
    }

    public static Field getField(Class cls, String str) throws NoSuchFieldException {
        try {
            return cls.getDeclaredField(str);
        } catch (NoSuchFieldException e) {
            Class superclass = cls.getSuperclass();
            if (superclass == null) {
                throw e;
            }
            return getField(superclass, str);
        }
    }

    public static Map<String, String> bundleToMap(Bundle bundle) {
        HashMap hashMap = new HashMap();
        for (String str : bundle.keySet()) {
            Object obj = bundle.get(str);
            if (obj != null) {
                hashMap.put(str, obj.toString());
            }
        }
        return hashMap;
    }

    public static void threadSleep(long j) {
        try {
            Thread.sleep(j);
        } catch (InterruptedException unused) {
        }
    }

    public static ByteBuffer bArrayAsBuffer(byte[] bArr) {
        ByteBuffer allocate = ByteBuffer.allocate(bArr.length);
        allocate.put(bArr);
        return allocate;
    }

    public static byte[] splitBytes(byte[] bArr, int i, int i2) {
        byte[] bArr2 = new byte[i2];
        System.arraycopy(bArr, i, bArr2, 0, i2);
        return bArr2;
    }

    public static byte[] joinBytes(byte[] bArr, byte[] bArr2) {
        if (bArr == null || bArr2 == null) {
            throw new IllegalArgumentException("Input arrays cannot be null");
        }
        byte[] bArr3 = new byte[bArr.length + bArr2.length];
        System.arraycopy(bArr, 0, bArr3, 0, bArr.length);
        System.arraycopy(bArr2, 0, bArr3, bArr.length, bArr2.length);
        return bArr3;
    }

    public static long checksum(byte[] bArr) {
        if (bArr == null) {
            return 0L;
        }
        CRC32 crc32 = new CRC32();
        crc32.update(bArr);
        return crc32.getValue();
    }

    public static byte[] bchecksum(byte[] bArr) {
        long checksum = checksum(bArr);
        byte[] bArr2 = new byte[4];
        ByteBuffer.wrap(bArr2).order(ByteOrder.LITTLE_ENDIAN).putInt((int) checksum);
        return bArr2;
    }

    public static boolean checkChecksum(byte[] bArr) {
        if (bArr == null || bArr.length < 4) {
            return debug_wakelocks;
        }
        CRC32 crc32 = new CRC32();
        crc32.update(bArr, 0, bArr.length - 4);
        if (UnsignedInts.toLong(ByteBuffer.wrap(bArr).order(ByteOrder.LITTLE_ENDIAN).getInt(bArr.length - 4)) == crc32.getValue()) {
            return true;
        }
        return debug_wakelocks;
    }

    public static int parseIntWithDefault(String str, int i, int i2) {
        try {
            return Integer.parseInt(str, i);
        } catch (NumberFormatException unused) {
            Log.e(TAG, "Error parsing integer number = " + str + " radix = " + i);
            return i2;
        }
    }

    public static double roundDouble(double d, int i) {
        if (i < 0) {
            throw new IllegalArgumentException("Invalid decimal places");
        }
        return new BigDecimal(d).setScale(i, RoundingMode.HALF_UP).doubleValue();
    }

    public static float roundFloat(float f, int i) {
        if (i < 0) {
            throw new IllegalArgumentException("Invalid decimal places");
        }
        return new BigDecimal(f).setScale(i, RoundingMode.HALF_UP).floatValue();
    }

    public static boolean isServiceRunningInForeground(Class<?> cls) {
        try {
            for (ActivityManager.RunningServiceInfo runningServiceInfo : ((ActivityManager) xdrip.getAppContext().getSystemService("activity")).getRunningServices(Integer.MAX_VALUE)) {
                if (cls.getName().equals(runningServiceInfo.service.getClassName())) {
                    return runningServiceInfo.foreground;
                }
            }
        } catch (NullPointerException unused) {
        }
        return debug_wakelocks;
    }

    public static boolean emptyString(String str) {
        if (str == null || str.length() == 0) {
            return true;
        }
        return debug_wakelocks;
    }
}