Search in sources :

Example 1 with ReferencesAdapter

use of com.asksven.betterbatterystats.adapters.ReferencesAdapter in project BetterBatteryStats by asksven.

the class StatsActivity method onItemSelected.

/**
 * Take the change of selection from the spinners into account and refresh the ListView
 * with the right data
 */
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
    // this method is fired even if nothing has changed so we nee to find that out
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean bChanged = false;
    // id is in the order of the spinners, 0 is stat, 1 is stat_type
    if (parent == (Spinner) findViewById(R.id.spinnerStatType)) {
        // detect if something changed
        String newStat = (String) ((ReferencesAdapter) parent.getAdapter()).getItemName(position);
        if ((m_refFromName != null) && (!m_refFromName.equals(newStat))) {
            if (LogSettings.DEBUG)
                Log.i(TAG, "Spinner from changed from " + m_refFromName + " to " + newStat);
            m_refFromName = newStat;
            bChanged = true;
            // we need to update the second spinner
            m_spinnerToAdapter.filterToSpinner(newStat, this);
            m_spinnerToAdapter.notifyDataSetChanged();
            // select the right element
            Spinner spinnerStatSampleEnd = (Spinner) findViewById(R.id.spinnerStatSampleEnd);
            if (spinnerStatSampleEnd.isShown()) {
                spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(m_refToName));
            } else {
                spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME));
            }
        } else {
            return;
        }
    } else if (parent == (Spinner) findViewById(R.id.spinnerStatSampleEnd)) {
        String newStat = (String) ((ReferencesAdapter) parent.getAdapter()).getItemName(position);
        if ((m_refFromName != null) && (!m_refToName.equals(newStat))) {
            if (LogSettings.DEBUG)
                Log.i(TAG, "Spinner to changed from " + m_refToName + " to " + newStat);
            m_refToName = newStat;
            bChanged = true;
        } else {
            return;
        }
    } else if (parent == (Spinner) findViewById(R.id.spinnerStat)) {
        int iNewStat = position;
        if (m_iStat != iNewStat) {
            m_iStat = iNewStat;
            bChanged = true;
        } else {
            return;
        }
    } else {
        Log.e(TAG, "ProcessStatsActivity.onItemSelected error. ID could not be resolved");
        Toast.makeText(this, getString(R.string.info_unknown_state), Toast.LENGTH_SHORT).show();
    }
    Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName, this);
    Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName, this);
    TextView tvSince = (TextView) findViewById(R.id.TextViewSince);
    long sinceMs = StatsProvider.getInstance().getSince(myReferenceFrom, myReferenceTo);
    if (sinceMs != -1) {
        String sinceText = DateUtils.formatDuration(sinceMs);
        sinceText += " " + StatsProvider.getInstance().getBatteryLevelFromTo(myReferenceFrom, myReferenceTo, true);
        tvSince.setText(sinceText);
        if (LogSettings.DEBUG)
            Log.i(TAG, "Since " + sinceText);
    } else {
        tvSince.setText("n/a ");
        if (LogSettings.DEBUG)
            Log.i(TAG, "Since: n/a ");
    }
    // m_listViewAdapter.notifyDataSetChanged();
    if (bChanged) {
        // as the source changed fetch the data
        doRefresh(false);
    }
}
Also used : SharedPreferences(android.content.SharedPreferences) Spinner(android.widget.Spinner) Reference(com.asksven.betterbatterystats.data.Reference) TextView(android.widget.TextView) ReferencesAdapter(com.asksven.betterbatterystats.adapters.ReferencesAdapter)

Example 2 with ReferencesAdapter

use of com.asksven.betterbatterystats.adapters.ReferencesAdapter in project BetterBatteryStats by asksven.

the class EditActivity method onCreate.

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.locale_plugin_main);
    /*
         * To help the user keep context, the title shows the host's name and the subtitle
         * shows the plug-in's name.
         */
    CharSequence callingApplicationLabel = null;
    try {
        callingApplicationLabel = getPackageManager().getApplicationLabel(getPackageManager().getApplicationInfo(getCallingPackage(), 0));
    } catch (final PackageManager.NameNotFoundException e) {
        // $NON-NLS-1$
        Log.e(TAG, "Calling package couldn't be found %s", e);
    }
    if (null != callingApplicationLabel) {
        setTitle(callingApplicationLabel);
    }
    getSupportActionBar().setSubtitle(R.string.plugin_name);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    // populate the spinner
    Spinner spinner = (Spinner) findViewById(R.id.spinnerStatType);
    m_spinnerAdapter = new ReferencesAdapter(this, android.R.layout.simple_spinner_item);
    m_spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(m_spinnerAdapter);
}
Also used : PackageManager(android.content.pm.PackageManager) Spinner(android.widget.Spinner) ReferencesAdapter(com.asksven.betterbatterystats.adapters.ReferencesAdapter)

Example 3 with ReferencesAdapter

use of com.asksven.betterbatterystats.adapters.ReferencesAdapter in project BetterBatteryStats by asksven.

the class StatsActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    super.onCreate(savedInstanceState);
    // HockeyApp
    try {
        MetricsManager.register(getApplication());
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }
    // Log.i(TAG, "OnCreated called");
    setContentView(R.layout.stats);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle(getString(R.string.app_name));
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayUseLogoEnabled(false);
    // set debugging
    if (sharedPrefs.getBoolean("debug_logging", false)) {
        LogSettings.DEBUG = true;
        CommonLogSettings.DEBUG = true;
    } else {
        LogSettings.DEBUG = false;
        CommonLogSettings.DEBUG = false;
    }
    swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
    swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            doRefresh(true);
        }
    });
    // /////////////////////////////////////////////
    // check if we have a new release
    // /////////////////////////////////////////////
    // if yes do some migration (if required) and show release notes
    String strLastRelease = sharedPrefs.getString("last_release", "0");
    String strCurrentRelease = "";
    try {
        PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        strCurrentRelease = Integer.toString(pinfo.versionCode);
    } catch (Exception e) {
    // nop strCurrentRelease is set to ""
    }
    // if root is available use it
    boolean ignoreSystemApp = sharedPrefs.getBoolean("ignore_system_app", false);
    // Grant permissions if they are missing and root is available
    if (!SysUtils.hasBatteryStatsPermission(this) || !SysUtils.hasDumpsysPermission(this) || !SysUtils.hasPackageUsageStatsPermission(this)) {
        if ((!ignoreSystemApp && RootShell.getInstance().hasRootPermissions())) {
            // attempt to set perms using pm-comand
            Log.i(TAG, "attempting to grant perms with 'pm grant'");
            String pkg = this.getPackageName();
            RootShell.getInstance().run("pm grant " + pkg + " android.permission.BATTERY_STATS");
            RootShell.getInstance().run("pm grant " + pkg + " android.permission.DUMP");
            RootShell.getInstance().run("pm grant " + pkg + " android.permission.PACKAGE_USAGE_STATS");
            if (SysUtils.hasBatteryStatsPermission(this)) {
                Log.i(TAG, "succeeded");
            } else {
                Log.i(TAG, "failed");
            }
        }
    }
    // Package usage stats were introduced in SDK21 so we need to make the distinction
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // show install as system app screen if root available but perms missing
        if (!SysUtils.hasBatteryStatsPermission(this) || !SysUtils.hasDumpsysPermission(this) || !SysUtils.hasPackageUsageStatsPermission(this)) {
            Intent intentSystemApp = new Intent(this, SystemAppActivity.class);
            this.startActivity(intentSystemApp);
        }
    } else {
        if (!SysUtils.hasBatteryStatsPermission(this) || !SysUtils.hasDumpsysPermission(this)) {
            Intent intentSystemApp = new Intent(this, SystemAppActivity.class);
            this.startActivity(intentSystemApp);
        }
    }
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    // first start
    if (strLastRelease.equals("0")) {
        boolean firstLaunch = !prefs.getBoolean("launched", false);
        if (firstLaunch) {
            // Save that the app has been launched
            SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean("launched", true);
            editor.commit();
            // start service to persist reference
            Intent serviceIntent = new Intent(this, WriteUnpluggedReferenceService.class);
            this.startService(serviceIntent);
            // refresh widgets
            Intent intentRefreshWidgets = new Intent(LargeWidgetProvider.WIDGET_UPDATE);
            this.sendBroadcast(intentRefreshWidgets);
        }
        SharedPreferences.Editor updater = sharedPrefs.edit();
        updater.putString("last_release", strCurrentRelease);
        updater.commit();
    } else if (!strLastRelease.equals(strCurrentRelease)) {
        // save the current release to properties so that the dialog won't be shown till next version
        SharedPreferences.Editor updater = sharedPrefs.edit();
        updater.putString("last_release", strCurrentRelease);
        updater.commit();
        // we don't need to delete refs as long as we don't change the database schema
        // Toast.makeText(this, getString(R.string.info_deleting_refs), Toast.LENGTH_SHORT).show();
        // ReferenceStore.deleteAllRefs(this);
        // Intent i = new Intent(this, WriteBootReferenceService.class);
        // this.startService(i);
        // i = new Intent(this, WriteUnpluggedReferenceService.class);
        // this.startService(i);
        ChangeLog cl = new ChangeLog(this);
        cl.getLogDialog().show();
    }
    // /////////////////////////////////////////////
    // retrieve default selections for spinners
    // if none were passed
    // /////////////////////////////////////////////
    m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0"));
    m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
    if (!ReferenceStore.hasReferenceByName(m_refFromName, this)) {
        m_refFromName = Reference.BOOT_REF_FILENAME;
        Toast.makeText(this, getString(R.string.info_fallback_to_boot), Toast.LENGTH_SHORT).show();
    }
    if (LogSettings.DEBUG)
        Log.i(TAG, "onCreate state from preferences: refFrom=" + m_refFromName + " refTo=" + m_refToName);
    try {
        // recover any saved state
        if ((savedInstanceState != null) && (!savedInstanceState.isEmpty())) {
            m_iStat = (Integer) savedInstanceState.getSerializable("stat");
            m_refFromName = (String) savedInstanceState.getSerializable("stattypeFrom");
            m_refToName = (String) savedInstanceState.getSerializable("stattypeTo");
            if (LogSettings.DEBUG)
                Log.i(TAG, "onCreate retrieved saved state: refFrom=" + m_refFromName + " refTo=" + m_refToName);
        }
    } catch (Exception e) {
        m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0"));
        m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
        Log.e(TAG, "Exception: " + e.getMessage());
        DataStorage.LogToFile(LOGFILE, "Exception in onCreate restoring Bundle");
        DataStorage.LogToFile(LOGFILE, e.getMessage());
        DataStorage.LogToFile(LOGFILE, e.getStackTrace());
        Toast.makeText(this, getString(R.string.info_state_recovery_error), Toast.LENGTH_SHORT).show();
    }
    // Handle the case the Activity was called from an intent with paramaters
    Bundle extras = getIntent().getExtras();
    if ((extras != null) && !extras.isEmpty()) {
        // Override if some values were passed to the intent
        if (extras.containsKey(StatsActivity.STAT))
            m_iStat = extras.getInt(StatsActivity.STAT);
        if (extras.containsKey(StatsActivity.STAT_TYPE_FROM))
            m_refFromName = extras.getString(StatsActivity.STAT_TYPE_FROM);
        if (extras.containsKey(StatsActivity.STAT_TYPE_TO))
            m_refToName = extras.getString(StatsActivity.STAT_TYPE_TO);
        if (LogSettings.DEBUG)
            Log.i(TAG, "onCreate state from extra: refFrom=" + m_refFromName + " refTo=" + m_refToName);
        boolean bCalledFromNotification = extras.getBoolean(StatsActivity.FROM_NOTIFICATION, false);
        // Clear the notifications that was clicked to call the activity
        if (bCalledFromNotification) {
            NotificationManager nM = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
            nM.cancel(EventWatcherService.NOTFICATION_ID);
        }
    }
    // Spinner for selecting the stat
    Spinner spinnerStat = (Spinner) findViewById(R.id.spinnerStat);
    ArrayAdapter spinnerStatAdapter = ArrayAdapter.createFromResource(this, R.array.stats, // android.R.layout.simple_spinner_item);
    R.layout.bbs_spinner_layout);
    // android.R.layout.simple_spinner_dropdown_item);
    spinnerStatAdapter.setDropDownViewResource(R.layout.bbs_spinner_dropdown_item);
    spinnerStat.setAdapter(spinnerStatAdapter);
    // setSelection MUST be called after setAdapter
    spinnerStat.setSelection(m_iStat);
    spinnerStat.setOnItemSelectedListener(this);
    // /////////////////////////////////////////////
    // Spinner for Selecting the Stat type
    // /////////////////////////////////////////////
    Spinner spinnerStatType = (Spinner) findViewById(R.id.spinnerStatType);
    // android.R.layout.simple_spinner_item);
    m_spinnerFromAdapter = new ReferencesAdapter(this, R.layout.bbs_spinner_layout);
    // android.R.layout.simple_spinner_dropdown_item);
    m_spinnerFromAdapter.setDropDownViewResource(R.layout.bbs_spinner_dropdown_item);
    spinnerStatType.setAdapter(m_spinnerFromAdapter);
    try {
        this.setListViewAdapter();
    } catch (BatteryInfoUnavailableException e) {
        Log.e(TAG, "Exception: " + Log.getStackTraceString(e));
        Snackbar.make(findViewById(android.R.id.content), R.string.info_service_connection_error, Snackbar.LENGTH_LONG).show();
    // Toast.makeText(this,
    // getString(R.string.info_service_connection_error),
    // Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        // Log.e(TAG, e.getMessage(), e.fillInStackTrace());
        Log.e(TAG, "Exception: " + Log.getStackTraceString(e));
        Toast.makeText(this, getString(R.string.info_unknown_stat_error), Toast.LENGTH_LONG).show();
    }
    // setSelection MUST be called after setAdapter
    spinnerStatType.setSelection(m_spinnerFromAdapter.getPosition(m_refFromName));
    spinnerStatType.setOnItemSelectedListener(this);
    // /////////////////////////////////////////////
    // Spinner for Selecting the end sample
    // /////////////////////////////////////////////
    Spinner spinnerStatSampleEnd = (Spinner) findViewById(R.id.spinnerStatSampleEnd);
    // android.R.layout.simple_spinner_item);
    m_spinnerToAdapter = new ReferencesAdapter(this, R.layout.bbs_spinner_layout);
    // android.R.layout.simple_spinner_dropdown_item);
    m_spinnerToAdapter.setDropDownViewResource(R.layout.bbs_spinner_dropdown_item);
    spinnerStatSampleEnd.setVisibility(View.VISIBLE);
    spinnerStatSampleEnd.setAdapter(m_spinnerToAdapter);
    // setSelection must be called after setAdapter
    if ((m_refToName != null) && !m_refToName.equals("")) {
        int pos = m_spinnerToAdapter.getPosition(m_refToName);
        spinnerStatSampleEnd.setSelection(pos);
    } else {
        spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME));
    }
    spinnerStatSampleEnd.setOnItemSelectedListener(this);
    // /////////////////////////////////////////////
    // sorting
    // /////////////////////////////////////////////
    m_iSorting = 0;
    // log reference store
    ReferenceStore.logReferences(this);
    if (LogSettings.DEBUG) {
        Log.i(TAG, "onCreate final state: refFrom=" + m_refFromName + " refTo=" + m_refToName);
        Log.i(TAG, "OnCreated end");
    }
}
Also used : NotificationManager(android.app.NotificationManager) SharedPreferences(android.content.SharedPreferences) PackageInfo(android.content.pm.PackageInfo) Bundle(android.os.Bundle) Spinner(android.widget.Spinner) Intent(android.content.Intent) SwipeRefreshLayout(android.support.v4.widget.SwipeRefreshLayout) BatteryInfoUnavailableException(com.asksven.android.common.privateapiproxies.BatteryInfoUnavailableException) ReferencesAdapter(com.asksven.betterbatterystats.adapters.ReferencesAdapter) ChangeLog(de.cketti.library.changelog.ChangeLog) BatteryInfoUnavailableException(com.asksven.android.common.privateapiproxies.BatteryInfoUnavailableException) ArrayAdapter(android.widget.ArrayAdapter) Toolbar(android.support.v7.widget.Toolbar)

Aggregations

Spinner (android.widget.Spinner)3 ReferencesAdapter (com.asksven.betterbatterystats.adapters.ReferencesAdapter)3 SharedPreferences (android.content.SharedPreferences)2 NotificationManager (android.app.NotificationManager)1 Intent (android.content.Intent)1 PackageInfo (android.content.pm.PackageInfo)1 PackageManager (android.content.pm.PackageManager)1 Bundle (android.os.Bundle)1 SwipeRefreshLayout (android.support.v4.widget.SwipeRefreshLayout)1 Toolbar (android.support.v7.widget.Toolbar)1 ArrayAdapter (android.widget.ArrayAdapter)1 TextView (android.widget.TextView)1 BatteryInfoUnavailableException (com.asksven.android.common.privateapiproxies.BatteryInfoUnavailableException)1 Reference (com.asksven.betterbatterystats.data.Reference)1 ChangeLog (de.cketti.library.changelog.ChangeLog)1