Search in sources :

Example 6 with StatsProvider

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

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

the class UpdateTextWidgetService 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;
            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);
                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);
                Log.i(TAG, "[" + widgetId + "] using horizontal layout");
                remoteViews = new RemoteViews(this.getPackageName(), R.layout.text_widget_horz);
            }
            // 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);
            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);
                remoteViews.setTextViewText(R.id.stat_type, fromRef.getLabel());
                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);
                }
                remoteViews.setTextViewText(R.id.textViewSinceVal, AppWidget.formatDuration(timeSince));
                // Show % depending on width and preferences
                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 <= 2) {
                        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) BatteryStatsProxy(com.asksven.android.common.privateapiproxies.BatteryStatsProxy) 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 8 with StatsProvider

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

the class WatchdogProcessingService method onHandleIntent.

@Override
public void onHandleIntent(Intent intent) {
    Log.i(TAG, "Called at " + DateUtils.now());
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    try {
        if (true) {
            int minScreenOffDurationMin = sharedPrefs.getInt("watchdog_duration_threshold", 10);
            int awakeThresholdPct = sharedPrefs.getInt("watchdog_awake_threshold", 30);
            long now = System.currentTimeMillis();
            Long screenOffTime = sharedPrefs.getLong("screen_went_off_at", now);
            Long screenOffDurationMs = now - screenOffTime;
            // we process only if screenOffDuration is >= minScreenOffDuration
            if (screenOffDurationMs >= ((long) minScreenOffDurationMin * 60 * 1000)) {
                // Toast.makeText(this, getString(R.string.message_watchdog_processing), Toast.LENGTH_SHORT).show();
                int awakePct = 0;
                StatsProvider stats = StatsProvider.getInstance();
                // make sure to flush cache
                BatteryStatsProxy.getInstance(this).invalidate();
                // save screen on reference
                Intent serviceIntent = new Intent(this.getApplicationContext(), WriteScreenOnReferenceService.class);
                this.startService(serviceIntent);
                if (stats.hasScreenOffRef()) {
                    // restore any available since screen reference
                    Reference refFrom = ReferenceStore.getReferenceByName(Reference.SCREEN_OFF_REF_FILENAME, this);
                    StatsProvider.getInstance().setCurrentReference(0);
                    // Reference refTo = StatsProvider.getInstance(this).getUncachedPartialReference(0);
                    Reference refTo = ReferenceStore.getReferenceByName(Reference.CURRENT_REF_FILENAME, this);
                    ArrayList<StatElement> otherStats = null;
                    // only process if both references are in the right order
                    if (refFrom.getCreationTime() < refTo.getCreationTime()) {
                        otherStats = stats.getOtherUsageStatList(true, refFrom, false, false, refTo);
                    } else {
                        otherStats = null;
                    }
                    long timeAwake = 0;
                    long timeSince = 0;
                    if ((otherStats != null) && (otherStats.size() > 1)) {
                        timeAwake = ((Misc) stats.getElementByKey(otherStats, StatsProvider.LABEL_MISC_AWAKE)).getTimeOn();
                        timeSince = stats.getBatteryRealtime(StatsProvider.STATS_SCREEN_OFF);
                        Log.i(TAG, "Other stats found. Since=" + timeSince + ", Awake=" + timeAwake);
                    } else {
                        // no stats means the phone was awake
                        timeSince = stats.getBatteryRealtime(StatsProvider.STATS_SCREEN_OFF);
                        timeAwake = timeSince;
                        Log.i(TAG, "Other stats do not have any data. Since=" + timeSince + ", Awake=" + timeAwake);
                    }
                    if (timeSince > 0) {
                        awakePct = (int) ((timeAwake * 100 / timeSince));
                    } else {
                        awakePct = 0;
                    }
                    Log.i(TAG, "Awake %=" + awakePct);
                    // we issue a warning if awakePct > awakeThresholdPct
                    if (awakePct >= awakeThresholdPct) {
                        // Instantiate a Builder object.
                        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
                        String alertText = "";
                        try {
                            alertText = getString(R.string.message_awake_info, awakePct);
                        } catch (Exception e) {
                            alertText = getString(R.string.message_awake_alert);
                        }
                        builder.setSmallIcon(R.drawable.ic_stat_notification);
                        builder.setContentTitle(this.getText(R.string.app_name));
                        builder.setContentText(alertText);
                        // Creates an Intent for the Activity
                        Intent i = new Intent(Intent.ACTION_MAIN);
                        PackageManager manager = this.getPackageManager();
                        i = manager.getLaunchIntentForPackage(this.getPackageName());
                        i.addCategory(Intent.CATEGORY_LAUNCHER);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        i.putExtra(StatsActivity.STAT, 0);
                        i.putExtra(StatsActivity.STAT_TYPE_FROM, Reference.SCREEN_OFF_REF_FILENAME);
                        i.putExtra(StatsActivity.STAT_TYPE_TO, Reference.SCREEN_ON_REF_FILENAME);
                        i.putExtra(StatsActivity.FROM_NOTIFICATION, true);
                        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
                        // Puts the PendingIntent into the notification builder
                        builder.setContentIntent(contentIntent);
                        // Notifications are issued by sending them to the
                        // NotificationManager system service.
                        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                        // Builds an anonymous Notification object from the builder, and
                        // passes it to the NotificationManager
                        mNotificationManager.notify(EventWatcherService.NOTIFICATION_ID, builder.build());
                    }
                }
            } else {
                // delete screen on ref
                ReferenceStore.invalidate(Reference.SCREEN_ON_REF_FILENAME, this);
            }
            // Build the intent to update the widget
            Intent intentRefreshWidgets = new Intent(AppWidget.WIDGET_UPDATE);
            this.sendBroadcast(intentRefreshWidgets);
        }
    } catch (Exception e) {
        Log.e(TAG, "An error occured: " + e.getMessage());
    }
}
Also used : NotificationManager(android.app.NotificationManager) SharedPreferences(android.content.SharedPreferences) Reference(com.asksven.betterbatterystats.data.Reference) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) PackageManager(android.content.pm.PackageManager) StatsProvider(com.asksven.betterbatterystats.data.StatsProvider) StatElement(com.asksven.android.common.privateapiproxies.StatElement) NotificationCompat(androidx.core.app.NotificationCompat) PendingIntent(android.app.PendingIntent)

Aggregations

Intent (android.content.Intent)8 SharedPreferences (android.content.SharedPreferences)8 StatElement (com.asksven.android.common.privateapiproxies.StatElement)8 Reference (com.asksven.betterbatterystats.data.Reference)8 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 DisplayMetrics (android.util.DisplayMetrics)2 BatteryStatsProxy (com.asksven.android.common.privateapiproxies.BatteryStatsProxy)2 WidgetSummary (com.asksven.betterbatterystats.widgets.WidgetSummary)2 SuppressLint (android.annotation.SuppressLint)1 NotificationManager (android.app.NotificationManager)1 ComponentName (android.content.ComponentName)1 NotificationCompat (androidx.core.app.NotificationCompat)1 WidgetBars (com.asksven.betterbatterystats.widgets.WidgetBars)1 WidgetBattery (com.asksven.betterbatterystats.widgets.WidgetBattery)1