WiGLE WiFi Wardriving FOSS v2.63版本的 MD5 值为:20a157bff1dec2e81d8268d404e15cb5

以下内容为反编译后的 MainActivity.java 源代码,内容仅作参考


package net.wigle.wigleandroid;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.location.GnssStatus;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.speech.tts.TextToSpeech;
import android.telephony.TelephonyManager;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.google.android.material.navigation.NavigationView;
import com.google.gson.Gson;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.lang.Thread;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.wigle.wigleandroid.WigleService;
import net.wigle.wigleandroid.background.ObservationUploader;
import net.wigle.wigleandroid.db.DBException;
import net.wigle.wigleandroid.db.DatabaseHelper;
import net.wigle.wigleandroid.db.MxcDatabaseHelper;
import net.wigle.wigleandroid.listener.BatteryLevelReceiver;
import net.wigle.wigleandroid.listener.BluetoothReceiver;
import net.wigle.wigleandroid.listener.GPSListener;
import net.wigle.wigleandroid.listener.PhoneState;
import net.wigle.wigleandroid.listener.PrefCheckboxListener;
import net.wigle.wigleandroid.listener.WifiReceiver;
import net.wigle.wigleandroid.model.ConcurrentLinkedHashMap;
import net.wigle.wigleandroid.model.Network;
import net.wigle.wigleandroid.ui.SetNetworkListAdapter;
import net.wigle.wigleandroid.ui.ThemeUtil;
import net.wigle.wigleandroid.ui.WiGLEToast;
import net.wigle.wigleandroid.util.FileUtility;
import net.wigle.wigleandroid.util.InstallUtility;
import net.wigle.wigleandroid.util.InsufficientSpaceException;
import org.apache.commons.io.IOUtils;
public final class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
    public static final String ACTION_END = "net.wigle.wigleandroid.END";
    public static final String ACTION_PAUSE = "net.wigle.wigleandroid.PAUSE";
    public static final String ACTION_SCAN = "net.wigle.wigleandroid.SCAN";
    private static final int ACTION_TTS_CODE = 3;
    public static final String ACTION_UPLOAD = "net.wigle.wigleandroid.UPLOAD";
    private static final int ACTION_WIFI_CODE = 2;
    public static final String CSV_TRANSID_URL_STEM = "https://api.wigle.net/api/v2/file/csv/";
    public static final boolean DEBUG_BLUETOOTH_DATA = false;
    public static final boolean DEBUG_CELL_DATA = false;
    public static final long DEFAULT_BATTERY_KILL_PERCENT = 2;
    public static final long DEFAULT_RESET_WIFI_PERIOD = 90000;
    public static final long DEFAULT_SPEECH_PERIOD = 60;
    private static final long DESTROY_FINISH_MILLIS = 3000;
    public static final String ENCODING = "ISO-8859-1";
    public static final String ERROR_REPORT_DIALOG = "doDialog";
    static final String ERROR_REPORT_DO_EMAIL = "doEmail";
    public static final String FILE_POST_URL = "https://api.wigle.net/api/v2/file/upload";
    private static final long FINISH_TIME_MILLIS = 10;
    public static final String FRAGMENT_TAG_PREFIX = "VisibleFragment-";
    public static final String KML_TRANSID_URL_STEM = "https://api.wigle.net/api/v2/file/kml/";
    public static final String LIST_FRAGMENT_TAG = "ListFragmentTag";
    public static final long LOCATION_UPDATE_INTERVAL = 1000;
    private static final String LOG_TAG = "wigle";
    public static final String NEWS_URL = "https://api.wigle.net/api/v2/news/latest";
    public static final String OBSERVED_URL = "https://api.wigle.net/api/v2/network/mine";
    public static final long OG_BT_SCAN_DEFAULT = 5000;
    public static final long OG_BT_SCAN_FAST_DEFAULT = 5000;
    public static final long OG_BT_SCAN_STILL_DEFAULT = 5000;
    static final Locale ORIG_LOCALE = Locale.getDefault();
    private static final int PERMISSIONS_REQUEST = 1;
    public static final String RANK_STATS_URL = "https://api.wigle.net/api/v2/stats/standings";
    public static final String REG_URL = "https://wigle.net/register";
    public static final long SCAN_DEFAULT = 2000;
    public static final long SCAN_FAST_DEFAULT = 1000;
    public static final long SCAN_P_DEFAULT = 30000;
    public static final long SCAN_STILL_DEFAULT = 3000;
    public static final String SEARCH_CELL_URL = "https://api.wigle.net/api/v2/cell/search";
    public static final String SEARCH_WIFI_URL = "https://api.wigle.net/api/v2/network/search";
    public static final String SITE_STATS_URL = "https://api.wigle.net/api/v2/stats/site";
    private static final String STATE_FRAGMENT_TAG = "StateFragmentTag";
    public static final String TOKEN_URL = "https://api.wigle.net/api/v2/activate";
    public static final String UPLOADS_STATS_URL = "https://api.wigle.net/api/v2/file/transactions";
    public static final String USER_STATS_URL = "https://api.wigle.net/api/v2/stats/user";
    private static MainActivity mainActivity;
    private BatteryLevelReceiver batteryLevelReceiver;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    private State state;
    private GnssStatus.Callback gnssStatusCallback = null;
    private boolean playServiceShown = false;

    public void endRouteLogging() {
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }

    public static class State {
        BluetoothReceiver bluetoothReceiver;
        Matcher bssidDisplayExclusions;
        Matcher bssidLogExclusions;
        public DatabaseHelper dbHelper;
        AtomicBoolean finishing;
        GPSListener gpsListener;
        boolean inEmulator;
        SetNetworkListAdapter listAdapter;
        public MxcDatabaseHelper mxcDbHelper;
        NumberFormat numberFormat0;
        NumberFormat numberFormat1;
        NumberFormat numberFormat8;
        ObservationUploader observationUploader;
        PhoneState phoneState;
        String previousStatus;
        ServiceConnection serviceConnection;
        MediaPlayer soundNewPop;
        MediaPlayer soundPop;
        AtomicBoolean transferring;
        TextToSpeech tts;
        int uiMode;
        AtomicBoolean uiRestart;
        private PowerManager.WakeLock wakeLock;
        WifiManager.WifiLock wifiLock;
        WifiReceiver wifiReceiver;
        WigleService wigleService;
        boolean ttsChecked = false;
        int currentTab = R.id.nav_list;
        int previousTab = 0;
        private boolean screenLocked = false;
        private int logPointer = 0;
        private final String[] logs = new String[25];
        AtomicBoolean ttsNag = new AtomicBoolean(true);

        static int access$508(State state) {
            int i = state.logPointer;
            state.logPointer = i + 1;
            return i;
        }
    }

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        info("MAIN onCreate. state:  " + this.state);
        workAroundGoogleMapsBug();
        SharedPreferences sharedPreferences = getSharedPreferences(ListFragment.SHARED_PREFS, 0);
        ThemeUtil.setTheme(sharedPreferences);
        ThemeUtil.setNavTheme(getWindow(), this, sharedPreferences);
        mainActivity = this;
        setLocale(this);
        setContentView(R.layout.main);
        setupPermissions();
        setupMenuDrawer();
        Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        if (!(defaultUncaughtExceptionHandler instanceof WigleUncaughtExceptionHandler)) {
            Thread.setDefaultUncaughtExceptionHandler(new WigleUncaughtExceptionHandler(getApplicationContext(), defaultUncaughtExceptionHandler));
        }
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        supportFragmentManager.executePendingTransactions();
        StateFragment stateFragment = (StateFragment) supportFragmentManager.findFragmentByTag(STATE_FRAGMENT_TAG);
        pieScanningSettings(sharedPreferences);
        if (stateFragment != null && stateFragment.getState() != null) {
            info("MAIN: using retained stateFragment state");
            State state = stateFragment.getState();
            this.state = state;
            if (state.gpsListener != null) {
                this.state.gpsListener.setMainActivity(this);
            }
            if (this.state.wifiReceiver != null) {
                this.state.wifiReceiver.setMainActivity(this);
            }
            if (this.state.observationUploader != null) {
                this.state.observationUploader.setContext(this);
            }
        } else {
            info("MAIN: creating new state");
            State state2 = new State();
            this.state = state2;
            state2.finishing = new AtomicBoolean(false);
            this.state.transferring = new AtomicBoolean(false);
            this.state.uiRestart = new AtomicBoolean(false);
            StateFragment stateFragment2 = new StateFragment();
            stateFragment2.setState(this.state);
            supportFragmentManager.beginTransaction().add(stateFragment2, STATE_FRAGMENT_TAG).commit();
            float f = sharedPreferences.getFloat(ListFragment.PREF_DISTANCE_RUN, 0.0f);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putFloat(ListFragment.PREF_DISTANCE_RUN, 0.0f);
            edit.putLong(ListFragment.PREF_STARTTIME_RUN, System.currentTimeMillis());
            edit.putLong(ListFragment.PREF_STARTTIME_CURRENT_SCAN, System.currentTimeMillis());
            edit.putLong(ListFragment.PREF_CUMULATIVE_SCANTIME_RUN, 0L);
            edit.putFloat(ListFragment.PREF_DISTANCE_PREV_RUN, f);
            edit.apply();
        }
        PowerManager powerManager = (PowerManager) getSystemService("power");
        if (this.state.wakeLock == null) {
            this.state.wakeLock = powerManager.newWakeLock(26, "wiglewifiwardriving:DoNotDimScreen");
            if (this.state.wakeLock.isHeld()) {
                this.state.wakeLock.release();
            }
        }
        String string = Settings.Secure.getString(getContentResolver(), "android_id");
        this.state.inEmulator = string == null;
        State state3 = this.state;
        state3.inEmulator = state3.inEmulator || "sdk".equals(Build.PRODUCT);
        State state4 = this.state;
        state4.inEmulator = state4.inEmulator || "google_sdk".equals(Build.PRODUCT);
        this.state.uiMode = getResources().getConfiguration().uiMode;
        info("id: '" + string + "' inEmulator: " + this.state.inEmulator + " product: " + Build.PRODUCT);
        info("android release: '" + Build.VERSION.RELEASE);
        if (this.state.numberFormat0 == null) {
            this.state.numberFormat0 = NumberFormat.getNumberInstance(Locale.US);
            if (this.state.numberFormat0 instanceof DecimalFormat) {
                this.state.numberFormat0.setMaximumFractionDigits(0);
            }
        }
        if (this.state.numberFormat1 == null) {
            this.state.numberFormat1 = NumberFormat.getNumberInstance(Locale.US);
            if (this.state.numberFormat1 instanceof DecimalFormat) {
                this.state.numberFormat1.setMaximumFractionDigits(1);
            }
        }
        if (this.state.numberFormat8 == null) {
            this.state.numberFormat8 = NumberFormat.getNumberInstance(Locale.US);
            if (this.state.numberFormat8 instanceof DecimalFormat) {
                this.state.numberFormat8.setMaximumFractionDigits(8);
                this.state.numberFormat8.setMinimumFractionDigits(8);
            }
        }
        info("setupService");
        setupService();
        info("checkStorage");
        checkStorage();
        info("setupDatabase");
        setupDatabase();
        info("setupBattery");
        setupBattery();
        info("setupSound");
        setupSound();
        info("setupActivationDialog");
        setupActivationDialog();
        info("setupBluetooth");
        setupBluetooth();
        info("setupWifi");
        setupWifi();
        info("setupLocation");
        setupLocation();
        info("setup tabs");
        if (bundle == null) {
            setupFragments();
        }
        setupFilters(sharedPreferences);
        if (InstallUtility.isFirstInstall(this)) {
            SharedPreferences.Editor edit2 = PreferenceManager.getDefaultSharedPreferences(this).edit();
            edit2.remove(ListFragment.PREF_MXC_REINSTALL_ATTEMPTED);
            edit2.apply();
        }
        try {
            this.state.mxcDbHelper.implantMxcDatabase();
        } catch (IOException e) {
            error("unable to implant mcc/mnc db", e);
        } catch (InsufficientSpaceException unused) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(R.string.no_mxc_space_message).setTitle(R.string.no_internal_space_title).setCancelable(true).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                }
            });
            AlertDialog create = builder.create();
            if (!isFinishing()) {
                create.show();
            }
        }
        checkInitKeystore();
        selectFragment(this.state.currentTab);
        info("onCreate setup complete");
    }

    private void pieScanningSettings(SharedPreferences sharedPreferences) {
        if (Build.VERSION.SDK_INT < 28) {
            return;
        }
        List<String> asList = Arrays.asList(ListFragment.PREF_SCAN_PERIOD_STILL, ListFragment.PREF_SCAN_PERIOD, ListFragment.PREF_SCAN_PERIOD_FAST);
        if (Build.VERSION.SDK_INT == 28) {
            for (String str : asList) {
                pieScanSet(sharedPreferences, str);
            }
        } else if (Build.VERSION.SDK_INT == 29) {
            Iterator it = asList.iterator();
            while (it.hasNext()) {
                if (sharedPreferences.getLong((String) it.next(), -1L) != SCAN_P_DEFAULT) {
                    return;
                }
            }
            for (String str2 : asList) {
                qScanSet(sharedPreferences, str2);
            }
        }
    }

    private void workAroundGoogleMapsBug() {
        try {
            SharedPreferences sharedPreferences = getSharedPreferences("google_bug_154855417", 0);
            if (!sharedPreferences.contains("fixed")) {
                info("working around google maps bug 154855417");
                new File(getFilesDir(), "ZoomTables.data").delete();
                sharedPreferences.edit().putBoolean("fixed", true).apply();
            } else {
                info("already worked around google maps bug 154855417");
            }
        } catch (Exception e) {
            warn("Exception in workAroundGoogleMapsBug: " + e);
        }
    }

    private void pieScanSet(SharedPreferences sharedPreferences, String str) {
        if (-1 == sharedPreferences.getLong(str, -1L)) {
            info("Setting 30 second scan for " + str + " due to broken Android Pie");
            sharedPreferences.edit().putLong(str, SCAN_P_DEFAULT).commit();
        }
    }

    private void qScanSet(SharedPreferences sharedPreferences, String str) {
        if (SCAN_P_DEFAULT == sharedPreferences.getLong(str, -1L)) {
            info("Removing 30 second scan for " + str + " due to less broken Android Q");
            sharedPreferences.edit().remove(str).commit();
        }
    }

    private void checkInitKeystore() {
        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(ListFragment.SHARED_PREFS, 0);
        if (TokenAccess.checkMigrateKeystoreVersion(sharedPreferences, this)) {
            if (sharedPreferences.getString(ListFragment.PREF_PASSWORD, "").isEmpty()) {
                return;
            }
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.remove(ListFragment.PREF_PASSWORD);
            edit.apply();
            return;
        }
        info("Not able to upgrade key storage.");
    }

    private void setupPermissions() {
        if (Build.VERSION.SDK_INT >= 23) {
            ArrayList arrayList = new ArrayList();
            ArrayList arrayList2 = new ArrayList();
            if (!addPermission(arrayList2, "android.permission.ACCESS_FINE_LOCATION")) {
                arrayList.add(mainActivity.getString(R.string.gps_permission));
            }
            if (!addPermission(arrayList2, "android.permission.ACCESS_COARSE_LOCATION")) {
                arrayList.add(mainActivity.getString(R.string.cell_permission));
            }
            addPermission(arrayList2, "android.permission.WRITE_EXTERNAL_STORAGE");
            addPermission(arrayList2, "android.permission.BLUETOOTH");
            if (arrayList2.isEmpty()) {
                return;
            }
            info("no permission for " + arrayList);
            requestPermissions((String[]) arrayList2.toArray(new String[arrayList2.size()]), 1);
        }
    }

    private boolean addPermission(List<String> list, String str) {
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(str) != 0) {
                list.add(str);
                return shouldShowRequestPermissionRationale(str);
            }
            return true;
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int i, String[] strArr, int[] iArr) {
        if (i == 1) {
            info("location grant response permissions: " + Arrays.toString(strArr) + " grantResults: " + Arrays.toString(iArr));
            boolean z = false;
            for (int i2 = 0; i2 < strArr.length; i2++) {
                if ("android.permission.WRITE_EXTERNAL_STORAGE".equals(strArr[i2]) && iArr[i2] == 0) {
                    z = true;
                }
            }
            if (z) {
                info("Restarting to pick up storage permission");
                finishSoon(FINISH_TIME_MILLIS, true);
                return;
            }
            return;
        }
        warn("Unhandled onRequestPermissionsResult code: " + i);
    }

    private void setupMenuDrawer() {
        this.mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, this.mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
            @Override
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
            }

            @Override
            public void onDrawerOpened(View view) {
                super.onDrawerOpened(view);
                ActionBar supportActionBar = MainActivity.this.getSupportActionBar();
                if (supportActionBar != null) {
                    supportActionBar.setTitle("Menu");
                }
                InputMethodManager inputMethodManager = (InputMethodManager) MainActivity.this.getSystemService("input_method");
                if (inputMethodManager == null || MainActivity.this.getCurrentFocus() == null) {
                    return;
                }
                inputMethodManager.hideSoftInputFromWindow(MainActivity.this.getCurrentFocus().getWindowToken(), 0);
                View currentFocus = MainActivity.this.getCurrentFocus();
                if (currentFocus != null) {
                    currentFocus.clearFocus();
                }
            }
        };
        this.mDrawerToggle = actionBarDrawerToggle;
        this.mDrawerLayout.setDrawerListener(actionBarDrawerToggle);
        final NavigationView navigationView = (NavigationView) findViewById(R.id.left_drawer);
        navigationView.getMenu().setGroupVisible(R.id.stats_group, false);
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                menuItem.setCheckable(true);
                if (menuItem.getItemId() == R.id.nav_stats) {
                    menuItem.setChecked(!menuItem.isChecked());
                } else {
                    menuItem.setChecked(true);
                    if (MainActivity.this.state.previousTab != menuItem.getItemId() && MainActivity.this.state.previousTab != 0) {
                        navigationView.getMenu().findItem(MainActivity.this.state.previousTab).setChecked(false);
                    }
                }
                MainActivity.this.state.previousTab = menuItem.getItemId();
                if (R.id.nav_stats == menuItem.getItemId()) {
                    MainActivity.info("Nav stats clicked");
                    MainActivity.this.showSubmenu(navigationView.getMenu(), R.id.stats_group, menuItem.isChecked());
                } else {
                    if (R.id.nav_site_stats != menuItem.getItemId() && R.id.nav_user_stats != menuItem.getItemId() && R.id.nav_rank != menuItem.getItemId()) {
                        MainActivity.this.showSubmenu(navigationView.getMenu(), R.id.stats_group, false);
                    }
                    MainActivity.this.mDrawerLayout.closeDrawers();
                    MainActivity.this.selectFragment(menuItem.getItemId());
                }
                return true;
            }
        });
        ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            supportActionBar.setDisplayHomeAsUpEnabled(true);
            supportActionBar.setHomeButtonEnabled(true);
        }
        MenuItem findItem = navigationView.getMenu().findItem(R.id.nav_user_stats);
        SpannableString spannableString = new SpannableString("    " + findItem.getTitle().toString());
        spannableString.setSpan(new ForegroundColorSpan(-529041545), 0, spannableString.length(), 0);
        findItem.setTitle(spannableString);
        MenuItem findItem2 = navigationView.getMenu().findItem(R.id.nav_site_stats);
        SpannableString spannableString2 = new SpannableString("    " + findItem2.getTitle().toString());
        spannableString2.setSpan(new ForegroundColorSpan(-529041545), 0, spannableString2.length(), 0);
        findItem2.setTitle(spannableString2);
        MenuItem findItem3 = navigationView.getMenu().findItem(R.id.nav_rank);
        SpannableString spannableString3 = new SpannableString("    " + findItem3.getTitle().toString());
        spannableString3.setSpan(new ForegroundColorSpan(-529041545), 0, spannableString3.length(), 0);
        findItem3.setTitle(spannableString3);
        navigationView.getMenu().getItem(0).setCheckable(true);
        navigationView.getMenu().getItem(0).setChecked(true);
    }

    public void selectFragment(int i) {
        if (i == R.id.nav_exit) {
            finishSoon();
            return;
        }
        HashMap hashMap = new HashMap();
        hashMap.put(Integer.valueOf((int) R.id.nav_list), getString(R.string.mapping_app_name));
        hashMap.put(Integer.valueOf((int) R.id.nav_dash), getString(R.string.dashboard_app_name));
        hashMap.put(Integer.valueOf((int) R.id.nav_data), getString(R.string.data_activity_name));
        hashMap.put(Integer.valueOf((int) R.id.nav_search), getString(R.string.tab_search));
        hashMap.put(Integer.valueOf((int) R.id.nav_news), getString(R.string.news_app_name));
        hashMap.put(Integer.valueOf((int) R.id.nav_rank), getString(R.string.rank_stats_app_name));
        hashMap.put(Integer.valueOf((int) R.id.nav_stats), getString(R.string.tab_stats));
        hashMap.put(Integer.valueOf((int) R.id.nav_uploads), getString(R.string.uploads_app_name));
        hashMap.put(Integer.valueOf((int) R.id.nav_settings), getString(R.string.settings_app_name));
        hashMap.put(Integer.valueOf((int) R.id.nav_exit), getString(R.string.menu_exit));
        try {
            FragmentManager supportFragmentManager = getSupportFragmentManager();
            Fragment fragment = (Fragment) classForFragmentNavId(i).newInstance();
            fragment.setArguments(new Bundle());
            if (fragment == null) {
                error("null fragment for: " + String.format("0x%08X", Integer.valueOf(i)) + " (" + getResources().getResourceName(i) + ")");
            }
            try {
                supportFragmentManager.beginTransaction().replace(R.id.tabcontent, fragment, FRAGMENT_TAG_PREFIX + i).commit();
            } catch (IllegalStateException | NullPointerException e) {
                error("exception in fragment switch: " + e, e);
            }
            this.state.currentTab = i;
            setTitle((CharSequence) hashMap.get(Integer.valueOf(i)));
        } catch (IllegalAccessException e2) {
            error("Unable to get fragment for id: " + i, e2);
        } catch (InstantiationException e3) {
            error("Unable to make fragment for id: " + i, e3);
        }
    }

    public void showSubmenu(Menu menu, int i, boolean z) {
        menu.setGroupVisible(i, z);
    }

    @Override
    public void setTitle(CharSequence charSequence) {
        ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            supportActionBar.setTitle(charSequence);
        }
    }

    private void setupFragments() {
        FragmentTransaction beginTransaction = getSupportFragmentManager().beginTransaction();
        info("Creating ListFragment");
        ListFragment listFragment = new ListFragment();
        listFragment.setArguments(new Bundle());
        beginTransaction.add(R.id.tabcontent, listFragment, "VisibleFragment-2131231107");
        beginTransaction.commit();
    }

    private static Class classForFragmentNavId(int i) {
        switch (i) {
            case R.id.nav_dash:
                return DashboardFragment.class;
            case R.id.nav_data:
                return DataFragment.class;
            case R.id.nav_exit:
            case R.id.nav_stats:
            default:
                return ListFragment.class;
            case R.id.nav_list:
                return ListFragment.class;
            case R.id.nav_map:
                return MappingFragment.class;
            case R.id.nav_news:
                return NewsFragment.class;
            case R.id.nav_rank:
                return RankStatsFragment.class;
            case R.id.nav_search:
                return SearchFragment.class;
            case R.id.nav_settings:
                return SettingsFragment.class;
            case R.id.nav_site_stats:
                return SiteStatsFragment.class;
            case R.id.nav_uploads:
                return UploadsFragment.class;
            case R.id.nav_user_stats:
                return UserStatsFragment.class;
        }
    }

    @Override
    public boolean onMenuOpened(int i, Menu menu) {
        if (i == 8 && menu != null && menu.getClass().getSimpleName().equals("MenuBuilder")) {
            try {
                Method declaredMethod = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                declaredMethod.setAccessible(true);
                declaredMethod.invoke(menu, true);
            } catch (NoSuchMethodException e) {
                error("onMenuOpened no such method: " + e, e);
            } catch (Exception e2) {
                error("onMenuOpened ex: " + e2, e2);
            }
        }
        return super.onMenuOpened(i, menu);
    }

    public static MainActivity getMainActivity() {
        return mainActivity;
    }

    public static void setLockScreen(Fragment fragment, boolean z) {
        MainActivity mainActivity2 = getMainActivity(fragment);
        if (mainActivity2 != null) {
            mainActivity2.setLockScreen(z);
        }
    }

    public static boolean isHighDefinition() {
        if (Build.VERSION.SDK_INT >= 17) {
            DisplayMetrics displayMetrics = new DisplayMetrics();
            getMainActivity().getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);
            return displayMetrics.densityDpi >= 240;
        }
        return false;
    }

    public static boolean isScreenLocked(Fragment fragment) {
        MainActivity mainActivity2 = getMainActivity(fragment);
        return mainActivity2 != null && mainActivity2.getState().screenLocked;
    }

    private void setLockScreen(boolean z) {
        this.state.screenLocked = z;
        if (z) {
            if (this.state.wakeLock.isHeld()) {
                return;
            }
            info("acquire wake lock");
            this.state.wakeLock.acquire();
        } else if (this.state.wakeLock.isHeld()) {
            info("release wake lock");
            this.state.wakeLock.release();
        }
    }

    public static class ConfirmationDialog extends DialogFragment {
        public static ConfirmationDialog newInstance(String str, int i, int i2) {
            ConfirmationDialog confirmationDialog = new ConfirmationDialog();
            Bundle bundle = new Bundle();
            bundle.putString("message", str);
            bundle.putInt("tabPos", i);
            bundle.putInt("dialogId", i2);
            confirmationDialog.setArguments(bundle);
            return confirmationDialog;
        }

        public static ConfirmationDialog newInstance(String str, String str2, String str3, String str4, String str5, int i, int i2) {
            ConfirmationDialog confirmationDialog = new ConfirmationDialog();
            Bundle bundle = new Bundle();
            bundle.putString("message", str);
            bundle.putInt("tabPos", i);
            bundle.putInt("dialogId", i2);
            bundle.putString("checkboxLabel", str2);
            bundle.putString("persistPref", str3);
            bundle.putString("persistPrefAgreeValue", str4);
            bundle.putString("persistPrefDisagreeValue", str5);
            confirmationDialog.setArguments(bundle);
            return confirmationDialog;
        }

        @Override
        public Dialog onCreateDialog(Bundle bundle) {
            FragmentActivity activity = getActivity();
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setCancelable(true);
            builder.setTitle("Confirmation");
            String string = getArguments().containsKey("checkboxLabel") ? getArguments().getString("checkboxLabel") : null;
            if (string != null) {
                View inflate = View.inflate(activity, R.layout.checkbox, null);
                ((CheckBox) inflate.findViewById(R.id.checkbox)).setText(string);
                builder.setView(inflate);
            }
            final String string2 = getArguments().containsKey("persistPref") ? getArguments().getString("persistPref") : null;
            final String string3 = getArguments().containsKey("persistPrefAgreeValue") ? getArguments().getString("persistPrefAgreeValue") : null;
            final String string4 = getArguments().containsKey("persistPrefDisagreeValue") ? getArguments().getString("persistPrefDisagreeValue") : null;
            builder.setMessage(getArguments().getString("message"));
            final int i = getArguments().getInt("tabPos");
            final int i2 = getArguments().getInt("dialogId");
            final SharedPreferences sharedPreferences = activity.getSharedPreferences(ListFragment.SHARED_PREFS, 0);
            AlertDialog create = builder.create();
            final String str = string2;
            create.setButton(-1, activity.getString(R.string.ok), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i3) {
                    try {
                        if (str != null && ((CheckBox) ((AlertDialog) dialogInterface).findViewById(R.id.checkbox)).isChecked()) {
                            SharedPreferences.Editor edit = sharedPreferences.edit();
                            edit.putString(str, string3);
                            edit.apply();
                        }
                        dialogInterface.dismiss();
                        FragmentActivity activity2 = ConfirmationDialog.this.getActivity();
                        if (activity2 == null) {
                            MainActivity.info("activity is null in dialog. tabPos: " + i + " dialogId: " + i2);
                        } else if (activity2 instanceof MainActivity) {
                            if (((MainActivity) activity2).getState() != null) {
                                String resourceName = ConfirmationDialog.this.getResources().getResourceName(i);
                                Fragment findFragmentByTag = ((MainActivity) activity2).getSupportFragmentManager().findFragmentByTag(MainActivity.FRAGMENT_TAG_PREFIX + i);
                                if (findFragmentByTag == null) {
                                    MainActivity.error("null fragment for: " + String.format("0x%08X", Integer.valueOf(i)) + " (" + resourceName + ")");
                                } else {
                                    ((DialogListener) findFragmentByTag).handleDialog(i2);
                                }
                            }
                        } else {
                            ((DialogListener) activity2).handleDialog(i2);
                        }
                    } catch (Exception e) {
                        MainActivity.info("exception handling fragment alert dialog: " + e, e);
                    }
                }
            });
            create.setButton(-2, activity.getString(R.string.cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i3) {
                    try {
                        if (string2 != null && ((CheckBox) ((AlertDialog) dialogInterface).findViewById(R.id.checkbox)).isChecked()) {
                            SharedPreferences.Editor edit = sharedPreferences.edit();
                            edit.putString(string2, string4);
                            edit.apply();
                        }
                        dialogInterface.dismiss();
                    } catch (Exception e) {
                        MainActivity.info("exception dismissing fragment alert dialog: " + e, e);
                    }
                }
            });
            return create;
        }
    }

    public static void createConfirmation(FragmentActivity fragmentActivity, String str, int i, int i2) {
        try {
            FragmentManager supportFragmentManager = fragmentActivity.getSupportFragmentManager();
            ConfirmationDialog newInstance = ConfirmationDialog.newInstance(str, i, i2);
            String str2 = i + "-" + i2 + "-" + fragmentActivity.getClass().getSimpleName();
            info("tag: " + str2 + " fm: " + supportFragmentManager);
            newInstance.show(supportFragmentManager, str2);
        } catch (WindowManager.BadTokenException e) {
            info("exception showing dialog, view probably changed: " + e, e);
        } catch (IllegalStateException e2) {
            error("Exception trying to show dialog: " + e2, e2);
        }
    }

    public static void createCheckboxConfirmation(FragmentActivity fragmentActivity, String str, String str2, String str3, String str4, String str5, int i, int i2) {
        try {
            FragmentManager supportFragmentManager = fragmentActivity.getSupportFragmentManager();
            ConfirmationDialog newInstance = ConfirmationDialog.newInstance(str, str2, str3, str4, str5, i, i2);
            String str6 = i + "-" + i2 + "-" + fragmentActivity.getClass().getSimpleName();
            info("tag: " + str6 + " fm: " + supportFragmentManager);
            newInstance.show(supportFragmentManager, str6);
        } catch (WindowManager.BadTokenException e) {
            info("exception showing dialog, view probably changed: " + e, e);
        } catch (IllegalStateException e2) {
            error("Exception trying to show dialog: " + e2, e2);
        }
    }

    private void setupDatabase() {
        if (this.state.dbHelper == null) {
            this.state.dbHelper = new DatabaseHelper(getApplicationContext());
            this.state.dbHelper.start();
            ListFragment.lameStatic.dbHelper = this.state.dbHelper;
        }
        if (this.state.mxcDbHelper == null) {
            this.state.mxcDbHelper = new MxcDatabaseHelper(getApplicationContext());
        }
    }

    public static CheckBox prefSetCheckBox(Context context, View view, int i, String str, boolean z) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(ListFragment.SHARED_PREFS, 0);
        CheckBox checkBox = (CheckBox) view.findViewById(i);
        checkBox.setChecked(sharedPreferences.getBoolean(str, z));
        return checkBox;
    }

    private static CheckBox prefSetCheckBox(SharedPreferences sharedPreferences, View view, int i, String str, boolean z) {
        CheckBox checkBox = (CheckBox) view.findViewById(i);
        if (checkBox == null) {
            error("No checkbox for id: " + i);
        } else {
            checkBox.setChecked(sharedPreferences.getBoolean(str, z));
        }
        return checkBox;
    }

    public static CheckBox prefBackedCheckBox(Activity activity, View view, int i, String str, boolean z) {
        return prefBackedCheckBox(activity, view, i, str, z, null);
    }

    public static CheckBox prefBackedCheckBox(Activity activity, View view, int i, final String str, boolean z, final PrefCheckboxListener prefCheckboxListener) {
        SharedPreferences sharedPreferences = activity.getSharedPreferences(ListFragment.SHARED_PREFS, 0);
        final SharedPreferences.Editor edit = sharedPreferences.edit();
        CheckBox prefSetCheckBox = prefSetCheckBox(sharedPreferences, view, i, str, z);
        prefSetCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean z2) {
                edit.putBoolean(str, z2);
                edit.apply();
                PrefCheckboxListener prefCheckboxListener2 = prefCheckboxListener;
                if (prefCheckboxListener2 != null) {
                    prefCheckboxListener2.preferenceSet(z2);
                }
            }
        });
        return prefSetCheckBox;
    }

    public static State getStaticState() {
        MainActivity mainActivity2 = getMainActivity();
        if (mainActivity2 == null) {
            return null;
        }
        return mainActivity2.getState();
    }

    public State getState() {
        return this.state;
    }

    public static MainActivity getMainActivity(Fragment fragment) {
        FragmentActivity activity = fragment.getActivity();
        if (activity instanceof MainActivity) {
            return (MainActivity) activity;
        }
        info("not main activity: " + activity);
        return null;
    }

    @Override
    public void onDestroy() {
        info("MAIN: destroy.");
        super.onDestroy();
        if (!this.state.uiRestart.get()) {
            try {
                info("unregister batteryLevelReceiver");
                unregisterReceiver(this.batteryLevelReceiver);
            } catch (IllegalArgumentException e) {
                info("batteryLevelReceiver not registered: " + e);
            }
            try {
                info("unregister wifiReceiver");
                unregisterReceiver(this.state.wifiReceiver);
            } catch (IllegalArgumentException e2) {
                info("wifiReceiver not registered: " + e2);
            }
            if (this.state.tts != null) {
                this.state.tts.shutdown();
            }
            BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
            if (defaultAdapter != null && defaultAdapter.isDiscovering()) {
                defaultAdapter.cancelDiscovery();
            }
            try {
                info("unregister bluetoothReceiver");
                unregisterReceiver(this.state.bluetoothReceiver);
            } catch (IllegalArgumentException e3) {
                info("bluetoothReceiver not registered: " + e3);
            }
            if (this.state.bluetoothReceiver != null) {
                this.state.bluetoothReceiver.stopScanning();
            }
            finishSoon(3000L, false);
            return;
        }
        this.state.uiRestart.set(false);
    }

    @Override
    public void onSaveInstanceState(Bundle bundle) {
        info("MAIN: onSaveInstanceState");
        super.onSaveInstanceState(bundle);
    }

    @Override
    public void onPause() {
        info("MAIN: pause.");
        super.onPause();
        if (this.state.wakeLock.isHeld()) {
            info("release wake lock");
            this.state.wakeLock.release();
        }
    }

    @Override
    public void onResume() {
        info("MAIN: resume.");
        super.onResume();
        if (this.state.wakeLock.isHeld() || !this.state.screenLocked) {
            return;
        }
        info("acquire wake lock");
        this.state.wakeLock.acquire();
    }

    @Override
    protected void onPostCreate(Bundle bundle) {
        super.onPostCreate(bundle);
        this.mDrawerToggle.syncState();
    }

    @Override
    public void onPostResume() {
        info("MAIN: post resume.");
        super.onPostResume();
    }

    @Override
    public void onConfigurationChanged(Configuration configuration) {
        info("MAIN: config changed");
        setLocale(this, configuration);
        super.onConfigurationChanged(configuration);
        this.mDrawerToggle.onConfigurationChanged(configuration);
        if (Build.VERSION.SDK_INT <= 28 || configuration.uiMode == this.state.uiMode) {
            return;
        }
        info("uiMode change - " + this.state.uiMode + "->" + configuration.uiMode);
        this.state.uiMode = configuration.uiMode;
        finishSoon(0L, false, true);
    }

    @Override
    public void onStart() {
        info("MAIN: start.");
        SharedPreferences sharedPreferences = getSharedPreferences(ListFragment.SHARED_PREFS, 0);
        if (sharedPreferences.getBoolean(ListFragment.PREF_BLOWED_UP, false)) {
            sharedPreferences.edit().putBoolean(ListFragment.PREF_BLOWED_UP, false).commit();
            Intent intent = new Intent(this, ErrorReportActivity.class);
            intent.putExtra(ERROR_REPORT_DO_EMAIL, true);
            startActivity(intent);
        }
        super.onStart();
    }

    @Override
    public void onStop() {
        info("MAIN: stop.");
        super.onStop();
    }

    @Override
    public void onRestart() {
        info("MAIN: restart.");
        super.onRestart();
    }

    public static Throwable getBaseThrowable(Throwable th) {
        while (th.getCause() != null) {
            th = th.getCause();
        }
        return th;
    }

    public static String getBaseErrorMessage(Throwable th, boolean z) {
        Throwable baseThrowable = getBaseThrowable(th);
        return baseThrowable.getClass().getSimpleName() + ":" + (z ? IOUtils.LINE_SEPARATOR_UNIX : " ") + baseThrowable.getMessage();
    }

    public static void setLocale(Activity activity) {
        Context baseContext = activity.getBaseContext();
        setLocale(baseContext, baseContext.getResources().getConfiguration());
    }

    public static void setLocale(Context context, Configuration configuration) {
        Locale locale;
        Locale locale2;
        String string = context.getSharedPreferences(ListFragment.SHARED_PREFS, 0).getString(ListFragment.PREF_LANGUAGE, "");
        String language = configuration.locale.getLanguage();
        info("current lang: " + language + " new lang: " + string);
        if (!string.isEmpty() && !language.equals(string)) {
            if (string.contains("-r")) {
                String[] split = string.split("-r");
                info("\tlang: " + split[0] + " country: " + split[1]);
                locale = new Locale(split[0], split[1]);
            } else {
                info("\tlang: " + string + " current: " + language);
                locale = new Locale(string);
            }
        } else {
            locale = (!string.isEmpty() || (locale2 = ORIG_LOCALE) == null || locale2.getLanguage().isEmpty() || language.equals(locale2.getLanguage())) ? null : locale2;
        }
        if (locale != null) {
            Locale.setDefault(locale);
            configuration.locale = locale;
            info("setting locale: " + locale);
            context.getResources().updateConfiguration(configuration, context.getResources().getDisplayMetrics());
            if (getMainActivity() == null || getMainActivity().state == null || getMainActivity().state.ttsChecked) {
                return;
            }
            ttsCheckIntent();
        }
    }

    public static void ttsCheckIntent() {
        MainActivity mainActivity2 = mainActivity;
        if (mainActivity2 != null) {
            if (mainActivity2.getState() == null || !mainActivity.getState().ttsNag.compareAndSet(true, false)) {
                return;
            }
            try {
                Intent intent = new Intent();
                intent.setAction("android.speech.tts.engine.CHECK_TTS_DATA");
                mainActivity.startActivityForResult(intent, 3);
                return;
            } catch (ActivityNotFoundException e) {
                error("TTS check not available in your device." + e.fillInStackTrace());
                return;
            }
        }
        error("could not launch TTS check due to pre-instantiation state");
    }

    public static Locale getLocale(Context context, Configuration configuration) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(ListFragment.SHARED_PREFS, 0);
        String language = configuration.locale.getLanguage();
        String string = sharedPreferences.getString(ListFragment.PREF_LANGUAGE, language);
        if (string.isEmpty()) {
            string = language;
        }
        info("current lang: " + language + " new lang: " + string);
        if (string.contains("-r")) {
            String[] split = string.split("-r");
            info("\tlang: " + split[0] + " country: " + split[1]);
            return new Locale(split[0], split[1]);
        }
        info("\tlang: " + string);
        return new Locale(string);
    }

    private MediaPlayer createMediaPlayer(int i) {
        MediaPlayer createMp = createMp(getApplicationContext(), i);
        if (createMp == null) {
            info("sound null from media player");
            return null;
        }
        createMp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mediaPlayer, int i2, int i3) {
                MainActivity.info("media player error \"" + (i2 != 1 ? i2 != 100 ? "not defined" : "server died" : "error unknown") + "\" what: " + i2 + " extra: " + i3 + " mp: " + mediaPlayer);
                return false;
            }
        });
        return createMp;
    }

    private static Uri resToFile(Context context, int i, String str) throws IOException {
        String str2;
        InputStream inputStream;
        FileOutputStream openFileOutput;
        boolean hasSD = FileUtility.hasSD();
        if (hasSD) {
            String sDPath = FileUtility.getSDPath();
            new File(sDPath).mkdirs();
            str2 = sDPath + str;
        } else {
            str2 = str;
        }
        File file = new File(str2);
        if (!file.exists()) {
            info("causing " + str2 + " to be made");
            if (!file.createNewFile()) {
                throw new IOException("Could not create file: " + str2);
            }
            FileOutputStream fileOutputStream = null;
            try {
                inputStream = context.getResources().openRawResource(i);
                try {
                    if (hasSD) {
                        openFileOutput = new FileOutputStream(file);
                    } else {
                        openFileOutput = context.openFileOutput(str, 0);
                    }
                    fileOutputStream = openFileOutput;
                    byte[] bArr = new byte[1024];
                    while (true) {
                        int read = inputStream.read(bArr);
                        if (read <= -1) {
                            break;
                        }
                        fileOutputStream.write(bArr, 0, read);
                    }
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                    if (inputStream != null) {
                        inputStream.close();
                    }
                } catch (Throwable th) {
                    th = th;
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    throw th;
                }
            } catch (Throwable th2) {
                th = th2;
                inputStream = null;
            }
        }
        return Uri.fromFile(file);
    }

    private static MediaPlayer createMp(Context context, int i) {
        Uri resToFile;
        try {
            MediaPlayer create = MediaPlayer.create(context, i);
            if (create == null) {
                if (i == R.raw.pop) {
                    resToFile = resToFile(context, i, "pop.wav");
                } else if (i == R.raw.newpop) {
                    resToFile = resToFile(context, i, "newpop.wav");
                } else {
                    info("unknown raw sound id:" + i);
                    return null;
                }
                return MediaPlayer.create(context, resToFile);
            }
            return create;
        } catch (Resources.NotFoundException e) {
            error("rnfe create failed(" + i + "): " + e, e);
            return null;
        } catch (IOException e2) {
            error("ioe create failed: " + e2, e2);
            return null;
        } catch (IllegalArgumentException e3) {
            error("iae create failed: " + e3, e3);
            return null;
        } catch (SecurityException e4) {
            error("se create failed: " + e4, e4);
            return null;
        }
    }

    public boolean isMuted() {
        if (this.state.phoneState == null || !this.state.phoneState.isPhoneActive()) {
            return getSharedPreferences(ListFragment.SHARED_PREFS, 0).getBoolean(ListFragment.PREF_MUTED, true);
        }
        return true;
    }

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

    public static void info(String str) {
        Log.i(LOG_TAG, Thread.currentThread().getName() + "] " + str);
        saveLog(str);
    }

    public static void warn(String str) {
        Log.w(LOG_TAG, Thread.currentThread().getName() + "] " + str);
        saveLog(str);
    }

    public static void error(String str) {
        Log.e(LOG_TAG, Thread.currentThread().getName() + "] " + str);
        saveLog(str);
    }

    public static void info(String str, Throwable th) {
        Log.i(LOG_TAG, Thread.currentThread().getName() + "] " + str, th);
        saveLog(str);
    }

    public static void warn(String str, Throwable th) {
        Log.w(LOG_TAG, Thread.currentThread().getName() + "] " + str, th);
        saveLog(str);
    }

    public static void error(String str, Throwable th) {
        Log.e(LOG_TAG, Thread.currentThread().getName() + "] " + str, th);
        saveLog(str);
    }

    private static void saveLog(String str) {
        State staticState = getStaticState();
        if (staticState == null) {
            return;
        }
        int access$508 = State.access$508(staticState) % staticState.logs.length;
        staticState.logs[access$508] = new SimpleDateFormat("HH:mm:ss.SSS", Locale.US).format(new Date()) + " " + Thread.currentThread().getName() + "] " + str;
        if (access$508 > staticState.logs.length * 10000) {
            staticState.logPointer -= staticState.logs.length * 100;
        }
    }

    public static ConcurrentLinkedHashMap<String, Network> getNetworkCache() {
        return ListFragment.lameStatic.networkCache;
    }

    public static void addNetworkToMap(Network network) {
        MappingFragment mappingFragment;
        FragmentManager supportFragmentManager = mainActivity.getSupportFragmentManager();
        if (getStaticState().currentTab != R.id.nav_map || (mappingFragment = (MappingFragment) supportFragmentManager.findFragmentByTag("VisibleFragment-2131231108")) == null) {
            return;
        }
        mappingFragment.addNetwork(network);
    }

    public static void updateNetworkOnMap(Network network) {
        MappingFragment mappingFragment;
        FragmentManager supportFragmentManager = mainActivity.getSupportFragmentManager();
        if (getStaticState().currentTab != R.id.nav_map || (mappingFragment = (MappingFragment) supportFragmentManager.findFragmentByTag("VisibleFragment-2131231108")) == null) {
            return;
        }
        mappingFragment.updateNetwork(network);
    }

    public static void reclusterMap() {
        MappingFragment mappingFragment;
        FragmentManager supportFragmentManager = mainActivity.getSupportFragmentManager();
        if (getStaticState().currentTab != R.id.nav_map || (mappingFragment = (MappingFragment) supportFragmentManager.findFragmentByTag("VisibleFragment-2131231108")) == null) {
            return;
        }
        mappingFragment.reCluster();
    }

    public static void writeError(Thread thread, Throwable th, Context context) {
        writeError(thread, th, context, null);
    }

    public static void writeError(Thread thread, Throwable th, Context context, String str) {
        try {
            String str2 = "Thread: " + thread + " throwable: " + th;
            error(str2, th);
            File errorStackPath = FileUtility.getErrorStackPath(context);
            if (errorStackPath.exists() && errorStackPath.canWrite()) {
                errorStackPath.mkdirs();
                File file = new File(errorStackPath, "errorstack_" + System.currentTimeMillis() + ".txt");
                error("Writing stackfile to: " + file.getAbsolutePath());
                if (!file.exists() && !file.createNewFile()) {
                    throw new IOException("Cannot create file: " + file);
                }
                FileOutputStream fileOutputStream = null;
                try {
                    FileOutputStream fileOutputStream2 = new FileOutputStream(file);
                    try {
                        PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
                        StringBuilder sb = new StringBuilder("WigleWifi error log - ");
                        sb.append(SimpleDateFormat.getDateTimeInstance().format(new Date())).append(IOUtils.LINE_SEPARATOR_UNIX);
                        if (packageInfo != null) {
                            sb.append("versionName: ").append(packageInfo.versionName).append(IOUtils.LINE_SEPARATOR_UNIX);
                            sb.append("packageName: ").append(packageInfo.packageName).append(IOUtils.LINE_SEPARATOR_UNIX);
                        }
                        if (str != null) {
                            sb.append("detail: ").append(str).append(IOUtils.LINE_SEPARATOR_UNIX);
                        }
                        sb.append("MODEL: ").append(Build.MODEL).append(IOUtils.LINE_SEPARATOR_UNIX);
                        sb.append("RELEASE: ").append(Build.VERSION.RELEASE).append(IOUtils.LINE_SEPARATOR_UNIX);
                        sb.append("BOARD: ").append(Build.BOARD).append(IOUtils.LINE_SEPARATOR_UNIX);
                        sb.append("BRAND: ").append(Build.BRAND).append(IOUtils.LINE_SEPARATOR_UNIX);
                        sb.append("DEVICE: ").append(Build.DEVICE).append(IOUtils.LINE_SEPARATOR_UNIX);
                        sb.append("DISPLAY: ").append(Build.DISPLAY).append(IOUtils.LINE_SEPARATOR_UNIX);
                        sb.append("FINGERPRINT: ").append(Build.FINGERPRINT).append(IOUtils.LINE_SEPARATOR_UNIX);
                        sb.append("HOST: ").append(Build.HOST).append(IOUtils.LINE_SEPARATOR_UNIX);
                        sb.append("ID: ").append(Build.ID).append(IOUtils.LINE_SEPARATOR_UNIX);
                        sb.append("PRODUCT: ").append(Build.PRODUCT).append(IOUtils.LINE_SEPARATOR_UNIX);
                        sb.append("TAGS: ").append(Build.TAGS).append(IOUtils.LINE_SEPARATOR_UNIX);
                        sb.append("TIME: ").append(Build.TIME).append(IOUtils.LINE_SEPARATOR_UNIX);
                        sb.append("TYPE: ").append(Build.TYPE).append(IOUtils.LINE_SEPARATOR_UNIX);
                        sb.append("USER: ").append(Build.USER).append(IOUtils.LINE_SEPARATOR_UNIX);
                        fileOutputStream2.write(sb.toString().getBytes(ENCODING));
                        String baseErrorMessage = getBaseErrorMessage(th, false);
                        fileOutputStream2.write("baseError: ".getBytes(ENCODING));
                        fileOutputStream2.write(baseErrorMessage.getBytes(ENCODING));
                        fileOutputStream2.write("\n\n".getBytes(ENCODING));
                        th.printStackTrace(new PrintStream(fileOutputStream2));
                        fileOutputStream2.write((str2 + "\n\n").getBytes(ENCODING));
                        for (String str3 : getLogLines()) {
                            fileOutputStream2.write(str3.getBytes(ENCODING));
                            fileOutputStream2.write(IOUtils.LINE_SEPARATOR_UNIX.getBytes(ENCODING));
                        }
                        try {
                            fileOutputStream2.close();
                        } catch (Exception e) {
                            error("error closing fos: " + e, e);
                        }
                    }
                } catch (Throwable th2) {
                    if (0 != 0) {
                        try {
                            fileOutputStream.close();
                        } catch (Exception e2) {
                            error("error closing fos: " + e2, e2);
                        }
                    }
                    throw th2;
                }
            }
        } catch (Exception e3) {
            error("error logging error: " + e3, e3);
            e3.printStackTrace();
        }
    }

    private static void handleErrorError(FileOutputStream fileOutputStream, Throwable th) throws IOException {
        String str = "error getting data for error: " + th;
        error(str, th);
        fileOutputStream.write((str + "\n\n").getBytes(ENCODING));
        th.printStackTrace(new PrintStream(fileOutputStream));
    }

    public static Iterable<String> getLogLines() {
        final State staticState = getStaticState();
        return new Iterable<String>() {
            @Override
            public Iterator<String> iterator() {
                return State.this == null ? Collections.emptySet().iterator() : new Iterator<String>() {
                    int currentPointer;
                    final int maxPointer;

                    {
                        int i = State.this.logPointer;
                        this.currentPointer = i;
                        this.maxPointer = i + State.this.logs.length;
                    }

                    @Override
                    public boolean hasNext() {
                        return State.this.logs[this.currentPointer % State.this.logs.length] != null && this.currentPointer < this.maxPointer;
                    }

                    @Override
                    public String next() {
                        String str = State.this.logs[this.currentPointer % State.this.logs.length];
                        this.currentPointer++;
                        return str;
                    }
                };
            }
        };
    }

    public static boolean isDevMode(Context context) {
        return Build.VERSION.SDK_INT == 16 ? Settings.Secure.getInt(context.getContentResolver(), "development_settings_enabled", 0) != 0 : Build.VERSION.SDK_INT >= 17 && Settings.Secure.getInt(context.getContentResolver(), "development_settings_enabled", 0) != 0;
    }

    private void setupSound() {
        if (this.state.soundPop == null) {
            this.state.soundPop = createMediaPlayer(R.raw.pop);
        }
        if (this.state.soundNewPop == null) {
            this.state.soundNewPop = createMediaPlayer(R.raw.newpop);
        }
        setVolumeControlStream(3);
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService("phone");
        if (telephonyManager != null && this.state.phoneState == null) {
            this.state.phoneState = new PhoneState();
            try {
                telephonyManager.listen(this.state.phoneState, 289);
            } catch (SecurityException e) {
                info("cannot get call state, will play audio over any telephone calls: " + e);
            }
        }
        if (getMainActivity() == null || getMainActivity().state == null || getMainActivity().state.ttsChecked) {
            return;
        }
        ttsCheckIntent();
    }

    private void setupFilters(SharedPreferences sharedPreferences) {
        State state = this.state;
        if (state != null) {
            state.bssidDisplayExclusions = generateBssidFilterMatcher(sharedPreferences, ListFragment.PREF_EXCLUDE_DISPLAY_ADDRS);
            this.state.bssidLogExclusions = generateBssidFilterMatcher(sharedPreferences, ListFragment.PREF_EXCLUDE_LOG_ADDRS);
        }
    }

    public void updateAddressFilter(String str) {
        if (this.state != null) {
            SharedPreferences sharedPreferences = getSharedPreferences(ListFragment.SHARED_PREFS, 0);
            if (ListFragment.PREF_EXCLUDE_DISPLAY_ADDRS.equals(str)) {
                this.state.bssidDisplayExclusions = generateBssidFilterMatcher(sharedPreferences, ListFragment.PREF_EXCLUDE_DISPLAY_ADDRS);
            } else if (ListFragment.PREF_EXCLUDE_LOG_ADDRS.equals(str)) {
                this.state.bssidLogExclusions = generateBssidFilterMatcher(sharedPreferences, ListFragment.PREF_EXCLUDE_LOG_ADDRS);
            }
        }
    }

    public Matcher getBssidFilterMatcher(String str) {
        if (this.state != null) {
            if (ListFragment.PREF_EXCLUDE_DISPLAY_ADDRS.equals(str)) {
                return this.state.bssidDisplayExclusions;
            }
            if (ListFragment.PREF_EXCLUDE_LOG_ADDRS.equals(str)) {
                return this.state.bssidLogExclusions;
            }
            return null;
        }
        return null;
    }

    private Matcher generateBssidFilterMatcher(SharedPreferences sharedPreferences, String str) {
        String[] strArr = (String[]) new Gson().fromJson(sharedPreferences.getString(str, "[]"), (Class<Object>) String[].class);
        if (strArr.length > 0) {
            StringBuilder sb = new StringBuilder("^(");
            boolean z = true;
            for (String str2 : strArr) {
                if (z) {
                    z = false;
                } else {
                    sb.append("|");
                }
                sb.append(str2);
                if (str2.length() == 17) {
                    sb.append("$");
                }
            }
            sb.append(")");
            info("building regex from: " + sb.toString());
            return Pattern.compile(sb.toString(), 2).matcher("");
        }
        return null;
    }

    public boolean inEmulator() {
        return this.state.inEmulator;
    }

    public BatteryLevelReceiver getBatteryLevelReceiver() {
        return this.batteryLevelReceiver;
    }

    public GPSListener getGPSListener() {
        return this.state.gpsListener;
    }

    public PhoneState getPhoneState() {
        return this.state.phoneState;
    }

    @Override
    public boolean isFinishing() {
        return this.state.finishing.get();
    }

    public boolean isTransferring() {
        return this.state.transferring.get();
    }

    public boolean isScanning() {
        return isScanning(this);
    }

    public static boolean isScanning(Context context) {
        return context.getSharedPreferences(ListFragment.SHARED_PREFS, 0).getBoolean(ListFragment.PREF_SCAN_RUNNING, true);
    }

    public void playNewNetSound() {
        try {
            if (this.state.soundNewPop != null && !this.state.soundNewPop.isPlaying()) {
                this.state.soundNewPop.start();
            } else {
                info("soundNewPop is playing or null");
            }
        } catch (IllegalStateException e) {
            info("exception trying to play sound: " + e);
        }
    }

    public void playRunNetSound() {
        try {
            if (this.state.soundPop != null && !this.state.soundPop.isPlaying()) {
                this.state.soundPop.start();
            } else {
                info("soundPop is playing or null");
            }
        } catch (IllegalStateException e) {
            info("exception trying to play sound: " + e);
        }
    }

    private void setupActivationDialog() {
        String str;
        boolean canBtBeActivated = canBtBeActivated();
        boolean canWifiBeActivated = canWifiBeActivated();
        SharedPreferences sharedPreferences = getSharedPreferences(ListFragment.SHARED_PREFS, 0);
        boolean z = sharedPreferences.getBoolean(ListFragment.PREF_SCAN_BT, true);
        boolean z2 = Build.VERSION.SDK_INT >= 28;
        int i = sharedPreferences.getInt(ListFragment.PREF_PIE_BAD_TOAST_COUNT, 0);
        int i2 = sharedPreferences.getInt(ListFragment.PREF_Q_BAD_TOAST_COUNT, 0);
        if ((canBtBeActivated && z) || canWifiBeActivated || z2) {
            str = "";
            SharedPreferences.Editor edit = sharedPreferences.edit();
            if (Build.VERSION.SDK_INT == 28) {
                str = i < 5 ? getString(R.string.pie_bad) : "";
                edit.putInt(ListFragment.PREF_PIE_BAD_TOAST_COUNT, i + 1);
            } else if (Build.VERSION.SDK_INT == 29) {
                str = i2 < 5 ? getString(R.string.q_bad) : "";
                edit.putInt(ListFragment.PREF_Q_BAD_TOAST_COUNT, i2 + 1);
            }
            edit.apply();
            if (canBtBeActivated && z) {
                if (str.length() > 0) {
                    str = str + IOUtils.LINE_SEPARATOR_UNIX;
                }
                str = str + getString(R.string.turn_on_bt);
                if (canWifiBeActivated) {
                    str = str + IOUtils.LINE_SEPARATOR_UNIX;
                }
            }
            if (canWifiBeActivated) {
                str = str + getString(R.string.turn_on_wifi);
            }
            if (str.isEmpty()) {
                return;
            }
            WiGLEToast.showOverActivity(this, R.string.app_name, str, 1);
        }
    }

    private boolean canWifiBeActivated() {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService("wifi");
        return (wifiManager == null || wifiManager.isWifiEnabled() || this.state.inEmulator) ? false : true;
    }

    private void setupWifi() {
        if ("1".equals(Settings.Secure.getString(getContentResolver(), "wifi_networks_available_notification_on")) && this.state.wifiReceiver == null) {
            WiGLEToast.showOverActivity(this, R.string.app_name, getString(R.string.best_results));
        }
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService("wifi");
        boolean z = false;
        SharedPreferences.Editor edit = getSharedPreferences(ListFragment.SHARED_PREFS, 0).edit();
        if (wifiManager != null && !wifiManager.isWifiEnabled()) {
            z = true;
            if (Build.VERSION.SDK_INT >= 29) {
                startActivityForResult(new Intent("android.settings.panel.action.WIFI"), 2);
            } else {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        MainActivity mainActivity2 = MainActivity.this;
                        WiGLEToast.showOverActivity(mainActivity2, R.string.app_name, mainActivity2.getString(R.string.turn_on_wifi), 1);
                        MainActivity.this.startActivity(new Intent("android.settings.WIFI_SETTINGS"));
                    }
                }, 3000L);
            }
        }
        edit.apply();
        if (this.state.wifiReceiver == null) {
            info("new wifiReceiver");
            this.state.wifiReceiver = new WifiReceiver(this, this.state.dbHelper, getApplicationContext());
            this.state.wifiReceiver.setupWifiTimer(z);
        }
        setupWifiReceiverIntent();
        if (this.state.wifiLock != null || wifiManager == null) {
            return;
        }
        info("lock wifi radio on");
        this.state.wifiLock = wifiManager.createWifiLock(2, ListFragment.WIFI_LOCK_NAME);
        this.state.wifiLock.acquire();
    }

    @Override
    protected void onActivityResult(int i, int i2, Intent intent) {
        super.onActivityResult(i, i2, intent);
        if (i == 2) {
            if (i2 == -1) {
                info("wifi turned on");
            } else {
                info("wifi NOT turned on, resultCode: " + i2);
            }
        } else if (i != 3) {
            info("MainActivity: Unhandled requestCode: " + i + " resultCode: " + i2);
        } else if (i2 == 1) {
            this.state.tts = new TextToSpeech(this, this);
        } else {
            try {
                PackageManager packageManager = getPackageManager();
                Intent intent2 = new Intent();
                intent2.setAction("android.speech.tts.engine.INSTALL_TTS_DATA");
                if (packageManager.resolveActivity(intent2, 65536) == null) {
                    error("ACTION_TTS_CALLBACK: resolve ACTION_INSTALL_TTS_DATA via package mgr.");
                } else {
                    startActivity(intent2);
                }
            } catch (Exception e) {
                error("ACTION_TTS_CALLBACK: failed to issue ACTION_INSTALL_TTS_DATA", e);
            }
        }
    }

    private void setupWifiReceiverIntent() {
        info("register BroadcastReceiver");
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.wifi.SCAN_RESULTS");
        registerReceiver(this.state.wifiReceiver, intentFilter);
    }

    private boolean canBtBeActivated() {
        BluetoothAdapter defaultAdapter;
        try {
            defaultAdapter = BluetoothAdapter.getDefaultAdapter();
        } catch (SecurityException unused) {
            warn("bt activation security exception");
        }
        if (defaultAdapter != null) {
            return !defaultAdapter.isEnabled();
        }
        info("No bluetooth adapter");
        return false;
    }

    public void setupBluetooth() {
        try {
            BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
            if (defaultAdapter == null) {
                info("No bluetooth adapter");
                return;
            }
            SharedPreferences sharedPreferences = getSharedPreferences(ListFragment.SHARED_PREFS, 0);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            if (sharedPreferences.getBoolean(ListFragment.PREF_SCAN_BT, true)) {
                if (defaultAdapter.getState() != 10 && defaultAdapter.getState() != 13) {
                    edit.putBoolean(ListFragment.PREF_BT_WAS_OFF, false);
                    edit.apply();
                    if (this.state.bluetoothReceiver == null) {
                        info("new bluetoothReceiver");
                        boolean hasSystemFeature = getPackageManager().hasSystemFeature("android.hardware.bluetooth_le");
                        this.state.bluetoothReceiver = new BluetoothReceiver(this, this.state.dbHelper, hasSystemFeature);
                        this.state.bluetoothReceiver.setupBluetoothTimer(true);
                    }
                    info("register bluetooth BroadcastReceiver");
                    IntentFilter intentFilter = new IntentFilter("android.bluetooth.device.action.FOUND");
                    intentFilter.addAction("android.bluetooth.adapter.action.DISCOVERY_FINISHED");
                    registerReceiver(this.state.bluetoothReceiver, intentFilter);
                }
                info("Enable bluetooth");
                edit.putBoolean(ListFragment.PREF_BT_WAS_OFF, true);
                defaultAdapter.enable();
                edit.apply();
                if (this.state.bluetoothReceiver == null) {
                }
                info("register bluetooth BroadcastReceiver");
                IntentFilter intentFilter2 = new IntentFilter("android.bluetooth.device.action.FOUND");
                intentFilter2.addAction("android.bluetooth.adapter.action.DISCOVERY_FINISHED");
                registerReceiver(this.state.bluetoothReceiver, intentFilter2);
            }
        } catch (SecurityException e) {
            info("Security exception attempting to access bluetooth adapter", e);
        } catch (Exception e2) {
            error("failure initializing bluetooth: ", e2);
        }
    }

    public void endBluetooth(SharedPreferences sharedPreferences) {
        if (this.state.bluetoothReceiver != null) {
            this.state.bluetoothReceiver.stopScanning();
        }
        BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
        if (defaultAdapter != null && defaultAdapter.isDiscovering()) {
            defaultAdapter.cancelDiscovery();
        }
        try {
            info("unregister bluetoothReceiver");
            unregisterReceiver(this.state.bluetoothReceiver);
            this.state.bluetoothReceiver = null;
        } catch (IllegalArgumentException e) {
            info("bluetoothReceiver not registered: " + e);
        }
        boolean z = sharedPreferences.getBoolean(ListFragment.PREF_BT_WAS_OFF, false);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.remove(ListFragment.PREF_BT_WAS_OFF);
        edit.apply();
        if (!z || this.state.inEmulator) {
            return;
        }
        info("turning bluetooth back off");
        try {
            BluetoothAdapter defaultAdapter2 = BluetoothAdapter.getDefaultAdapter();
            if (defaultAdapter2 == null) {
                info("No bluetooth adapter");
            } else if (defaultAdapter2.isEnabled()) {
                info("Disable bluetooth");
                defaultAdapter2.disable();
            }
        } catch (Exception e2) {
            error("exception turning bluetooth back off: " + e2, e2);
        }
    }

    public void bluetoothScan() {
        if (this.state.bluetoothReceiver != null) {
            this.state.bluetoothReceiver.bluetoothScan();
        }
    }

    private void setupBattery() {
        if (this.batteryLevelReceiver == null) {
            this.batteryLevelReceiver = new BatteryLevelReceiver();
            registerReceiver(this.batteryLevelReceiver, new IntentFilter("android.intent.action.BATTERY_CHANGED"));
        }
    }

    public void setTransferring() {
        info("setTransferring");
        this.state.transferring.set(true);
    }

    public void scheduleScan() {
        this.state.wifiReceiver.scheduleScan();
    }

    public void speak(String str) {
        if (getMainActivity().isMuted() || this.state.tts == null) {
            return;
        }
        this.state.tts.speak(str, 1, null);
    }

    public void interruptSpeak() {
        if (this.state.tts != null) {
            this.state.tts.stop();
        }
    }

    private void setupService() {
        if (this.state.serviceConnection == null) {
            this.state.serviceConnection = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                    MainActivity.info(componentName + " service connected");
                    MainActivity.this.state.wigleService = ((WigleService.WigleServiceBinder) iBinder).getService();
                }

                @Override
                public void onServiceDisconnected(ComponentName componentName) {
                    MainActivity.info(componentName + " service disconnected");
                }
            };
            info("service bound: " + getApplicationContext().bindService(new Intent(getApplicationContext(), WigleService.class), this.state.serviceConnection, 65));
        }
    }

    private void setupLocation() {
        LocationManager locationManager = (LocationManager) getSystemService(DatabaseHelper.LOCATION_TABLE);
        try {
            if (locationManager.getProvider("gps") == null) {
                WiGLEToast.showOverActivity(this, R.string.app_name, getString(R.string.no_gps_device), 1);
            } else if (!locationManager.isProviderEnabled("gps")) {
                WiGLEToast.showOverActivity(this, R.string.app_name, getString(R.string.turn_on_gps), 1);
                try {
                    startActivity(new Intent("android.settings.LOCATION_SOURCE_SETTINGS"));
                } catch (Exception e) {
                    error("exception trying to start location activity: " + e, e);
                }
            }
            if (this.state.gpsListener == null) {
                SharedPreferences sharedPreferences = getSharedPreferences(ListFragment.SHARED_PREFS, 0);
                if (sharedPreferences.getBoolean(ListFragment.PREF_LOG_ROUTES, false)) {
                    startRouteLogging(sharedPreferences);
                }
                if (sharedPreferences.getBoolean(ListFragment.PREF_VISUALIZE_ROUTE, false)) {
                    startRouteMapping(sharedPreferences);
                }
                internalHandleScanChange(sharedPreferences.getBoolean(ListFragment.PREF_SCAN_RUNNING, true));
            }
        } catch (SecurityException e2) {
            info("Security exception in setupLocation: " + e2);
        }
    }

    public void handleScanChange(boolean z) {
        if (z == isScanning()) {
            info("main handleScanChange: no difference, returning");
            return;
        }
        SharedPreferences sharedPreferences = getSharedPreferences(ListFragment.SHARED_PREFS, 0);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        if (z) {
            edit.putLong(ListFragment.PREF_STARTTIME_CURRENT_SCAN, System.currentTimeMillis());
        } else {
            long j = sharedPreferences.getLong(ListFragment.PREF_CUMULATIVE_SCANTIME_RUN, 0L);
            edit.putLong(ListFragment.PREF_CUMULATIVE_SCANTIME_RUN, (j + System.currentTimeMillis()) - sharedPreferences.getLong(ListFragment.PREF_STARTTIME_CURRENT_SCAN, System.currentTimeMillis()));
        }
        edit.putBoolean(ListFragment.PREF_SCAN_RUNNING, z);
        edit.apply();
        internalHandleScanChange(z);
    }

    private ListFragment getListFragmentIfCurrent() {
        try {
            Fragment findFragmentByTag = getSupportFragmentManager().findFragmentByTag("VisibleFragment-2131231107");
            if (findFragmentByTag != null) {
                return (ListFragment) findFragmentByTag;
            }
            return null;
        } catch (Exception e) {
            error("Unable to get listfragment: ", e);
            return null;
        }
    }

    private void internalHandleScanChange(boolean z) {
        info("main internalHandleScanChange: isScanning now: " + z);
        ListFragment listFragmentIfCurrent = getListFragmentIfCurrent();
        if (z) {
            if (listFragmentIfCurrent != null) {
                listFragmentIfCurrent.setStatusUI(getString(R.string.list_scanning_on));
                listFragmentIfCurrent.setScanningStatusIndicator(true);
            }
            if (this.state.wifiReceiver != null) {
                this.state.wifiReceiver.updateLastScanResponseTime();
            }
            setLocationUpdates(getLocationSetPeriod(), 0.0f);
            if (!this.state.wifiLock.isHeld()) {
                this.state.wifiLock.acquire();
            }
        } else {
            if (listFragmentIfCurrent != null) {
                listFragmentIfCurrent.setStatusUI(getString(R.string.list_scanning_off));
                listFragmentIfCurrent.setScanningStatusIndicator(false);
            }
            setLocationUpdates(0L, 0.0f);
            this.state.gpsListener.handleScanStop();
            if (this.state.wifiLock.isHeld()) {
                try {
                    this.state.wifiLock.release();
                } catch (SecurityException e) {
                    info("exception releasing wifilock: " + e);
                }
            }
        }
        State state = this.state;
        if (state == null || state.wigleService == null) {
            return;
        }
        this.state.wigleService.setupNotification();
    }

    public void setLocationUpdates(long j, float f) {
        try {
            internalSetLocationUpdates(j, f);
        } catch (SecurityException e) {
            error("Security exception in setLocationUpdates: " + e, e);
        }
    }

    private void internalSetLocationUpdates(long j, float f) throws SecurityException {
        GnssStatus.Callback callback;
        GnssStatus.Callback callback2;
        LocationManager locationManager = (LocationManager) getSystemService(DatabaseHelper.LOCATION_TABLE);
        if (this.state.gpsListener != null) {
            locationManager.removeUpdates(this.state.gpsListener);
            if (Build.VERSION.SDK_INT >= 24 && (callback2 = this.gnssStatusCallback) != null) {
                locationManager.unregisterGnssStatusCallback(callback2);
            }
            locationManager.removeGpsStatusListener(this.state.gpsListener);
        }
        this.state.gpsListener = new GPSListener(this, this.state.dbHelper);
        this.state.gpsListener.setMapListener(MappingFragment.STATIC_LOCATION_LISTENER);
        try {
            locationManager.addGpsStatusListener(this.state.gpsListener);
        } catch (SecurityException e) {
            info("Security exception adding status listener: " + e, e);
        }
        if (Build.VERSION.SDK_INT >= 24) {
            try {
                GnssStatus.Callback callback3 = new GnssStatus.Callback() {
                    @Override
                    public void onFirstFix(int i) {
                    }

                    @Override
                    public void onStarted() {
                    }

                    @Override
                    public void onStopped() {
                    }

                    @Override
                    public void onSatelliteStatusChanged(GnssStatus gnssStatus) {
                        MainActivity.this.state.gpsListener.onGnssStatusChanged(gnssStatus);
                    }
                };
                this.gnssStatusCallback = callback3;
                locationManager.registerGnssStatusCallback(callback3);
            } catch (Exception e2) {
                error("Error registering for gnss: " + e2, e2);
            }
        }
        boolean z = getSharedPreferences(ListFragment.SHARED_PREFS, 0).getBoolean(ListFragment.PREF_USE_NETWORK_LOC, false);
        List<String> allProviders = locationManager.getAllProviders();
        if (allProviders != null) {
            for (String str : allProviders) {
                info("available provider: " + str + " updateIntervalMillis: " + j);
                if (z || !DatabaseHelper.NETWORK_TABLE.equals(str)) {
                    if (!"passive".equals(str) && j > 0) {
                        info("using provider: " + str);
                        try {
                            locationManager.requestLocationUpdates(str, j, f, this.state.gpsListener);
                        } catch (SecurityException e3) {
                            info("Security exception adding status listener: " + e3, e3);
                        }
                    }
                }
            }
            if (j <= 0) {
                info("removing location listener: " + this.state.gpsListener);
                try {
                    locationManager.removeUpdates(this.state.gpsListener);
                    if (Build.VERSION.SDK_INT < 24 || (callback = this.gnssStatusCallback) == null) {
                        return;
                    }
                    locationManager.unregisterGnssStatusCallback(callback);
                } catch (SecurityException e4) {
                    info("Security exception removing status listener: " + e4, e4);
                }
            }
        }
    }

    public static <A> String join(String str, Iterable<A> iterable) {
        if (str == null || iterable == null) {
            throw new IllegalArgumentException("join argument is null. delimiter: " + str + " iterable: " + iterable);
        }
        StringBuilder sb = new StringBuilder();
        for (A a : iterable) {
            if (a != null) {
                if (sb.length() > 0) {
                    sb.append(str);
                }
                sb.append(a.toString());
            }
        }
        return sb.toString();
    }

    public long getLocationSetPeriod() {
        long j = getSharedPreferences(ListFragment.SHARED_PREFS, 0).getLong(ListFragment.GPS_SCAN_PERIOD, 1000L);
        if (j == 0) {
            if (this.state.wifiReceiver == null) {
                return 1000L;
            }
            return Math.max(this.state.wifiReceiver.getScanPeriod(), 1000L);
        }
        return j;
    }

    public void setLocationUpdates() {
        setLocationUpdates(getLocationSetPeriod(), 0.0f);
    }

    public void transferComplete() {
        this.state.transferring.set(false);
        info("transfer complete");
        scheduleScan();
        this.state.observationUploader = null;
    }

    public void setLocationUI() {
        ListFragment listFragmentIfCurrent = getListFragmentIfCurrent();
        if (listFragmentIfCurrent != null) {
            listFragmentIfCurrent.setLocationUI(this);
        }
    }

    public void setNetCountUI() {
        ListFragment listFragmentIfCurrent = getListFragmentIfCurrent();
        if (listFragmentIfCurrent != null) {
            listFragmentIfCurrent.setNetCountUI(getState());
        }
    }

    public void setStatusUI(String str) {
        if (str == null) {
            str = this.state.previousStatus;
        }
        if (str != null) {
            this.state.previousStatus = str;
            ListFragment listFragmentIfCurrent = getListFragmentIfCurrent();
            if (listFragmentIfCurrent != null) {
                listFragmentIfCurrent.setStatusUI(str);
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        return this.mDrawerToggle.onOptionsItemSelected(menuItem);
    }

    public void finishSoon() {
        finishSoon(FINISH_TIME_MILLIS, false, false);
    }

    public void finishSoon(long j, boolean z) {
        finishSoon(j, z, false);
    }

    public void finishSoon(long j, final boolean z, final boolean z2) {
        info("Will finish in " + j + "ms");
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                final Intent launchIntentForPackage = MainActivity.this.getBaseContext().getPackageManager().getLaunchIntentForPackage(MainActivity.this.getBaseContext().getPackageName());
                if (launchIntentForPackage != null) {
                    launchIntentForPackage.addFlags(67108864);
                    if (MainActivity.this.state.finishing.get()) {
                        MainActivity.info("finishSoon: finish already called");
                    } else {
                        MainActivity.info("finishSoon: calling finish now");
                        if (z2) {
                            MainActivity.info("UI-only termination (ui restart: " + MainActivity.this.state.uiRestart.get() + ")");
                            MainActivity.this.state.uiRestart.set(true);
                            MainActivity.super.recreate();
                        } else {
                            MainActivity.this.finish();
                        }
                    }
                    if (z) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                MainActivity.this.startActivity(launchIntentForPackage);
                            }
                        }, MainActivity.FINISH_TIME_MILLIS);
                        return;
                    }
                    return;
                }
                MainActivity.warn("Intent generation failed during finishSoon thread");
            }
        }, j);
    }

    @Override
    public void finish() {
        GnssStatus.Callback callback;
        info("MAIN: finish.");
        if (!this.state.uiRestart.get()) {
            if (this.state.wifiReceiver != null) {
                info("MAIN: finish. networks: " + this.state.wifiReceiver.getRunNetworkCount());
            }
            if (this.state.finishing.getAndSet(true)) {
                info("MAIN: finish called twice!");
            }
            ObservationUploader observationUploader = this.state.observationUploader;
            if (observationUploader != null) {
                observationUploader.setInterrupted();
            }
            if (this.state.gpsListener != null) {
                this.state.gpsListener.saveLocation();
            }
            if (this.state.dbHelper != null) {
                this.state.dbHelper.close();
            }
            LocationManager locationManager = (LocationManager) getSystemService(DatabaseHelper.LOCATION_TABLE);
            if (this.state.gpsListener != null && locationManager != null) {
                try {
                    locationManager.removeGpsStatusListener(this.state.gpsListener);
                    locationManager.removeUpdates(this.state.gpsListener);
                    if (Build.VERSION.SDK_INT >= 24 && (callback = this.gnssStatusCallback) != null) {
                        locationManager.unregisterGnssStatusCallback(callback);
                    }
                } catch (IllegalStateException e) {
                    error("ISE turning off GPS: ", e);
                } catch (NullPointerException e2) {
                    error("NPE turning off GPS: ", e2);
                } catch (SecurityException e3) {
                    error("SecurityException on finish: " + e3, e3);
                }
            }
            stopService(new Intent(this, WigleService.class));
            try {
                getApplicationContext().unbindService(this.state.serviceConnection);
            } catch (IllegalArgumentException e4) {
                info("serviceConnection not registered: " + e4, e4);
            }
            if (this.state.wifiLock != null && this.state.wifiLock.isHeld()) {
                try {
                    this.state.wifiLock.release();
                } catch (Exception e5) {
                    error("exception releasing wifi lock: " + e5, e5);
                }
            }
            endBluetooth(getSharedPreferences(ListFragment.SHARED_PREFS, 0));
            TelephonyManager telephonyManager = (TelephonyManager) getSystemService("phone");
            if (telephonyManager != null && this.state.phoneState != null) {
                telephonyManager.listen(this.state.phoneState, 0);
            }
            if (this.state.tts != null) {
                if (!isMuted()) {
                    sleep(250L);
                }
                this.state.tts.shutdown();
            }
            if (this.state.soundPop != null) {
                this.state.soundPop.release();
            }
            if (this.state.soundNewPop != null) {
                this.state.soundNewPop.release();
            }
            info("MAIN: finish complete.");
        }
        super.finish();
    }

    @Override
    public boolean onKeyDown(int i, KeyEvent keyEvent) {
        if (i == 4) {
            info("onKeyDown: not quitting app on back");
            selectFragment(R.id.nav_list);
            return true;
        }
        return super.onKeyDown(i, keyEvent);
    }

    public void doUpload() {
        selectFragment(R.id.nav_list);
        getListFragmentIfCurrent().makeUploadDialog(this);
    }

    public void backgroundUploadFile() {
        info("background upload file");
        State state = getState();
        setTransferring();
        state.observationUploader = new ObservationUploader(this, ListFragment.lameStatic.dbHelper, null, false, false, false);
        try {
            state.observationUploader.startDownload(null);
        } catch (WiGLEAuthException unused) {
            warn("Authentication failure on background run upload");
        }
    }

    public boolean checkStorage() {
        boolean checkInternalStorageDangerZone;
        boolean hasSD = FileUtility.hasSD();
        if (hasSD) {
            checkInternalStorageDangerZone = FileUtility.checkExternalStorageDangerZone();
        } else {
            checkInternalStorageDangerZone = FileUtility.checkInternalStorageDangerZone();
        }
        if (!checkInternalStorageDangerZone) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(hasSD ? R.string.no_external_space_message : R.string.no_internal_space_message).setTitle(hasSD ? R.string.no_external_space_title : R.string.no_internal_space_title).setCancelable(true).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                }
            });
            AlertDialog create = builder.create();
            if (!isFinishing()) {
                create.show();
            }
        }
        return checkInternalStorageDangerZone;
    }

    public void startRouteLogging(SharedPreferences sharedPreferences) {
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putLong(ListFragment.PREF_ROUTE_DB_RUN, sharedPreferences.getLong(ListFragment.PREF_ROUTE_DB_RUN, 0L) + 1);
        edit.apply();
    }

    public void startRouteMapping(SharedPreferences sharedPreferences) {
        State state;
        if (sharedPreferences.getBoolean(ListFragment.PREF_LOG_ROUTES, false) || (state = this.state) == null || state.dbHelper == null) {
            return;
        }
        try {
            this.state.dbHelper.clearDefaultRoute();
        } catch (DBException e) {
            warn("unable to clear default route on start-viz: ", e);
        }
    }

    public void endRouteMapping(SharedPreferences sharedPreferences) {
        State state;
        if (sharedPreferences.getBoolean(ListFragment.PREF_LOG_ROUTES, false) || (state = this.state) == null || state.dbHelper == null) {
            return;
        }
        try {
            this.state.dbHelper.clearDefaultRoute();
        } catch (DBException e) {
            warn("unable to clear default route on end-viz: ", e);
        }
    }

    @Override
    public void onInit(int i) {
        State state;
        if (i != 0 || (state = this.state) == null || state.tts == null) {
            if (i == 0) {
                info("TTS init successful, but state or TTS engine was null");
                return;
            } else if (i == -1) {
                error("TTS init failed: " + i);
                return;
            } else {
                return;
            }
        }
        Locale locale = getLocale(getApplicationContext(), getApplicationContext().getResources().getConfiguration());
        info("LOCALE: " + locale);
        if (this.state.tts.isLanguageAvailable(locale) == 0) {
            this.state.tts.setLanguage(locale);
        } else {
            info("preferred locale: [" + locale + "] not available on device.");
        }
        this.state.ttsChecked = true;
    }
}