Search in sources :

Example 1 with Reference

use of com.asksven.betterbatterystats.data.Reference in project BetterBatteryStats by asksven.

the class UpdateMediumWidgetService method onStart.

@Override
public void onStart(Intent intent, int startId) {
    if (LogSettings.DEBUG) {
        Log.d(TAG, "Service started");
    }
    // Create some random data
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this.getApplicationContext());
    int[] allWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
    Log.w(TAG, "From Intent" + String.valueOf(allWidgetIds.length));
    StatsProvider stats = StatsProvider.getInstance();
    // make sure to flush cache
    BatteryStatsProxy.getInstance(this).invalidate();
    for (int widgetId : allWidgetIds) {
        RemoteViews remoteViews = new RemoteViews(this.getApplicationContext().getPackageName(), R.layout.medium_widget_layout);
        // we change the bg color of the layout based on alpha from prefs
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        int opacity = sharedPrefs.getInt("large_widget_bg_opacity", 20);
        opacity = (255 * opacity) / 100;
        remoteViews.setInt(R.id.layout, "setBackgroundColor", (opacity << 24) & android.graphics.Color.BLACK);
        // retrieve stats
        String refFrom = sharedPrefs.getString("large_widget_default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
        boolean showPct = sharedPrefs.getBoolean("large_widget_show_pct", false);
        boolean showTitle = sharedPrefs.getBoolean("widget_show_stat_type", true);
        long timeAwake = 0;
        long timeDeepSleep = 0;
        long timeScreenOn = 0;
        long timeSince = 0;
        long sumPWakelocks = 0;
        long sumKWakelocks = 0;
        try {
            Reference currentRef = StatsProvider.getInstance().getUncachedPartialReference(0);
            Reference fromRef = ReferenceStore.getReferenceByName(refFrom, this);
            ArrayList<StatElement> otherStats = stats.getOtherUsageStatList(true, fromRef, false, true, currentRef);
            if ((otherStats == null) || (otherStats.size() == 1)) {
                // the desired stat type is unavailable, pick the alternate one and go on with that one
                refFrom = sharedPrefs.getString("widget_fallback_stat_type", Reference.BOOT_REF_FILENAME);
                fromRef = ReferenceStore.getReferenceByName(refFrom, this);
                otherStats = stats.getOtherUsageStatList(true, fromRef, false, true, currentRef);
            }
            if ((otherStats != null) && (otherStats.size() > 1)) {
                try {
                    timeAwake = ((Misc) stats.getElementByKey(otherStats, StatsProvider.LABEL_MISC_AWAKE)).getTimeOn();
                    timeScreenOn = ((Misc) stats.getElementByKey(otherStats, "Screen On")).getTimeOn();
                } catch (Exception e) {
                    timeAwake = 0;
                    timeScreenOn = 0;
                }
                timeSince = StatsProvider.getInstance().getSince(fromRef, currentRef);
                ArrayList<StatElement> pWakelockStats = stats.getWakelockStatList(true, fromRef, 0, 0, currentRef);
                sumPWakelocks = stats.sum(pWakelockStats);
                ArrayList<StatElement> kWakelockStats = stats.getKernelWakelockStatList(true, fromRef, 0, 0, currentRef);
                sumKWakelocks = stats.sum(kWakelockStats);
                Misc deepSleepStat = ((Misc) stats.getElementByKey(otherStats, "Deep Sleep"));
                if (deepSleepStat != null) {
                    timeDeepSleep = deepSleepStat.getTimeOn();
                } else {
                    timeDeepSleep = 0;
                }
                if (!showTitle) {
                    remoteViews.setInt(R.id.stat_type, "setVisibility", View.GONE);
                }
                // Set the text
                remoteViews.setTextViewText(R.id.stat_type, fromRef.getLabel());
                remoteViews.setTextViewText(R.id.since, DateUtils.formatDurationShort(timeSince));
                if (showPct) {
                    remoteViews.setTextViewText(R.id.awake, StringUtils.formatRatio(timeAwake, timeSince));
                    remoteViews.setTextViewText(R.id.deep_sleep, StringUtils.formatRatio(timeDeepSleep, timeSince));
                    remoteViews.setTextViewText(R.id.screen_on, StringUtils.formatRatio(timeScreenOn, timeSince));
                } else {
                    remoteViews.setTextViewText(R.id.awake, DateUtils.formatDurationShort(timeAwake));
                    remoteViews.setTextViewText(R.id.deep_sleep, DateUtils.formatDurationShort(timeDeepSleep));
                    remoteViews.setTextViewText(R.id.screen_on, DateUtils.formatDurationShort(timeScreenOn));
                }
                // and the font size
                float fontSize = Float.valueOf(sharedPrefs.getString("large_widget_font_size", "10"));
                remoteViews.setFloat(R.id.staticSince, "setTextSize", fontSize);
                remoteViews.setFloat(R.id.staticAwake, "setTextSize", fontSize);
                remoteViews.setFloat(R.id.staticDeepSleep, "setTextSize", fontSize);
                remoteViews.setFloat(R.id.staticScreenOn, "setTextSize", fontSize);
                remoteViews.setFloat(R.id.staticKWL, "setTextSize", fontSize);
                remoteViews.setFloat(R.id.staticPWL, "setTextSize", fontSize);
                remoteViews.setFloat(R.id.stat_type, "setTextSize", fontSize);
                remoteViews.setFloat(R.id.since, "setTextSize", fontSize);
                remoteViews.setFloat(R.id.awake, "setTextSize", fontSize);
                remoteViews.setFloat(R.id.deep_sleep, "setTextSize", fontSize);
                remoteViews.setFloat(R.id.screen_on, "setTextSize", fontSize);
                remoteViews.setFloat(R.id.kwl, "setTextSize", fontSize);
                remoteViews.setFloat(R.id.wl, "setTextSize", fontSize);
                if ((sumPWakelocks == 1) && (pWakelockStats.size() == 1)) {
                    // there was no reference
                    remoteViews.setTextViewText(R.id.wl, "n/a");
                } else {
                    if (showPct) {
                        remoteViews.setTextViewText(R.id.wl, StringUtils.formatRatio(sumPWakelocks, timeSince));
                    } else {
                        remoteViews.setTextViewText(R.id.wl, DateUtils.formatDurationShort(sumPWakelocks));
                    }
                }
                if ((sumKWakelocks == 1) && (kWakelockStats.size() == 1)) {
                    // there was no reference
                    remoteViews.setTextViewText(R.id.kwl, "n/a");
                } else {
                    if (showPct) {
                        remoteViews.setTextViewText(R.id.kwl, StringUtils.formatRatio(sumKWakelocks, timeSince));
                    } else {
                        remoteViews.setTextViewText(R.id.kwl, DateUtils.formatDurationShort(sumKWakelocks));
                    }
                }
            } else {
                // no stat available
                // Set the text
                String notAvailable = "n/a";
                if (fromRef != null) {
                    remoteViews.setTextViewText(R.id.stat_type, fromRef.m_fileName);
                } else {
                    remoteViews.setTextViewText(R.id.stat_type, notAvailable);
                }
                remoteViews.setTextViewText(R.id.since, notAvailable);
                remoteViews.setTextViewText(R.id.awake, notAvailable);
                remoteViews.setTextViewText(R.id.deep_sleep, notAvailable);
                remoteViews.setTextViewText(R.id.screen_on, notAvailable);
                remoteViews.setTextViewText(R.id.wl, notAvailable);
                remoteViews.setTextViewText(R.id.kwl, notAvailable);
            }
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + Log.getStackTraceString(e));
        } finally {
            if (LogSettings.DEBUG) {
                Log.d(TAG, "Since: " + DateUtils.formatDurationShort(timeSince));
                Log.d(TAG, "Awake: " + DateUtils.formatDurationShort(timeAwake));
                Log.d(TAG, "Deep Sleep: " + DateUtils.formatDurationShort(timeDeepSleep));
                Log.d(TAG, "Screen on: " + DateUtils.formatDurationShort(timeScreenOn));
                Log.d(TAG, "PWL: " + DateUtils.formatDurationShort(sumPWakelocks));
                Log.d(TAG, "KWL: " + DateUtils.formatDurationShort(sumKWakelocks));
            }
            // Register an onClickListener for the graph -> refresh
            Intent clickIntent = new Intent(this.getApplicationContext(), MediumWidgetProvider.class);
            clickIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
            clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.layout, pendingIntent);
            // Register an onClickListener for the widget -> call main activity
            Intent i = new Intent(Intent.ACTION_MAIN);
            PackageManager manager = getPackageManager();
            i = manager.getLaunchIntentForPackage(getPackageName());
            i.addCategory(Intent.CATEGORY_LAUNCHER);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            int stat = Integer.valueOf(sharedPrefs.getString("widget_default_stat", "0"));
            i.putExtra(StatsActivity.STAT, stat);
            i.putExtra(StatsActivity.STAT_TYPE_FROM, refFrom);
            i.putExtra(StatsActivity.STAT_TYPE_TO, Reference.CURRENT_REF_FILENAME);
            PendingIntent clickPI = PendingIntent.getActivity(this.getApplicationContext(), PI_CODE, i, PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.layout2, clickPI);
            appWidgetManager.updateAppWidget(widgetId, remoteViews);
        }
    }
    stopSelf();
    super.onStart(intent, startId);
}
Also used : SharedPreferences(android.content.SharedPreferences) Reference(com.asksven.betterbatterystats.data.Reference) AppWidgetManager(android.appwidget.AppWidgetManager) Misc(com.asksven.android.common.privateapiproxies.Misc) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) RemoteViews(android.widget.RemoteViews) PackageManager(android.content.pm.PackageManager) StatsProvider(com.asksven.betterbatterystats.data.StatsProvider) StatElement(com.asksven.android.common.privateapiproxies.StatElement) PendingIntent(android.app.PendingIntent)

Example 2 with Reference

use of com.asksven.betterbatterystats.data.Reference 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 3 with Reference

use of com.asksven.betterbatterystats.data.Reference in project BetterBatteryStats by asksven.

the class StatsActivity method setListViewAdapter.

/**
 * In order to refresh the ListView we need to re-create the Adapter
 * (should be the case but notifyDataSetChanged doesn't work so
 * we recreate and set a new one)
 */
private void setListViewAdapter() throws Exception {
    LinearLayout notificationPanel = (LinearLayout) findViewById(R.id.Notification);
    ListView listView = (ListView) findViewById(android.R.id.list);
    ArrayList<StatElement> myStats = StatsProvider.getInstance().getStatList(m_iStat, m_refFromName, m_iSorting, m_refToName);
    if ((myStats != null) && (!myStats.isEmpty())) {
        // check if notification
        if (myStats.get(0) instanceof Notification) {
            // Show Panel
            notificationPanel.setVisibility(View.VISIBLE);
            // Hide list
            listView.setVisibility(View.GONE);
            // set Text
            TextView tvNotification = (TextView) findViewById(R.id.TextViewNotification);
            tvNotification.setText(myStats.get(0).getName());
        } else {
            // hide Panel
            notificationPanel.setVisibility(View.GONE);
            // Show list
            listView.setVisibility(View.VISIBLE);
        }
    }
    // make sure we only instanciate when the reference does not exist
    if (m_listViewAdapter == null) {
        m_listViewAdapter = new StatsAdapter(this, myStats, StatsActivity.this);
        Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName, StatsActivity.this);
        Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName, StatsActivity.this);
        long sinceMs = StatsProvider.getInstance().getSince(myReferenceFrom, myReferenceTo);
        m_listViewAdapter.setTotalTime(sinceMs);
        setListAdapter(m_listViewAdapter);
    }
}
Also used : ListView(android.widget.ListView) Reference(com.asksven.betterbatterystats.data.Reference) StatElement(com.asksven.android.common.privateapiproxies.StatElement) TextView(android.widget.TextView) StatsAdapter(com.asksven.betterbatterystats.adapters.StatsAdapter) LinearLayout(android.widget.LinearLayout) Notification(com.asksven.android.common.privateapiproxies.Notification)

Example 4 with Reference

use of com.asksven.betterbatterystats.data.Reference in project BetterBatteryStats by asksven.

the class StatsActivity method getShareDialog.

public AlertDialog getShareDialog() {
    final ArrayList<Integer> selectedSaveActions = new ArrayList<Integer>();
    AlertDialog.Builder dialog = new AlertDialog.Builder(StatsActivity.this);
    /*
		dialog.setTitle("Alert");
		dialog.setMessage("Alert message to be shown");
		dialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		return dialog;
*/
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean saveDumpfile = sharedPrefs.getBoolean("save_dumpfile", true);
    boolean saveLogcat = sharedPrefs.getBoolean("save_logcat", false);
    boolean saveDmesg = sharedPrefs.getBoolean("save_dmesg", false);
    if (saveDumpfile) {
        selectedSaveActions.add(0);
    }
    if (saveLogcat) {
        selectedSaveActions.add(1);
    }
    if (saveDmesg) {
        selectedSaveActions.add(2);
    }
    // ----
    LinearLayout layout = new LinearLayout(this);
    LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.setLayoutParams(parms);
    layout.setGravity(Gravity.CLIP_VERTICAL);
    layout.setPadding(2, 2, 2, 2);
    final TextView editTitle = new TextView(StatsActivity.this);
    editTitle.setText(R.string.share_dialog_edit_title);
    editTitle.setPadding(40, 40, 40, 40);
    editTitle.setGravity(Gravity.LEFT);
    editTitle.setTextSize(20);
    final EditText editDescription = new EditText(StatsActivity.this);
    LinearLayout.LayoutParams tv1Params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    tv1Params.bottomMargin = 5;
    layout.addView(editTitle, tv1Params);
    layout.addView(editDescription, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    // ----
    // Set the dialog title
    dialog.setTitle(R.string.title_share_dialog).setMultiChoiceItems(R.array.saveAsLabels, new boolean[] { saveDumpfile, saveLogcat, saveDmesg }, new DialogInterface.OnMultiChoiceClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which, boolean isChecked) {
            if (isChecked) {
                // If the user checked the item, add it to the
                // selected items
                selectedSaveActions.add(which);
            } else if (selectedSaveActions.contains(which)) {
                // Else, if the item is already in the array,
                // remove it
                selectedSaveActions.remove(Integer.valueOf(which));
            }
        }
    }).setView(layout).setPositiveButton(R.string.label_button_share, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int id) {
            ArrayList<Uri> attachements = new ArrayList<Uri>();
            Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName, StatsActivity.this);
            Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName, StatsActivity.this);
            Reading reading = new Reading(StatsActivity.this, myReferenceFrom, myReferenceTo);
            // save as text is selected
            if (selectedSaveActions.contains(0)) {
                Uri fileUri = reading.writeDumpfile(StatsActivity.this, editDescription.getText().toString());
                File file = new File(fileUri.getPath());
                Uri shareableUri = FileProvider.getUriForFile(StatsActivity.this, StatsActivity.this.getPackageName() + ".provider", file);
                attachements.add(shareableUri);
            }
            // save logcat if selected
            if (selectedSaveActions.contains(1)) {
                Uri fileUri = StatsProvider.getInstance().writeLogcatToFile();
                File file = new File(fileUri.getPath());
                Uri shareableUri = FileProvider.getUriForFile(StatsActivity.this, StatsActivity.this.getPackageName() + ".provider", file);
                attachements.add(shareableUri);
            }
            // save dmesg if selected
            if (selectedSaveActions.contains(2)) {
                // attachements.add();
                Uri fileUri = StatsProvider.getInstance().writeDmesgToFile();
                File file = new File(fileUri.getPath());
                Uri shareableUri = FileProvider.getUriForFile(StatsActivity.this, StatsActivity.this.getPackageName() + ".provider", file);
                attachements.add(shareableUri);
            }
            if (!attachements.isEmpty()) {
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
                shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, attachements);
                shareIntent.setType("text/plain");
                startActivity(Intent.createChooser(shareIntent, "Share info to.."));
            }
        }
    }).setNeutralButton(R.string.label_button_save, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int id) {
            try {
                Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName, StatsActivity.this);
                Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName, StatsActivity.this);
                Reading reading = new Reading(StatsActivity.this, myReferenceFrom, myReferenceTo);
                // save as text is selected
                if (selectedSaveActions.contains(0)) {
                    reading.writeDumpfile(StatsActivity.this, editDescription.getText().toString());
                }
                // save logcat if selected
                if (selectedSaveActions.contains(1)) {
                    StatsProvider.getInstance().writeLogcatToFile();
                }
                // save dmesg if selected
                if (selectedSaveActions.contains(2)) {
                    StatsProvider.getInstance().writeDmesgToFile();
                }
                Snackbar.make(findViewById(android.R.id.content), getString(R.string.info_files_written) + ": " + StatsProvider.getWritableFilePath(), Snackbar.LENGTH_LONG).show();
            } catch (Exception e) {
                Log.e(TAG, "an error occured writing files: " + e.getMessage());
                Snackbar.make(findViewById(android.R.id.content), R.string.info_files_write_error, Snackbar.LENGTH_LONG).show();
            }
        }
    }).setNegativeButton(R.string.label_button_cancel, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int id) {
        // do nothing
        }
    });
    return dialog.create();
}
Also used : AlertDialog(android.app.AlertDialog) DialogInterface(android.content.DialogInterface) ArrayList(java.util.ArrayList) Uri(android.net.Uri) TextView(android.widget.TextView) EditText(android.widget.EditText) SharedPreferences(android.content.SharedPreferences) Reference(com.asksven.betterbatterystats.data.Reference) Intent(android.content.Intent) BatteryInfoUnavailableException(com.asksven.android.common.privateapiproxies.BatteryInfoUnavailableException) Reading(com.asksven.betterbatterystats.data.Reading) File(java.io.File) LinearLayout(android.widget.LinearLayout)

Example 5 with Reference

use of com.asksven.betterbatterystats.data.Reference in project BetterBatteryStats by asksven.

the class UpdateWidgetService method onHandleWork.

@Override
protected void onHandleWork(Intent intent) {
    // We have received work to do.  The system or framework is already
    // holding a wake lock for us at this point, so we can just go.
    Log.i(TAG, "onHandleWork: " + intent);
    if (LogSettings.DEBUG) {
        Log.d(TAG, "Service started");
    }
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this.getApplicationContext());
    int[] allWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
    StatsProvider stats = StatsProvider.getInstance();
    // make sure to flush cache
    BatteryStatsProxy proxy = BatteryStatsProxy.getInstance(this);
    if (proxy != null) {
        proxy.invalidate();
    }
    if (allWidgetIds != null) {
        if (allWidgetIds.length == 0) {
            Log.i(TAG, "allWidgetIds was empty");
        }
        for (int widgetId : allWidgetIds) {
            Log.i(TAG, "Update widget " + widgetId);
            RemoteViews remoteViews = new RemoteViews(this.getApplicationContext().getPackageName(), R.layout.widget);
            final int cellSize = 40;
            int width = 3;
            int height = 2;
            int widthDim = 0;
            int heightDim = 0;
            if (Build.VERSION.SDK_INT >= 16) {
                Bundle widgetOptions = appWidgetManager.getAppWidgetOptions(widgetId);
                width = AppWidget.sizeToCells(widgetOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH) - 10);
                height = AppWidget.sizeToCells(widgetOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT) + 10);
                widthDim = widgetOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH);
                heightDim = widgetOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT);
                Log.i(TAG, "[" + widgetId + "] height=" + height + " (" + widgetOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT) + ")");
                Log.i(TAG, "[" + widgetId + "] width=" + width + "(" + widgetOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH) + ")");
                remoteViews = new RemoteViews(this.getPackageName(), R.layout.widget_horz);
                if ((height <= 2) && (width <= 2)) {
                    // switch to image only
                    Log.i(TAG, "[" + widgetId + "] using image-only layout");
                    remoteViews = new RemoteViews(this.getPackageName(), R.layout.widget);
                } else if (height < width) {
                    // switch to horizontal
                    Log.i(TAG, "[" + widgetId + "] using horizontal layout");
                    remoteViews = new RemoteViews(this.getPackageName(), R.layout.widget_horz);
                } else {
                    // switch to vertical
                    Log.i(TAG, "[" + widgetId + "] using vertical layout");
                    remoteViews = new RemoteViews(this.getPackageName(), R.layout.widget_vert);
                }
            }
            // we change the bg color of the layout based on alpha from prefs
            SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
            int opacity = sharedPrefs.getInt("new_widget_bg_opacity", 20);
            opacity = (255 * opacity) / 100;
            remoteViews.setInt(R.id.background, "setBackgroundColor", (opacity << 24) & android.graphics.Color.BLACK);
            // remoteViews.setInt(R.id.layoutBackground, "setImageAlpha", opacity);
            long timeAwake = 0;
            long timeSince = 0;
            long timeScreenOn = 0;
            long timeDeepSleep = 0;
            long timePWL = 0;
            long timeKWL = 0;
            String refFrom = sharedPrefs.getString("new_widget_default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
            try {
                // retrieve stats
                Reference currentRef = StatsProvider.getInstance().getUncachedPartialReference(0);
                Reference fromRef = ReferenceStore.getReferenceByName(refFrom, this);
                ArrayList<StatElement> otherStats = stats.getOtherUsageStatList(true, fromRef, false, true, currentRef);
                if ((otherStats == null) || (otherStats.size() == 1)) {
                    // the desired stat type is unavailable, pick the alternate one and go on with that one
                    refFrom = sharedPrefs.getString("widget_fallback_stat_type", Reference.UNPLUGGED_REF_FILENAME);
                    fromRef = ReferenceStore.getReferenceByName(refFrom, this);
                    otherStats = stats.getOtherUsageStatList(true, fromRef, false, true, currentRef);
                }
                timeSince = StatsProvider.getInstance().getSince(fromRef, currentRef);
                if ((otherStats != null) && (otherStats.size() > 1)) {
                    Misc timeAwakeStat = (Misc) stats.getElementByKey(otherStats, StatsProvider.LABEL_MISC_AWAKE);
                    if (timeAwakeStat != null) {
                        timeAwake = timeAwakeStat.getTimeOn();
                    } else {
                        timeAwake = 0;
                    }
                    Misc timeScreenOnStat = (Misc) stats.getElementByKey(otherStats, "Screen On");
                    if (timeScreenOnStat != null) {
                        timeScreenOn = timeScreenOnStat.getTimeOn();
                    } else {
                        timeScreenOn = 0;
                    }
                    Misc deepSleepStat = ((Misc) stats.getElementByKey(otherStats, "Deep Sleep"));
                    if (deepSleepStat != null) {
                        timeDeepSleep = deepSleepStat.getTimeOn();
                    } else {
                        timeDeepSleep = 0;
                    }
                    ArrayList<StatElement> pWakelockStats = stats.getWakelockStatList(true, fromRef, 0, 0, currentRef);
                    timePWL = stats.sum(pWakelockStats);
                    ArrayList<StatElement> kWakelockStats = stats.getKernelWakelockStatList(true, fromRef, 0, 0, currentRef);
                    timeKWL = stats.sum(kWakelockStats);
                } else {
                }
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + Log.getStackTraceString(e));
            } finally {
                if (LogSettings.DEBUG) {
                    Log.d(TAG, "Reference: " + refFrom);
                    Log.d(TAG, "Since: " + DateUtils.formatShort(timeSince) + " " + AppWidget.formatDuration(timeSince) + " " + timeSince);
                    Log.d(TAG, "Awake: " + DateUtils.formatShort(timeAwake) + " " + AppWidget.formatDuration(timeAwake) + " " + timeAwake);
                    Log.d(TAG, "Screen on: " + DateUtils.formatShort(timeScreenOn) + " " + AppWidget.formatDuration(timeScreenOn) + " " + timeScreenOn);
                    Log.d(TAG, "Deep sleep: " + DateUtils.formatShort(timeDeepSleep) + " " + AppWidget.formatDuration(timeDeepSleep) + " " + timeDeepSleep);
                    Log.d(TAG, "KWL: " + DateUtils.formatShort(timeKWL) + " " + AppWidget.formatDuration(timeKWL) + " " + timeKWL);
                    Log.d(TAG, "PWL: " + DateUtils.formatShort(timePWL) + " " + AppWidget.formatDuration(timePWL) + " " + timePWL);
                }
                WidgetSummary graph = new WidgetSummary();
                graph.setAwake(timeAwake);
                graph.setScreenOn(timeScreenOn);
                graph.setDeepSleep(timeDeepSleep);
                graph.setDuration(timeSince);
                graph.setKWL(timeKWL);
                graph.setPWL(timePWL);
                DisplayMetrics metrics = this.getResources().getDisplayMetrics();
                Log.i(TAG, "Widget Dimensions: height=" + heightDim + " width=" + widthDim);
                Float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, Math.min(Math.max(Math.min(widthDim, heightDim), 80), 160), metrics);
                Log.i(TAG, "BitmapDip=" + Math.min(Math.max(Math.min(widthDim, heightDim), 80), 160) + ", BitmapPx=" + px.intValue());
                graph.setBitmapSizePx(px.intValue());
                remoteViews.setImageViewBitmap(R.id.imageView1, graph.getBitmap(this));
                boolean show_pwc_only = sharedPrefs.getBoolean("widget_show_pct", false);
                if (show_pwc_only) {
                    UpdateWidgetService.setValuesToPct(remoteViews, timeAwake, timeSince, timeScreenOn, timeDeepSleep, timePWL, timeKWL);
                } else {
                    if ((width > height) && (width <= 4)) {
                        UpdateWidgetService.setValuesToDuration(remoteViews, timeAwake, timeSince, timeScreenOn, timeDeepSleep, timePWL, timeKWL);
                    } else {
                        UpdateWidgetService.setValuesToDurationAndPct(remoteViews, timeAwake, timeSince, timeScreenOn, timeDeepSleep, timePWL, timeKWL);
                    }
                }
                boolean showColor = sharedPrefs.getBoolean("text_widget_color", true);
                UpdateWidgetService.setTextColor(remoteViews, showColor, this);
                // tap zones
                // Register an onClickListener for the graph -> refresh
                Intent clickIntentRefresh = new Intent(this.getApplicationContext(), AppWidget.class);
                clickIntentRefresh.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                clickIntentRefresh.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);
                PendingIntent pendingIntentRefresh = PendingIntent.getBroadcast(getApplicationContext(), 0, clickIntentRefresh, PendingIntent.FLAG_UPDATE_CURRENT);
                remoteViews.setOnClickPendingIntent(R.id.imageViewRefresh, pendingIntentRefresh);
                // Register an onClickListener for the widget -> call main activity
                Intent i = new Intent(Intent.ACTION_MAIN);
                PackageManager manager = getPackageManager();
                i = manager.getLaunchIntentForPackage(getPackageName());
                i.addCategory(Intent.CATEGORY_LAUNCHER);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                int stat = Integer.valueOf(sharedPrefs.getString("widget_default_stat", "0"));
                i.putExtra(StatsActivity.STAT, stat);
                i.putExtra(StatsActivity.STAT_TYPE_FROM, refFrom);
                i.putExtra(StatsActivity.STAT_TYPE_TO, Reference.CURRENT_REF_FILENAME);
                PendingIntent clickPI = PendingIntent.getActivity(this.getApplicationContext(), PI_CODE, i, PendingIntent.FLAG_UPDATE_CURRENT);
                remoteViews.setOnClickPendingIntent(R.id.imageView1, clickPI);
                appWidgetManager.updateAppWidget(widgetId, remoteViews);
            }
        }
    } else {
        Log.i(TAG, "allWidgetIds was null");
    }
    Log.i(TAG, "Completed service @ " + DateUtils.formatDurationLong(SystemClock.elapsedRealtime()));
}
Also used : SharedPreferences(android.content.SharedPreferences) Bundle(android.os.Bundle) Reference(com.asksven.betterbatterystats.data.Reference) AppWidgetManager(android.appwidget.AppWidgetManager) Misc(com.asksven.android.common.privateapiproxies.Misc) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) DisplayMetrics(android.util.DisplayMetrics) BatteryStatsProxy(com.asksven.android.common.privateapiproxies.BatteryStatsProxy) WidgetSummary(com.asksven.betterbatterystats.widgets.WidgetSummary) RemoteViews(android.widget.RemoteViews) PackageManager(android.content.pm.PackageManager) StatsProvider(com.asksven.betterbatterystats.data.StatsProvider) StatElement(com.asksven.android.common.privateapiproxies.StatElement) PendingIntent(android.app.PendingIntent)

Aggregations

Reference (com.asksven.betterbatterystats.data.Reference)13 SharedPreferences (android.content.SharedPreferences)10 Intent (android.content.Intent)9 StatElement (com.asksven.android.common.privateapiproxies.StatElement)9 StatsProvider (com.asksven.betterbatterystats.data.StatsProvider)8 PendingIntent (android.app.PendingIntent)7 PackageManager (android.content.pm.PackageManager)7 Misc (com.asksven.android.common.privateapiproxies.Misc)7 AppWidgetManager (android.appwidget.AppWidgetManager)6 RemoteViews (android.widget.RemoteViews)6 Bundle (android.os.Bundle)3 TextView (android.widget.TextView)3 Reading (com.asksven.betterbatterystats.data.Reading)3 DisplayMetrics (android.util.DisplayMetrics)2 LinearLayout (android.widget.LinearLayout)2 BatteryStatsProxy (com.asksven.android.common.privateapiproxies.BatteryStatsProxy)2 WidgetSummary (com.asksven.betterbatterystats.widgets.WidgetSummary)2 ArrayList (java.util.ArrayList)2 SuppressLint (android.annotation.SuppressLint)1 AlertDialog (android.app.AlertDialog)1