Add a power saving mode setting

Create a setting that tunes performance optimizations and improves the
power usage.
Automatically tune mode with the Power-saving mode of Android Lollipop+.
Also, when the phone drops below threshold for low battery, prompt user
to turn browser's power save mode on.

Change-Id: I64089a371de562f9a18c297eb09555733f020515
diff --git a/src/com/android/browser/BrowserSettings.java b/src/com/android/browser/BrowserSettings.java
index e3d1ee5..864315a 100644
--- a/src/com/android/browser/BrowserSettings.java
+++ b/src/com/android/browser/BrowserSettings.java
@@ -774,6 +774,14 @@
         mPrefs.edit().putBoolean(PREF_AUTOFILL_ENABLED, value).apply();
     }
 
+    public boolean isPowerSaveModeEnabled() {
+        return mPrefs.getBoolean(PREF_POWERSAVE_ENABLED, false);
+    }
+
+    public void setPowerSaveModeEnabled(boolean value) {
+        mPrefs.edit().putBoolean(PREF_POWERSAVE_ENABLED, value).apply();
+    }
+
     // -----------------------------
     // getter/setters for debug_preferences.xml
     // -----------------------------
diff --git a/src/com/android/browser/Controller.java b/src/com/android/browser/Controller.java
index 353fea9..07f2d12 100644
--- a/src/com/android/browser/Controller.java
+++ b/src/com/android/browser/Controller.java
@@ -1,6 +1,8 @@
 /*
  * Copyright (C) 2010 The Android Open Source Project
  *
+ * Copyright (C) 2015 The Linux Foundation
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
@@ -30,6 +32,7 @@
 import android.content.DialogInterface;
 import android.content.DialogInterface.OnCancelListener;
 import android.content.Intent;
+import android.content.IntentFilter;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.content.res.Configuration;
@@ -255,6 +258,8 @@
     private float mLevel = 0.0f;
     private WebView.HitTestResult mResult;
     private static Bitmap mBookmarkBitmap;
+    private PowerConnectionReceiver mLowPowerReceiver;
+    private PowerConnectionReceiver mPowerChangeReceiver;
 
     public Controller(Activity browser) {
         mActivity = browser;
@@ -398,6 +403,19 @@
                 && BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
             bookmarksOrHistoryPicker(ComboViews.Bookmarks);
         }
+
+        mLowPowerReceiver = new PowerConnectionReceiver();
+        mPowerChangeReceiver = new PowerConnectionReceiver();
+
+        //always track the android framework's power save mode
+        IntentFilter filter = new IntentFilter();
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+            // Power save mode only exists in Lollipop and above
+            filter.addAction("android.os.action.POWER_SAVE_MODE_CHANGED");
+        }
+        filter.addAction(Intent.ACTION_BATTERY_OKAY);
+        mActivity.registerReceiver(mPowerChangeReceiver, filter);
+
     }
 
     private static class PruneThumbnails implements Runnable {
@@ -748,6 +766,8 @@
 
         WebView.disablePlatformNotifications();
         NfcHandler.unregister(mActivity);
+
+        mActivity.unregisterReceiver(mLowPowerReceiver);
     }
 
     @Override
@@ -797,6 +817,8 @@
         if (current != null && current.hasCrashed) {
             current.replaceCrashView(current.getWebView(), current.getViewContainer());
         }
+
+        mActivity.registerReceiver(mLowPowerReceiver, new IntentFilter(Intent.ACTION_BATTERY_LOW));
     }
 
     private void releaseWakeLock() {
@@ -852,6 +874,8 @@
         mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
         // Destroy all the tabs
         mTabControl.destroy();
+        // Unregister receiver
+        mActivity.unregisterReceiver(mPowerChangeReceiver);
     }
 
     protected boolean isActivityPaused() {
diff --git a/src/com/android/browser/PowerConnectionReceiver.java b/src/com/android/browser/PowerConnectionReceiver.java
new file mode 100644
index 0000000..f68d3fc
--- /dev/null
+++ b/src/com/android/browser/PowerConnectionReceiver.java
@@ -0,0 +1,60 @@
+/* Copyright (c) 2015, The Linux Foundation. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *      * Redistributions of source code must retain the above copyright
+ *      notice, this list of conditions and the following disclaimer.
+ *      * Redistributions in binary form must reproduce the above
+ *      copyright notice, this list of conditions and the following
+ *      disclaimer in the documentation and/or other materials provided
+ *      with the distribution.
+ *      * Neither the name of The Linux Foundation nor the names of its
+ *      contributors may be used to endorse or promote products derived
+ *      from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package com.android.browser;
+
+import com.android.browser.preferences.GeneralPreferencesFragment;
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.app.DownloadManager;
+import android.content.ActivityNotFoundException;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.net.Uri;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.PowerManager;
+
+public class PowerConnectionReceiver extends BroadcastReceiver {
+    static final String POWER_MODE_TOGGLE = "android.os.action.POWER_SAVE_MODE_CHANGED";
+    static final String POWER_OKAY = Intent.ACTION_BATTERY_OKAY;
+
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        BrowserSettings settings = BrowserSettings.getInstance();
+        String action = intent.getAction();
+        if (POWER_MODE_TOGGLE.equals(action)) {
+            // This feature is only on android L+
+            PowerManager pm = (PowerManager) context.getSystemService(context.POWER_SERVICE);
+            settings.setPowerSaveModeEnabled(pm.isPowerSaveMode());
+        } else if (POWER_OKAY.equals(action)) {
+            settings.setPowerSaveModeEnabled(false);
+        } else {
+            if (settings.isPowerSaveModeEnabled())
+                return;
+            Bundle bundle = new Bundle();
+            bundle.putBoolean("LowPower", true);
+            BrowserPreferencesPage.startPreferenceFragmentExtraForResult((Activity) context, GeneralPreferencesFragment.class.getName(), bundle, 0);
+        }
+    }
+}
diff --git a/src/com/android/browser/PreferenceKeys.java b/src/com/android/browser/PreferenceKeys.java
index f6b37f5..b0c384a 100644
--- a/src/com/android/browser/PreferenceKeys.java
+++ b/src/com/android/browser/PreferenceKeys.java
@@ -60,6 +60,7 @@
     static final String PREF_AUTOFILL_ENABLED = "autofill_enabled";
     static final String PREF_AUTOFILL_PROFILE = "autofill_profile";
     static final String PREF_HOMEPAGE = "homepage";
+    static final String PREF_POWERSAVE_ENABLED = "powersave_enabled";
     static final String PREF_SYNC_WITH_CHROME = "sync_with_chrome";
 
     // ----------------------
diff --git a/src/com/android/browser/preferences/GeneralPreferencesFragment.java b/src/com/android/browser/preferences/GeneralPreferencesFragment.java
index f481e73..8ab79a3 100644
--- a/src/com/android/browser/preferences/GeneralPreferencesFragment.java
+++ b/src/com/android/browser/preferences/GeneralPreferencesFragment.java
@@ -93,6 +93,12 @@
                 PreferenceKeys.PREF_AUTOFILL_PROFILE);
         autofill.setOnPreferenceClickListener(this);
 
+        final Bundle arguments = getArguments();
+        if (arguments != null && arguments.getBoolean("LowPower")) {
+            LowPowerDialogFragment fragment = LowPowerDialogFragment.newInstance();
+            fragment.show(getActivity().getFragmentManager(), "setPowersave dialog");
+        }
+
         //Disable set search engine preference if SEARCH_ENGINE restriction is enabled
         if (SearchEngineRestriction.getInstance().isEnabled()) {
             findPreference("search_engine").setEnabled(false);
@@ -301,4 +307,37 @@
             outState.putString(HOME_PAGE, editText.getText().toString().trim());
         }
     }
+    public static class LowPowerDialogFragment extends DialogFragment {
+        public static LowPowerDialogFragment newInstance() {
+            LowPowerDialogFragment frag = new LowPowerDialogFragment();
+            return frag;
+        }
+
+        @Override
+        public Dialog onCreateDialog(Bundle savedInstanceState) {
+            final BrowserSettings settings = BrowserSettings.getInstance();
+            final AlertDialog dialog = new AlertDialog.Builder(getActivity())
+                    .setPositiveButton(android.R.string.ok, new OnClickListener() {
+                        @Override
+                        public void onClick(DialogInterface dialog, int which) {
+                            settings.setPowerSaveModeEnabled(true);
+                            getActivity().finish();
+                        }
+                    })
+                    .setNegativeButton(android.R.string.cancel, new OnClickListener() {
+                        @Override
+                        public void onClick(DialogInterface dialog, int which) {
+                            dialog.cancel();
+                            getActivity().finish();
+                        }
+                    })
+                    .setTitle(R.string.pref_powersave_enabled_summary)
+                    .create();
+
+            dialog.getWindow().setSoftInputMode(
+                    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
+
+            return dialog;
+        }
+    }
 }