Search in sources :

Example 21 with StatElement

use of com.asksven.android.common.privateapiproxies.StatElement in project BetterBatteryStats by asksven.

the class UpdateSmallWidgetService method onStart.

@Override
public void onStart(Intent intent, int startId) {
    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.getInstance(this).invalidate();
    for (int widgetId : allWidgetIds) {
        RemoteViews remoteViews = new RemoteViews(this.getApplicationContext().getPackageName(), R.layout.small_widget_layout);
        // make sure to make the widget visible as it may have been previously hidden
        remoteViews.setInt(R.id.graph, "setVisibility", View.VISIBLE);
        // we change the bg color of the layout based on alpha from prefs
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        int opacity = sharedPrefs.getInt("small_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("small_widget_default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
        boolean showTitle = sharedPrefs.getBoolean("widget_show_stat_type", true);
        long timeAwake = 0;
        long timeScreenOn = 0;
        long timeDeepSleep = 0;
        if (!showTitle) {
            remoteViews.setInt(R.id.stat_type, "setVisibility", View.GONE);
        }
        remoteViews.setTextViewText(R.id.stat_type, Reference.getLabel(refFrom));
        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.UNPLUGGED_REF_FILENAME);
                fromRef = ReferenceStore.getReferenceByName(refFrom, this);
                otherStats = stats.getOtherUsageStatList(true, fromRef, false, true, 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;
                }
            } else {
                // no proper reference found
                remoteViews.setInt(R.id.graph, "setVisibility", View.GONE);
            }
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + Log.getStackTraceString(e));
        } finally {
            if (LogSettings.DEBUG) {
                Log.d(TAG, "Awake: " + DateUtils.formatDuration(timeAwake));
                Log.d(TAG, "Screen on: " + DateUtils.formatDuration(timeScreenOn));
                Log.d(TAG, "Deep sleep: " + DateUtils.formatDuration(timeDeepSleep));
            }
            WidgetBattery graph = new WidgetBattery();
            graph.setAwake(timeAwake);
            graph.setScreenOn(timeScreenOn);
            graph.setDeepSleep(timeDeepSleep);
            remoteViews.setImageViewBitmap(R.id.graph, graph.getBitmap(this));
            // tap behavior depends on preferences
            boolean refreshOnTap = sharedPrefs.getBoolean("small_widget_refresh_on_tap", true);
            // Register an onClickListener for the graph -> refresh
            Intent clickIntent = new Intent(this.getApplicationContext(), SmallWidgetProvider.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);
            if (refreshOnTap) {
                remoteViews.setOnClickPendingIntent(R.id.layout, pendingIntent);
            } else {
                remoteViews.setOnClickPendingIntent(R.id.stat_type, 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.layout, clickPI);
            }
            appWidgetManager.updateAppWidget(widgetId, remoteViews);
        }
    }
    stopSelf();
    super.onStart(intent, startId);
}
Also used : WidgetBattery(com.asksven.betterbatterystats.widgets.WidgetBattery) 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 22 with StatElement

use of com.asksven.android.common.privateapiproxies.StatElement in project BetterBatteryStats by asksven.

the class UpdateWidgetService method onStart.

@SuppressLint("NewApi")
@Override
public void onStart(Intent intent, int startId) {
    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.getInstance(this).invalidate();
    for (int widgetId : allWidgetIds) {
        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 = (widgetOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH)) / cellSize;
            // height = (widgetOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT)) / cellSize;
            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 {
            // no proper reference found
            // remoteViews.setInt(R.id.graph, "setVisibility", View.GONE);
            }
        } 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();
            // Float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, Math.min(width, height) * cellSize, metrics);
            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));
            // Show % depending on width and if vertical or horz
            if ((width > height) && (width <= 4)) {
                remoteViews.setTextViewText(R.id.textViewAwakeVal, AppWidget.formatDuration(timeAwake - timeScreenOn));
                remoteViews.setTextViewText(R.id.textViewDeepSleepVal, AppWidget.formatDuration(timeDeepSleep));
                remoteViews.setTextViewText(R.id.textViewScreenOnVal, AppWidget.formatDuration(timeScreenOn));
                remoteViews.setTextViewText(R.id.textViewKWLVal, AppWidget.formatDuration(timeKWL));
                remoteViews.setTextViewText(R.id.textViewPWLVal, AppWidget.formatDuration(timePWL));
            } else {
                remoteViews.setTextViewText(R.id.textViewAwakeVal, AppWidget.formatDuration(timeAwake - timeScreenOn) + " (" + StringUtils.formatRatio(timeAwake - timeScreenOn, timeSince) + ")");
                remoteViews.setTextViewText(R.id.textViewDeepSleepVal, AppWidget.formatDuration(timeDeepSleep) + " (" + StringUtils.formatRatio(timeDeepSleep, timeSince) + ")");
                remoteViews.setTextViewText(R.id.textViewScreenOnVal, AppWidget.formatDuration(timeScreenOn) + " (" + StringUtils.formatRatio(timeScreenOn, timeSince) + ")");
                remoteViews.setTextViewText(R.id.textViewKWLVal, AppWidget.formatDuration(timeKWL) + " (" + StringUtils.formatRatio(timeKWL, timeSince) + ")");
                remoteViews.setTextViewText(R.id.textViewPWLVal, AppWidget.formatDuration(timePWL) + " (" + StringUtils.formatRatio(timePWL, timeSince) + ")");
            }
            // 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);
        }
    }
    stopSelf();
    super.onStart(intent, startId);
}
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) SuppressLint(android.annotation.SuppressLint) 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) SuppressLint(android.annotation.SuppressLint)

Example 23 with StatElement

use of com.asksven.android.common.privateapiproxies.StatElement in project BetterBatteryStats by asksven.

the class StatsProvider method getWakelockStatList.

/**
 * Get the Wakelock Stat to be displayed
 *
 * @param bFilter
 *            defines if zero-values should be filtered out
 * @return a List of Wakelocks sorted by duration (descending)
 * @throws Exception
 *             if the API call failed
 */
public ArrayList<StatElement> getWakelockStatList(boolean bFilter, Reference refFrom, int iPctType, int iSort, Reference refTo) throws Exception {
    Context ctx = BbsApplication.getAppContext();
    // this is the best practice described here: https://android-developers.googleblog.com/2011/03/identifying-app-installations.html
    String entropy = Settings.Secure.getString(ctx.getContentResolver(), Settings.Secure.ANDROID_ID);
    ArrayList<StatElement> myStats = new ArrayList<StatElement>();
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
    if (!SysUtils.hasBatteryStatsPermission(ctx)) {
        myStats.add(new Notification(ctx.getString(R.string.NO_PERM_ERR)));
        return myStats;
    }
    if ((refFrom == null) || (refTo == null)) {
        myStats.add(new Notification(ctx.getString(R.string.NO_REF_ERR)));
        return myStats;
    }
    ArrayList<StatElement> myWakelocks = null;
    if ((refTo.m_refWakelocks != null) && (!refTo.m_refWakelocks.isEmpty())) {
        myWakelocks = refTo.m_refWakelocks;
    } else {
        myStats.add(new Notification(ctx.getString(R.string.NO_STATS)));
        return myStats;
    }
    ArrayList<Wakelock> myRetWakelocks = new ArrayList<Wakelock>();
    String strCurrent = myWakelocks.toString();
    String strRef = "";
    String strRefDescr = "";
    if (LogSettings.DEBUG) {
        if (refFrom != null) {
            strRefDescr = refFrom.whoAmI();
            if (refFrom.m_refWakelocks != null) {
                strRef = refFrom.m_refWakelocks.toString();
            } else {
                strRef = "Wakelocks is null";
            }
        } else {
            strRefDescr = "Reference is null";
        }
        Log.d(TAG, "Processing kernel wakelocks from " + refFrom.m_fileName + " to " + refTo.m_fileName);
        Log.d(TAG, "Reference used: " + strRefDescr);
        Log.d(TAG, "It is now " + DateUtils.now());
        Log.d(TAG, "Substracting " + strRef);
        Log.d(TAG, "from " + strCurrent);
    }
    for (int i = 0; i < myWakelocks.size(); i++) {
        Wakelock wl = ((Wakelock) myWakelocks.get(i)).clone(entropy);
        if ((!bFilter) || ((wl.getDuration() / 1000) > 0)) {
            // we must distinguish two situations
            // a) we use custom stat type
            // b) we use regular stat type
            wl.substractFromRef(refFrom.m_refWakelocks);
            // threshold
            if ((!bFilter) || ((wl.getDuration() / 1000) > 0)) {
                myRetWakelocks.add(wl);
            } else {
                if (LogSettings.DEBUG) {
                    Log.i(TAG, "Skipped " + wl.toString() + " because duration < 1s");
                }
            }
        }
    }
    if (LogSettings.DEBUG) {
        Log.i(TAG, "Result has " + myRetWakelocks.size() + " entries");
    }
    // com.asksven.android.common.privateapiproxies.Walkelock.compareTo
    switch(iSort) {
        case 0:
            // by Duration
            Comparator<Wakelock> myCompTime = new Wakelock.WakelockTimeComparator();
            Collections.sort(myRetWakelocks, myCompTime);
            break;
        case 1:
            // by Count
            Comparator<Wakelock> myCompCount = new Wakelock.WakelockCountComparator();
            Collections.sort(myRetWakelocks, myCompCount);
            break;
    }
    for (int i = 0; i < myRetWakelocks.size(); i++) {
        myStats.add((StatElement) myRetWakelocks.get(i));
    }
    if (LogSettings.DEBUG) {
        Log.d(TAG, "Result " + myStats.toString());
    }
    return myStats;
}
Also used : Context(android.content.Context) SharedPreferences(android.content.SharedPreferences) ArrayList(java.util.ArrayList) Notification(com.asksven.android.common.privateapiproxies.Notification) SuppressLint(android.annotation.SuppressLint) Wakelock(com.asksven.android.common.privateapiproxies.Wakelock) NativeKernelWakelock(com.asksven.android.common.privateapiproxies.NativeKernelWakelock) StatElement(com.asksven.android.common.privateapiproxies.StatElement)

Example 24 with StatElement

use of com.asksven.android.common.privateapiproxies.StatElement in project BetterBatteryStats by asksven.

the class StatsProvider method getOtherUsageStatList.

/**
 * Get the Other Usage Stat to be displayed
 *
 * @param bFilter
 *            defines if zero-values should be filtered out
 * @return a List of Other usages sorted by duration (descending)
 * @throws Exception
 *             if the API call failed
 */
public ArrayList<StatElement> getOtherUsageStatList(boolean bFilter, Reference refFrom, boolean bFilterView, boolean bWidget, Reference refTo) throws Exception {
    Context ctx = BbsApplication.getAppContext();
    ArrayList<StatElement> myStats = new ArrayList<StatElement>();
    // if on of the refs is null return
    if ((refFrom == null) || (refTo == null)) {
        myStats.add(new Notification(ctx.getString(R.string.NO_REF_ERR)));
        return myStats;
    }
    // List to store the other usages to
    ArrayList<StatElement> myUsages = new ArrayList<StatElement>();
    if ((refTo.m_refOther != null) && (!refTo.m_refOther.isEmpty())) {
        myUsages = refTo.m_refOther;
    } else {
        myStats.add(new Notification(ctx.getString(R.string.NO_STATS)));
        return myStats;
    }
    String strRefFrom = "";
    String strRefTo = "";
    String strRefFromDescr = "";
    String strRefToDescr = "";
    if (LogSettings.DEBUG) {
        if (refFrom != null) {
            strRefFromDescr = refFrom.whoAmI();
            if (refFrom.m_refOther != null) {
                strRefFrom = refFrom.m_refOther.toString();
            } else {
                strRefFrom = "Other is null";
            }
        }
        if (refTo != null) {
            strRefToDescr = refTo.whoAmI();
            if (refTo.m_refOther != null) {
                strRefTo = refTo.m_refOther.toString();
            } else {
                strRefTo = "Other is null";
            }
        }
        Log.d(TAG, "Processing Other from " + refFrom.m_fileName + " to " + refTo.m_fileName);
        Log.d(TAG, "Reference from: " + strRefFromDescr);
        Log.d(TAG, "Reference to: " + strRefToDescr);
        Log.d(TAG, "It is now " + DateUtils.now());
        Log.d(TAG, "Substracting " + strRefFrom);
        Log.d(TAG, "from " + strRefTo);
    }
    for (int i = 0; i < myUsages.size(); i++) {
        Misc usage = ((Misc) myUsages.get(i)).clone();
        if (LogSettings.DEBUG) {
            Log.d(TAG, "Current value: " + usage.getName() + " " + usage.getData(StatsProvider.getInstance().getSince(refFrom, refTo)));
        }
        if ((!bFilter) || (usage.getTimeOn() > 0)) {
            usage.substractFromRef(refFrom.m_refOther);
            if ((!bFilter) || (usage.getTimeOn() > 0)) {
                if (LogSettings.DEBUG) {
                    Log.d(TAG, "Result value: " + usage.getName() + " " + usage.getData(StatsProvider.getInstance().getSince(refFrom, refTo)));
                }
                myStats.add((StatElement) usage);
            }
        }
    }
    return myStats;
}
Also used : Context(android.content.Context) StatElement(com.asksven.android.common.privateapiproxies.StatElement) ArrayList(java.util.ArrayList) Misc(com.asksven.android.common.privateapiproxies.Misc) Notification(com.asksven.android.common.privateapiproxies.Notification) SuppressLint(android.annotation.SuppressLint)

Example 25 with StatElement

use of com.asksven.android.common.privateapiproxies.StatElement in project BetterBatteryStats by asksven.

the class StatsProvider method getCurrentOtherUsageStatList.

public ArrayList<StatElement> getCurrentOtherUsageStatList(boolean bFilter, boolean bFilterView, boolean bWidget) throws Exception {
    Context ctx = BbsApplication.getAppContext();
    ArrayList<StatElement> myStats = new ArrayList<StatElement>();
    // List to store the other usages to
    ArrayList<StatElement> myUsages = new ArrayList<StatElement>();
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
    BatteryStatsProxy mStats = BatteryStatsProxy.getInstance(ctx);
    long rawRealtime = SystemClock.elapsedRealtime() * 1000;
    long uptime = SystemClock.uptimeMillis();
    long elaspedRealtime = rawRealtime / 1000;
    long batteryRealtime = 0;
    try {
        batteryRealtime = mStats.getBatteryRealtime(rawRealtime);
    } catch (Exception e) {
        Log.e(TAG, "An exception occured processing battery realtime. Message: " + e.getMessage());
        Log.e(TAG, "Exception: " + Log.getStackTraceString(e));
    }
    int statsType = 0;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        statsType = BatteryStatsTypesLolipop.STATS_CURRENT;
    } else {
        statsType = BatteryStatsTypes.STATS_CURRENT;
    }
    long whichRealtime = mStats.computeBatteryRealtime(rawRealtime, statsType) / 1000;
    long timeBatteryUp = mStats.computeBatteryUptime(SystemClock.uptimeMillis() * 1000, statsType) / 1000;
    if (CommonLogSettings.DEBUG) {
        Log.i(TAG, "whichRealtime = " + whichRealtime + " batteryRealtime = " + batteryRealtime + " timeBatteryUp=" + timeBatteryUp);
    }
    long timeScreenOn = mStats.getScreenOnTime(batteryRealtime, statsType) / 1000;
    long timePhoneOn = mStats.getPhoneOnTime(batteryRealtime, statsType) / 1000;
    long timeWifiOn = 0;
    long timeWifiRunning = 0;
    if (sharedPrefs.getBoolean("show_other_wifi", true) && !bWidget) {
        try {
            timeWifiOn = mStats.getWifiOnTime(batteryRealtime, statsType) / 1000;
            timeWifiRunning = mStats.getGlobalWifiRunningTime(batteryRealtime, statsType) / 1000;
        } catch (BatteryInfoUnavailableException e) {
            timeWifiOn = 0;
            timeWifiRunning = 0;
            Log.e(TAG, "A batteryinfo error occured while retrieving Wifi data");
        }
    }
    long timeBluetoothOn = 0;
    if (sharedPrefs.getBoolean("show_other_bt", true) && !bWidget) {
        try {
            if (Build.VERSION.SDK_INT >= 21) {
                timeBluetoothOn = mStats.getBluetoothInStateTime(ctx, statsType) / 1000;
            } else {
                timeBluetoothOn = mStats.getBluetoothOnTime(batteryRealtime, statsType) / 1000;
            }
        } catch (BatteryInfoUnavailableException e) {
            timeBluetoothOn = 0;
            Log.e(TAG, "A batteryinfo error occured while retrieving BT data");
        }
    }
    long interactiveTime = 0;
    long powerSaveModeEnabledTime = 0;
    long deviceIdleModeEnabledTime = 0;
    long getDeviceIdlingTime = 0;
    if (sharedPrefs.getBoolean("show_other_doze", true) && !bWidget) {
        try {
            if (Build.VERSION.SDK_INT >= 21) {
                interactiveTime = mStats.getInteractiveTime(batteryRealtime, statsType) / 1000;
                powerSaveModeEnabledTime = mStats.getPowerSaveModeEnabledTime(batteryRealtime, statsType) / 1000;
                deviceIdleModeEnabledTime = mStats.getDeviceIdleModeEnabledTime(batteryRealtime, statsType) / 1000;
                // these are not available anymore from SDK24 on
                if (Build.VERSION.SDK_INT <= 23) {
                    getDeviceIdlingTime = mStats.getDeviceIdlingTime(batteryRealtime, statsType) / 1000;
                } else {
                // we need to switch to getDeviceIdleModeTime
                }
            }
        } catch (BatteryInfoUnavailableException e) {
            timeBluetoothOn = 0;
            Log.e(TAG, "A batteryinfo error occured while retrieving doze mode data");
        }
    }
    long syncTime = 0;
    try {
        if ((Build.VERSION.SDK_INT >= 21) && (Build.VERSION.SDK_INT < 27)) {
            syncTime = mStats.getSyncOnTime(ctx, batteryRealtime, statsType) / 1000;
        }
    } catch (BatteryInfoUnavailableException e) {
        Log.e(TAG, "A batteryinfo error occured while retrieving sensor and sync stats");
    }
    long timeNoDataConnection = 0;
    long timeSignalNone = 0;
    long timeSignalPoor = 0;
    long timeSignalModerate = 0;
    long timeSignalGood = 0;
    long timeSignalGreat = 0;
    if (sharedPrefs.getBoolean("show_other_signal", true)) {
        try {
            timeNoDataConnection = mStats.getPhoneDataConnectionTime(BatteryStatsTypes.DATA_CONNECTION_NONE, batteryRealtime, statsType) / 1000;
            timeSignalNone = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_NONE_OR_UNKNOWN, batteryRealtime, statsType) / 1000;
            timeSignalPoor = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_POOR, batteryRealtime, statsType) / 1000;
            timeSignalModerate = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_MODERATE, batteryRealtime, statsType) / 1000;
            timeSignalGood = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_GOOD, batteryRealtime, statsType) / 1000;
            timeSignalGreat = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_GREAT, batteryRealtime, statsType) / 1000;
        } catch (BatteryInfoUnavailableException e) {
            timeNoDataConnection = 0;
            timeSignalNone = 0;
            timeSignalPoor = 0;
            timeSignalModerate = 0;
            timeSignalGood = 0;
            timeSignalGreat = 0;
            Log.e(TAG, "A batteryinfo error occured while retrieving Signal data");
        }
    }
    long timeScreenDark = 0;
    long timeScreenDim = 0;
    long timeScreenMedium = 0;
    long timeScreenLight = 0;
    long timeScreenBright = 0;
    if (sharedPrefs.getBoolean("show_other_screen_brightness", true)) {
        try {
            timeScreenDark = mStats.getScreenBrightnessTime(BatteryStatsTypes.SCREEN_BRIGHTNESS_DARK, batteryRealtime, statsType) / 1000;
            timeScreenDim = mStats.getScreenBrightnessTime(BatteryStatsTypes.SCREEN_BRIGHTNESS_DIM, batteryRealtime, statsType) / 1000;
            timeScreenMedium = mStats.getScreenBrightnessTime(BatteryStatsTypes.SCREEN_BRIGHTNESS_MEDIUM, batteryRealtime, statsType) / 1000;
            timeScreenLight = mStats.getScreenBrightnessTime(BatteryStatsTypes.SCREEN_BRIGHTNESS_LIGHT, batteryRealtime, statsType) / 1000;
            timeScreenBright = mStats.getScreenBrightnessTime(BatteryStatsTypes.SCREEN_BRIGHTNESS_BRIGHT, batteryRealtime, statsType) / 1000;
        } catch (BatteryInfoUnavailableException e) {
            timeScreenDark = 0;
            timeScreenDim = 0;
            timeScreenMedium = 0;
            timeScreenLight = 0;
            timeScreenBright = 0;
            Log.e(TAG, "A batteryinfo error occured while retrieving Screen brightness data");
        }
    }
    // deep sleep times are independent of stat type
    long timeDeepSleep = (SystemClock.elapsedRealtime() - SystemClock.uptimeMillis());
    Misc deepSleepUsage = new Misc("Deep Sleep", timeDeepSleep, elaspedRealtime);
    if (LogSettings.DEBUG) {
        Log.d(TAG, "Added Deep sleep:" + deepSleepUsage.toString());
    }
    if ((!bFilter) || (deepSleepUsage.getTimeOn() > 0)) {
        myUsages.add(deepSleepUsage);
    }
    if (timeBatteryUp > 0) {
        myUsages.add(new Misc(LABEL_MISC_AWAKE, timeBatteryUp - timeScreenOn, elaspedRealtime));
    }
    if (timeScreenOn > 0) {
        myUsages.add(new Misc("Screen On", timeScreenOn, elaspedRealtime));
    }
    if (timePhoneOn > 0) {
        myUsages.add(new Misc("Phone On", timePhoneOn, elaspedRealtime));
    }
    if ((timeWifiOn > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_wifi", true))) {
        myUsages.add(new Misc("Wifi On", timeWifiOn, elaspedRealtime));
    }
    if ((timeWifiRunning > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_wifi", true))) {
        myUsages.add(new Misc("Wifi Running", timeWifiRunning, elaspedRealtime));
    }
    if ((timeBluetoothOn > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_bt", true))) {
        myUsages.add(new Misc("Bluetooth On", timeBluetoothOn, elaspedRealtime));
    }
    if (Build.VERSION.SDK_INT >= 6) {
        if ((interactiveTime > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_doze", true))) {
            myUsages.add(new Misc("Doze Interactive Time", interactiveTime, elaspedRealtime));
        }
        if ((powerSaveModeEnabledTime > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_doze", true))) {
            myUsages.add(new Misc("Doze Powersave Time", powerSaveModeEnabledTime, elaspedRealtime));
        }
        if ((deviceIdleModeEnabledTime > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_doze", true))) {
            myUsages.add(new Misc("Doze Idle Mode Time", deviceIdleModeEnabledTime, elaspedRealtime));
        }
        if ((getDeviceIdlingTime > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_doze", true))) {
            myUsages.add(new Misc("Doze Idling Time", getDeviceIdlingTime, elaspedRealtime));
        }
        if (syncTime > 0) {
            myUsages.add(new Misc("Sync", syncTime, elaspedRealtime));
        }
    }
    if ((timeNoDataConnection > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_connection", true))) {
        myUsages.add(new Misc("No Data Connection", timeNoDataConnection, elaspedRealtime));
    }
    if ((timeSignalNone > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_signal", true))) {
        myUsages.add(new Misc("No or Unknown Signal", timeSignalNone, elaspedRealtime));
    }
    if ((timeSignalPoor > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_signal", true))) {
        myUsages.add(new Misc("Poor Signal", timeSignalPoor, elaspedRealtime));
    }
    if ((timeSignalModerate > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_signal", true))) {
        myUsages.add(new Misc("Moderate Signal", timeSignalModerate, elaspedRealtime));
    }
    if ((timeSignalGood > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_signal", true))) {
        myUsages.add(new Misc("Good Signal", timeSignalGood, elaspedRealtime));
    }
    if ((timeSignalGreat > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_signal", true))) {
        myUsages.add(new Misc("Great Signal", timeSignalGreat, elaspedRealtime));
    }
    if ((timeScreenDark > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_screen_brightness", true))) {
        myUsages.add(new Misc("Screen dark", timeScreenDark, elaspedRealtime));
    }
    if ((timeScreenDim > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_screen_brightness", true))) {
        myUsages.add(new Misc("Screen dimmed", timeScreenDim, elaspedRealtime));
    }
    if ((timeScreenMedium > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_screen_brightness", true))) {
        myUsages.add(new Misc("Screen medium", timeScreenMedium, elaspedRealtime));
    }
    if ((timeScreenLight > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_screen_brightness", true))) {
        myUsages.add(new Misc("Screen light", timeScreenLight, elaspedRealtime));
    }
    if ((timeScreenBright > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_screen_brightness", true))) {
        myUsages.add(new Misc("Screen bright", timeScreenBright, elaspedRealtime));
    }
    for (int i = 0; i < myUsages.size(); i++) {
        Misc usage = (Misc) myUsages.get(i);
        if (LogSettings.DEBUG) {
            Log.d(TAG, "Current value: " + usage.getName() + " " + usage.toString());
        }
        if ((!bFilter) || (usage.getTimeOn() > 0)) {
            myStats.add((StatElement) usage);
        }
    }
    return myStats;
}
Also used : Context(android.content.Context) SharedPreferences(android.content.SharedPreferences) StatElement(com.asksven.android.common.privateapiproxies.StatElement) ArrayList(java.util.ArrayList) Misc(com.asksven.android.common.privateapiproxies.Misc) BatteryInfoUnavailableException(com.asksven.android.common.privateapiproxies.BatteryInfoUnavailableException) BatteryStatsProxy(com.asksven.android.common.privateapiproxies.BatteryStatsProxy) ReceiverCallNotAllowedException(android.content.ReceiverCallNotAllowedException) BatteryInfoUnavailableException(com.asksven.android.common.privateapiproxies.BatteryInfoUnavailableException) SuppressLint(android.annotation.SuppressLint)

Aggregations

StatElement (com.asksven.android.common.privateapiproxies.StatElement)39 ArrayList (java.util.ArrayList)22 SuppressLint (android.annotation.SuppressLint)21 SharedPreferences (android.content.SharedPreferences)21 Context (android.content.Context)16 Misc (com.asksven.android.common.privateapiproxies.Misc)11 Notification (com.asksven.android.common.privateapiproxies.Notification)10 BatteryStatsProxy (com.asksven.android.common.privateapiproxies.BatteryStatsProxy)9 Reference (com.asksven.betterbatterystats.data.Reference)9 Intent (android.content.Intent)8 PackageManager (android.content.pm.PackageManager)8 Alarm (com.asksven.android.common.privateapiproxies.Alarm)8 NativeKernelWakelock (com.asksven.android.common.privateapiproxies.NativeKernelWakelock)8 StatsProvider (com.asksven.betterbatterystats.data.StatsProvider)8 PendingIntent (android.app.PendingIntent)7 AppWidgetManager (android.appwidget.AppWidgetManager)6 RemoteViews (android.widget.RemoteViews)6 Matcher (java.util.regex.Matcher)6 Pattern (java.util.regex.Pattern)6 NetworkUsage (com.asksven.android.common.privateapiproxies.NetworkUsage)4