OSDN Git Service

Start fragmentizing battery usage.
authorDianne Hackborn <hackbod@google.com>
Thu, 11 Nov 2010 07:34:52 +0000 (23:34 -0800)
committerDianne Hackborn <hackbod@google.com>
Fri, 12 Nov 2010 06:32:58 +0000 (22:32 -0800)
Change-Id: I0864f6738b37c3203e166bb8f7e61e8904d9980a

AndroidManifest.xml
res/values/strings.xml
res/xml/application_settings.xml
src/com/android/settings/Settings.java
src/com/android/settings/SettingsPreferenceFragment.java
src/com/android/settings/fuelgauge/BatteryHistoryDetail.java
src/com/android/settings/fuelgauge/PowerUsageDetail.java
src/com/android/settings/fuelgauge/PowerUsageSummary.java

index d8a2fa1..5960572 100644 (file)
              InstalledAppDetails. -->
         <activity android:name=".applications.InstalledAppDetailsTop"
                   android:label="@string/application_info_label"
+                  android:theme="@android:style/Theme.Holo.DialogWhenLarge"
                   android:exported="true">
         </activity>
         <activity-alias android:name=".applications.InstalledAppDetails"
             </intent-filter>
         </activity-alias>
 
-        <!--
-        <activity android:name=".applications.ManageApplications"
-                  android:label="@string/manageapplications_settings_title"
-                  android:clearTaskOnLaunch="true"
-                  android:theme="@android:style/Theme.NoTitleBar">
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <action android:name="android.intent.action.MANAGE_PACKAGE_STORAGE" />
-                <action android:name="android.settings.MANAGE_APPLICATIONS_SETTINGS" />
-                <action android:name="android.settings.MANAGE_ALL_APPLICATIONS_SETTINGS" />
-                <category android:name="android.intent.category.DEFAULT" />
-                <category android:name="android.intent.category.MONKEY" />
-                <category android:name="android.intent.category.VOICE_LAUNCH" />
-                <category android:name="com.android.settings.SHORTCUT" />
-            </intent-filter>
-        </activity>
-
-        <activity-alias android:name=".ManageApplications"
-            android:targetActivity=".applications.ManageApplications"
-            android:exported="true" />
-
-        <activity android:name=".applications.InstalledAppDetails"
-                android:theme="@android:style/Theme.NoTitleBar"
-                android:label="@string/application_info_label">
-            <intent-filter>
-                <action android:name="android.settings.APPLICATION_DETAILS_SETTINGS" />
-                <category android:name="android.intent.category.DEFAULT" />
-                <data android:scheme="package" />
-            </intent-filter>
-        </activity>
-        -->
-
         <!-- Provide direct entry into manage apps showing running services. -->
         <activity android:name="Settings$RunningServicesActivity"
                 android:theme="@android:style/Theme.Holo.Extended"
             </intent-filter>
         </activity>
 
-        <activity android:name="MasterClear" android:label="@string/master_clear_title">
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-            </intent-filter>
-        </activity>
-
         <activity android:name="MediaFormat" android:label="@string/media_format_title">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
             </intent-filter>
         </activity>
 
-        <activity android:name=".fuelgauge.PowerUsageSummary"
-                android:theme="@android:style/Theme.NoTitleBar"
-                android:label="@string/power_usage_summary_title"
-                android:clearTaskOnLaunch="true"
-                >
+        <activity android:name="Settings$PowerUsageSummaryActivity"
+                android:theme="@android:style/Theme.Holo.Extended"
+                android:label="@string/storage_settings_title">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
                 <action android:name="android.intent.action.POWER_USAGE_SUMMARY" />
                 <category android:name="android.intent.category.DEFAULT" />
                 <category android:name="com.android.settings.SHORTCUT" />
             </intent-filter>
-        </activity>
-
-        <activity android:name=".fuelgauge.PowerUsageDetail"
-                android:theme="@android:style/Theme.NoTitleBar"
-                android:label="@string/details_title">
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.DEFAULT" />
-            </intent-filter>
-        </activity>
-
-        <activity android:name=".fuelgauge.BatteryHistoryDetail"
-                android:theme="@android:style/Theme.NoTitleBar">
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.DEFAULT" />
-            </intent-filter>
+            <meta-data android:name="com.android.settings.FRAGMENT_CLASS"
+                android:value="com.android.settings.fuelgauge.PowerUsageSummary" />
+            <meta-data android:name="com.android.settings.TOP_LEVEL_HEADER_ID"
+                android:resource="@id/application_settings" />
         </activity>
 
         <activity
index 2d09282..3aaed74 100644 (file)
@@ -2440,8 +2440,11 @@ found in the list of installed applications.</string>
     <string name="usage_name_percent"><xliff:g id="name">%1$s</xliff:g>" - "
             <xliff:g id="number" example="30">%2$s</xliff:g><xliff:g id="percent" example="%">%%</xliff:g></string>
 
+    <!-- Activity title for battery usage history details -->
+    <string name="history_details_title">History details</string>
+    
     <!-- Activity title for battery usage details for an app. or power consumer -->
-    <string name="details_title">Battery use details</string>
+    <string name="details_title">Use details</string>
     <!-- Subtitle for application/subsystem details -->
     <string name="details_subtitle">Use details</string>
     <!-- Subtitle for possible options -->
index 2e446a2..9042ba9 100644 (file)
 
     <PreferenceScreen
             android:key="power_usage"
+            android:fragment="com.android.settings.fuelgauge.PowerUsageSummary"
             android:title="@string/power_usage_summary_title"
             android:summary="@string/power_usage_summary">
-        <intent android:action="android.intent.action.MAIN"
-                android:targetPackage="com.android.settings"
-                android:targetClass="com.android.settings.fuelgauge.PowerUsageSummary" />
     </PreferenceScreen>
 
     <PreferenceScreen 
index a00d58f..28a0f70 100644 (file)
@@ -193,4 +193,5 @@ public class Settings extends PreferenceActivity {
     public static class RunningServicesActivity extends Settings { }
     public static class VoiceInputOutputSettingsActivity extends Settings { }
     public static class ManageAccountsSettingsActivity extends Settings { }
+    public static class PowerUsageSummaryActivity extends Settings { }
 }
index 890da3d..41ff87f 100644 (file)
@@ -132,13 +132,6 @@ public class SettingsPreferenceFragment extends PreferenceFragment
     }
 
     /**
-     * Returns the Resources from the owning Activity.
-     */
-    protected Resources getResources() {
-        return getActivity().getResources();
-    }
-
-    /**
      * Returns the PackageManager from the owning Activity.
      */
     protected PackageManager getPackageManager() {
index c673ce3..ad6fb30 100644 (file)
 
 package com.android.settings.fuelgauge;
 
-import android.app.Activity;
+import android.app.Fragment;
 import android.os.Bundle;
 import android.os.Parcel;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
 
 import com.android.internal.os.BatteryStatsImpl;
 import com.android.settings.R;
 
-public class BatteryHistoryDetail extends Activity {
+public class BatteryHistoryDetail extends Fragment {
     public static final String EXTRA_STATS = "stats";
 
     private BatteryStatsImpl mStats;
 
     @Override
-    protected void onCreate(Bundle icicle) {
+    public void onCreate(Bundle icicle) {
         super.onCreate(icicle);
-        byte[] data = getIntent().getByteArrayExtra(EXTRA_STATS);
+        byte[] data = getArguments().getByteArray(EXTRA_STATS);
         Parcel parcel = Parcel.obtain();
         parcel.unmarshall(data, 0, data.length);
         parcel.setDataPosition(0);
-        setContentView(R.layout.preference_batteryhistory);
         mStats = com.android.internal.os.BatteryStatsImpl.CREATOR
                 .createFromParcel(parcel);
-        BatteryHistoryChart chart = (BatteryHistoryChart)findViewById(
+    }
+    
+    @Override
+    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+        View view = inflater.inflate(R.layout.preference_batteryhistory, null);
+        BatteryHistoryChart chart = (BatteryHistoryChart)view.findViewById(
                 R.id.battery_history_chart);
         chart.setStats(mStats);
+        return view;
     }
 }
index cc112f8..c4b6db4 100644 (file)
@@ -19,6 +19,7 @@ package com.android.settings.fuelgauge;
 import android.app.Activity;
 import android.app.ActivityManager;
 import android.app.ApplicationErrorReport;
+import android.app.Fragment;
 import android.content.BroadcastReceiver;
 import android.content.ComponentName;
 import android.content.Context;
@@ -32,6 +33,7 @@ import android.graphics.drawable.Drawable;
 import android.net.Uri;
 import android.os.Bundle;
 import android.os.Process;
+import android.preference.PreferenceActivity;
 import android.provider.Settings;
 import android.text.TextUtils;
 import android.view.LayoutInflater;
@@ -42,9 +44,8 @@ import android.widget.ImageView;
 import android.widget.TextView;
 import com.android.settings.R;
 import com.android.settings.applications.InstalledAppDetails;
-import com.android.settings.applications.ManageApplications;
 
-public class PowerUsageDetail extends Activity implements Button.OnClickListener {
+public class PowerUsageDetail extends Fragment implements Button.OnClickListener {
 
     enum DrainType {
         IDLE,
@@ -100,6 +101,7 @@ public class PowerUsageDetail extends Activity implements Button.OnClickListener
     private int[] mTypes;
     private int mUid;
     private double[] mValues;
+    private View mRootView;
     private TextView mTitleView;
     private ViewGroup mTwoButtonsPanel;
     private Button mForceStopButton;
@@ -121,38 +123,43 @@ public class PowerUsageDetail extends Activity implements Button.OnClickListener
     ComponentName mInstaller;
     
     @Override
-    protected void onCreate(Bundle icicle) {
+    public void onCreate(Bundle icicle) {
         super.onCreate(icicle);
-        setContentView(R.layout.power_usage_details);
+    }
+
+    @Override
+    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+        View view = mRootView = inflater.inflate(R.layout.power_usage_details, null);
         createDetails();
+        return view;
     }
 
     @Override
-    protected void onResume() {
+    public void onResume() {
         super.onResume();
         mStartTime = android.os.Process.getElapsedCpuTime();
         checkForceStop();
     }
 
     @Override
-    protected void onPause() {
+    public void onPause() {
         super.onPause();
     }
 
     private void createDetails() {
-        final Intent intent = getIntent();
-        mTitle = intent.getStringExtra(EXTRA_TITLE);
-        final int percentage = intent.getIntExtra(EXTRA_PERCENT, 1);
-        final int gaugeValue = intent.getIntExtra(EXTRA_GAUGE, 1);
-        mUsageSince = intent.getIntExtra(EXTRA_USAGE_SINCE, USAGE_SINCE_UNPLUGGED);
-        mUid = intent.getIntExtra(EXTRA_UID, 0);
-        mDrainType = (DrainType) intent.getSerializableExtra(EXTRA_DRAIN_TYPE);
-        mNoCoverage = intent.getDoubleExtra(EXTRA_NO_COVERAGE, 0);
-        String iconPackage = intent.getStringExtra(EXTRA_ICON_PACKAGE);
-        int iconId = intent.getIntExtra(EXTRA_ICON_ID, 0);
+        final Bundle args = getArguments();
+        mTitle = args.getString(EXTRA_TITLE);
+        final int percentage = args.getInt(EXTRA_PERCENT, 1);
+        final int gaugeValue = args.getInt(EXTRA_GAUGE, 1);
+        mUsageSince = args.getInt(EXTRA_USAGE_SINCE, USAGE_SINCE_UNPLUGGED);
+        mUid = args.getInt(EXTRA_UID, 0);
+        mDrainType = (DrainType) args.getSerializable(EXTRA_DRAIN_TYPE);
+        mNoCoverage = args.getDouble(EXTRA_NO_COVERAGE, 0);
+        String iconPackage = args.getString(EXTRA_ICON_PACKAGE);
+        int iconId = args.getInt(EXTRA_ICON_ID, 0);
         if (!TextUtils.isEmpty(iconPackage)) {
             try {
-                final PackageManager pm = getPackageManager();
+                final PackageManager pm = getActivity().getPackageManager();
                 ApplicationInfo ai = pm.getPackageInfo(iconPackage, 0).applicationInfo;
                 if (ai != null) {
                     mAppIcon = ai.loadIcon(pm);
@@ -161,40 +168,40 @@ public class PowerUsageDetail extends Activity implements Button.OnClickListener
                 // Use default icon
             }
         } else if (iconId != 0) {
-            mAppIcon = getResources().getDrawable(iconId);
+            mAppIcon = getActivity().getResources().getDrawable(iconId);
         }
         if (mAppIcon == null) {
-            mAppIcon = getPackageManager().getDefaultActivityIcon();
+            mAppIcon = getActivity().getPackageManager().getDefaultActivityIcon();
         }
 
         // Set the description
         String summary = getDescriptionForDrainType();
-        ((TextView)findViewById(R.id.summary)).setText(summary);
+        ((TextView)mRootView.findViewById(R.id.summary)).setText(summary);
         
-        mTypes = intent.getIntArrayExtra(EXTRA_DETAIL_TYPES);
-        mValues = intent.getDoubleArrayExtra(EXTRA_DETAIL_VALUES);
+        mTypes = args.getIntArray(EXTRA_DETAIL_TYPES);
+        mValues = args.getDoubleArray(EXTRA_DETAIL_VALUES);
 
-        mTitleView = (TextView) findViewById(R.id.name);
+        mTitleView = (TextView)mRootView.findViewById(R.id.name);
         mTitleView.setText(mTitle);
-        ((TextView)findViewById(R.id.battery_percentage))
+        ((TextView)mRootView.findViewById(R.id.battery_percentage))
             .setText(String.format("%d%%", percentage));
 
-        mTwoButtonsPanel = (ViewGroup) findViewById(R.id.two_buttons_panel);
-        mForceStopButton = (Button) findViewById(R.id.left_button);
-        mReportButton = (Button) findViewById(R.id.right_button);
+        mTwoButtonsPanel = (ViewGroup)mRootView.findViewById(R.id.two_buttons_panel);
+        mForceStopButton = (Button)mRootView.findViewById(R.id.left_button);
+        mReportButton = (Button)mRootView.findViewById(R.id.right_button);
         mForceStopButton.setEnabled(false);
         
-        ImageView gaugeImage = (ImageView) findViewById(R.id.gauge);
+        ImageView gaugeImage = (ImageView)mRootView.findViewById(R.id.gauge);
         mGauge = new PercentageBar();
         mGauge.percent = gaugeValue;
         mGauge.bar = getResources().getDrawable(R.drawable.app_gauge);
         gaugeImage.setImageDrawable(mGauge);
 
-        ImageView iconImage = (ImageView) findViewById(R.id.icon);
+        ImageView iconImage = (ImageView)mRootView.findViewById(R.id.icon);
         iconImage.setImageDrawable(mAppIcon);
 
-        mDetailsParent = (ViewGroup) findViewById(R.id.details);
-        mControlsParent = (ViewGroup) findViewById(R.id.controls);
+        mDetailsParent = (ViewGroup)mRootView.findViewById(R.id.details);
+        mControlsParent = (ViewGroup)mRootView.findViewById(R.id.controls);
 
         fillDetailsSection();
         fillPackagesSection(mUid);
@@ -209,14 +216,15 @@ public class PowerUsageDetail extends Activity implements Button.OnClickListener
             mReportButton.setOnClickListener(this);
             
             // check if error reporting is enabled in secure settings
-            int enabled = Settings.Secure.getInt(getContentResolver(),
+            int enabled = Settings.Secure.getInt(getActivity().getContentResolver(),
                     Settings.Secure.SEND_ACTION_APP_ERROR, 0);
             if (enabled != 0) {
                 if (mPackages != null && mPackages.length > 0) {
                     try {
-                        mApp = getPackageManager().getApplicationInfo(mPackages[0], 0);
+                        mApp = getActivity().getPackageManager().getApplicationInfo(
+                                mPackages[0], 0);
                         mInstaller = ApplicationErrorReport.getErrorReportReceiver(
-                                this, mPackages[0], mApp.flags);
+                                getActivity(), mPackages[0], mApp.flags);
                     } catch (NameNotFoundException e) {
                     }
                 }
@@ -233,6 +241,17 @@ public class PowerUsageDetail extends Activity implements Button.OnClickListener
         doAction((Integer) v.getTag());
     }
 
+    // utility method used to start sub activity
+    private void startApplicationDetailsActivity() {
+        // start new fragment to display extended information
+        Bundle args = new Bundle();
+        args.putString(InstalledAppDetails.ARG_PACKAGE_NAME, mPackages[0]);
+
+        PreferenceActivity pa = (PreferenceActivity)getActivity();
+        pa.startPreferencePanel(InstalledAppDetails.class.getName(), args,
+                R.string.application_info_label, null, null, 0);
+    }
+
     private void doAction(int action) {
         switch (action) {
             case ACTION_DISPLAY_SETTINGS:
@@ -248,10 +267,7 @@ public class PowerUsageDetail extends Activity implements Button.OnClickListener
                 startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
                 break;
             case ACTION_APP_DETAILS:
-                Intent intent = new Intent(Intent.ACTION_VIEW,
-                        Uri.fromParts("package", mPackages[0], null));
-                intent.setClass(this, InstalledAppDetails.class);
-                startActivity(intent);
+                startApplicationDetailsActivity();
                 break;
             case ACTION_SECURITY_SETTINGS:
                 startActivity(new Intent(Settings.ACTION_SECURITY_SETTINGS));
@@ -266,7 +282,7 @@ public class PowerUsageDetail extends Activity implements Button.OnClickListener
     }
 
     private void fillDetailsSection() {
-        LayoutInflater inflater = getLayoutInflater();
+        LayoutInflater inflater = getActivity().getLayoutInflater();
         if (mTypes != null && mValues != null) {
             for (int i = 0; i < mTypes.length; i++) {
                 // Only add an item if the time is greater than zero
@@ -276,7 +292,7 @@ public class PowerUsageDetail extends Activity implements Button.OnClickListener
                 switch (mTypes[i]) {
                     case R.string.usage_type_data_recv:
                     case R.string.usage_type_data_send:
-                        value = Utils.formatBytes(this, mValues[i]);
+                        value = Utils.formatBytes(getActivity(), mValues[i]);
                         break;
                     case R.string.usage_type_no_coverage:
                         value = String.format("%d%%", (int) Math.floor(mValues[i]));
@@ -285,7 +301,7 @@ public class PowerUsageDetail extends Activity implements Button.OnClickListener
                         mUsesGps = true;
                         // Fall through
                     default:
-                        value = Utils.formatElapsedTime(this, mValues[i]);
+                        value = Utils.formatElapsedTime(getActivity(), mValues[i]);
                 }
                 ViewGroup item = (ViewGroup) inflater.inflate(R.layout.power_usage_detail_item_text,
                         null);
@@ -299,7 +315,7 @@ public class PowerUsageDetail extends Activity implements Button.OnClickListener
     }
 
     private void fillControlsSection(int uid) {
-        PackageManager pm = getPackageManager();
+        PackageManager pm = getActivity().getPackageManager();
         String[] packages = pm.getPackagesForUid(uid);
         PackageInfo pi = null;
         try {
@@ -359,7 +375,7 @@ public class PowerUsageDetail extends Activity implements Button.OnClickListener
 
     private void addControl(int title, int summary, int action) {
         final Resources res = getResources();
-        LayoutInflater inflater = getLayoutInflater();
+        LayoutInflater inflater = getActivity().getLayoutInflater();
         ViewGroup item = (ViewGroup) inflater.inflate(R.layout.power_usage_action_item,null);
         mControlsParent.addView(item);
         Button actionButton = (Button) item.findViewById(R.id.action_button);
@@ -372,17 +388,17 @@ public class PowerUsageDetail extends Activity implements Button.OnClickListener
 
     private void removePackagesSection() {
         View view;
-        if ((view = findViewById(R.id.packages_section_title)) != null) {
+        if ((view = mRootView.findViewById(R.id.packages_section_title)) != null) {
             view.setVisibility(View.GONE);
         }
-        if ((view = findViewById(R.id.packages_section)) != null) {
+        if ((view = mRootView.findViewById(R.id.packages_section)) != null) {
             view.setVisibility(View.GONE);
         }
     }
 
     private void killProcesses() {
         if (mPackages == null) return;
-        ActivityManager am = (ActivityManager)getSystemService(
+        ActivityManager am = (ActivityManager)getActivity().getSystemService(
                 Context.ACTIVITY_SERVICE);
         for (int i = 0; i < mPackages.length; i++) {
             am.forceStopPackage(mPackages[i]);
@@ -393,7 +409,7 @@ public class PowerUsageDetail extends Activity implements Button.OnClickListener
     private final BroadcastReceiver mCheckKillProcessesReceiver = new BroadcastReceiver() {
         @Override
         public void onReceive(Context context, Intent intent) {
-            mForceStopButton.setEnabled(getResultCode() != RESULT_CANCELED);
+            mForceStopButton.setEnabled(getResultCode() != Activity.RESULT_CANCELED);
         }
     };
     
@@ -406,7 +422,7 @@ public class PowerUsageDetail extends Activity implements Button.OnClickListener
                 Uri.fromParts("package", mPackages[0], null));
         intent.putExtra(Intent.EXTRA_PACKAGES, mPackages);
         intent.putExtra(Intent.EXTRA_UID, mUid);
-        sendOrderedBroadcast(intent, null, mCheckKillProcessesReceiver, null,
+        getActivity().sendOrderedBroadcast(intent, null, mCheckKillProcessesReceiver, null,
                 Activity.RESULT_CANCELED, null, null);
     }
     
@@ -421,12 +437,12 @@ public class PowerUsageDetail extends Activity implements Button.OnClickListener
         report.time = System.currentTimeMillis();
         report.systemApp = (mApp.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
 
-        final Intent intent = getIntent();
+        final Bundle args = getArguments();
         ApplicationErrorReport.BatteryInfo batteryInfo = new ApplicationErrorReport.BatteryInfo();
-        batteryInfo.usagePercent = intent.getIntExtra(EXTRA_PERCENT, 1);
-        batteryInfo.durationMicros = intent.getLongExtra(EXTRA_USAGE_DURATION, 0);
-        batteryInfo.usageDetails = intent.getStringExtra(EXTRA_REPORT_DETAILS);
-        batteryInfo.checkinDetails = intent.getStringExtra(EXTRA_REPORT_CHECKIN_DETAILS);
+        batteryInfo.usagePercent = args.getInt(EXTRA_PERCENT, 1);
+        batteryInfo.durationMicros = args.getLong(EXTRA_USAGE_DURATION, 0);
+        batteryInfo.usageDetails = args.getString(EXTRA_REPORT_DETAILS);
+        batteryInfo.checkinDetails = args.getString(EXTRA_REPORT_CHECKIN_DETAILS);
         report.batteryInfo = batteryInfo;
 
         Intent result = new Intent(Intent.ACTION_APP_ERROR);
@@ -441,11 +457,11 @@ public class PowerUsageDetail extends Activity implements Button.OnClickListener
             removePackagesSection();
             return;
         }
-        ViewGroup packagesParent = (ViewGroup) findViewById(R.id.packages_section);
+        ViewGroup packagesParent = (ViewGroup)mRootView.findViewById(R.id.packages_section);
         if (packagesParent == null) return;
-        LayoutInflater inflater = getLayoutInflater();
+        LayoutInflater inflater = getActivity().getLayoutInflater();
         
-        PackageManager pm = getPackageManager();
+        PackageManager pm = getActivity().getPackageManager();
         //final Drawable defaultActivityIcon = pm.getDefaultActivityIcon();
         mPackages = pm.getPackagesForUid(uid);
         if (mPackages == null || mPackages.length < 2) {
index ea28c59..9fdc7f2 100644 (file)
@@ -31,17 +31,20 @@ import android.os.SystemClock;
 import android.os.BatteryStats.Uid;
 import android.preference.Preference;
 import android.preference.PreferenceActivity;
+import android.preference.PreferenceFragment;
 import android.preference.PreferenceGroup;
 import android.preference.PreferenceScreen;
 import android.util.Log;
 import android.util.SparseArray;
 import android.view.Menu;
+import android.view.MenuInflater;
 import android.view.MenuItem;
 
 import com.android.internal.app.IBatteryStats;
 import com.android.internal.os.BatteryStatsImpl;
 import com.android.internal.os.PowerProfile;
 import com.android.settings.R;
+import com.android.settings.applications.InstalledAppDetails;
 import com.android.settings.fuelgauge.PowerUsageDetail.DrainType;
 
 import java.io.PrintWriter;
@@ -56,7 +59,7 @@ import java.util.Map;
  * Displays a list of apps and subsystems that consume power, ordered by how much power was
  * consumed since the last time it was unplugged.
  */
-public class PowerUsageSummary extends PreferenceActivity implements Runnable {
+public class PowerUsageSummary extends PreferenceFragment implements Runnable {
 
     private static final boolean DEBUG = false;
 
@@ -65,6 +68,8 @@ public class PowerUsageSummary extends PreferenceActivity implements Runnable {
     private static final int MENU_STATS_TYPE = Menu.FIRST;
     private static final int MENU_STATS_REFRESH = Menu.FIRST + 1;
 
+    private static BatteryStatsImpl sStatsXfer;
+
     IBatteryStats mBatteryInfo;
     BatteryStatsImpl mStats;
     private final List<BatterySipper> mUsageList = new ArrayList<BatterySipper>();
@@ -94,32 +99,27 @@ public class PowerUsageSummary extends PreferenceActivity implements Runnable {
     private boolean mAbort;
     
     @Override
-    protected void onCreate(Bundle icicle) {
+    public void onCreate(Bundle icicle) {
         super.onCreate(icicle);
 
-        mStats = (BatteryStatsImpl)getLastNonConfigurationInstance();
+        mStats = sStatsXfer;
 
         addPreferencesFromResource(R.xml.power_usage_summary);
         mBatteryInfo = IBatteryStats.Stub.asInterface(
                 ServiceManager.getService("batteryinfo"));
         mAppListGroup = (PreferenceGroup) findPreference("app_list");
-        mPowerProfile = new PowerProfile(this);
-    }
-
-    @Override
-    public Object onRetainNonConfigurationInstance() {
-        return mStats;
+        mPowerProfile = new PowerProfile(getActivity());
     }
 
     @Override
-    protected void onResume() {
+    public void onResume() {
         super.onResume();
         mAbort = false;
         refreshStats();
     }
 
     @Override
-    protected void onPause() {
+    public void onPause() {
         synchronized (mRequestQueue) {
             mAbort = true;
         }
@@ -128,14 +128,24 @@ public class PowerUsageSummary extends PreferenceActivity implements Runnable {
     }
 
     @Override
+    public void onDestroy() {
+        super.onDestroy();
+        if (getActivity().isChangingConfigurations()) {
+            sStatsXfer = mStats;
+        }
+    }
+
+    @Override
     public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
         if (preference instanceof BatteryHistoryPreference) {
             Parcel hist = Parcel.obtain();
             mStats.writeToParcelWithoutUids(hist, 0);
             byte[] histData = hist.marshall();
-            Intent intent = new Intent(this, BatteryHistoryDetail.class);
-            intent.putExtra(BatteryHistoryDetail.EXTRA_STATS, histData);
-            startActivity(intent);
+            Bundle args = new Bundle();
+            args.putByteArray(BatteryHistoryDetail.EXTRA_STATS, histData);
+            PreferenceActivity pa = (PreferenceActivity)getActivity();
+            pa.startPreferencePanel(BatteryHistoryDetail.class.getName(), args,
+                    R.string.history_details_title, null, null, 0);
             return super.onPreferenceTreeClick(preferenceScreen, preference);
         }
         if (!(preference instanceof PowerGaugePreference)) {
@@ -143,20 +153,20 @@ public class PowerUsageSummary extends PreferenceActivity implements Runnable {
         }
         PowerGaugePreference pgp = (PowerGaugePreference) preference;
         BatterySipper sipper = pgp.getInfo();
-        Intent intent = new Intent(this, PowerUsageDetail.class);
-        intent.putExtra(PowerUsageDetail.EXTRA_TITLE, sipper.name);
-        intent.putExtra(PowerUsageDetail.EXTRA_PERCENT, (int)
+        Bundle args = new Bundle();
+        args.putString(PowerUsageDetail.EXTRA_TITLE, sipper.name);
+        args.putInt(PowerUsageDetail.EXTRA_PERCENT, (int)
                 Math.ceil(sipper.getSortValue() * 100 / mTotalPower));
-        intent.putExtra(PowerUsageDetail.EXTRA_GAUGE, (int)
+        args.putInt(PowerUsageDetail.EXTRA_GAUGE, (int)
                 Math.ceil(sipper.getSortValue() * 100 / mMaxPower));
-        intent.putExtra(PowerUsageDetail.EXTRA_USAGE_DURATION, mStatsPeriod);
-        intent.putExtra(PowerUsageDetail.EXTRA_ICON_PACKAGE, sipper.defaultPackageName);
-        intent.putExtra(PowerUsageDetail.EXTRA_ICON_ID, sipper.iconId);
-        intent.putExtra(PowerUsageDetail.EXTRA_NO_COVERAGE, sipper.noCoveragePercent);
+        args.putLong(PowerUsageDetail.EXTRA_USAGE_DURATION, mStatsPeriod);
+        args.putString(PowerUsageDetail.EXTRA_ICON_PACKAGE, sipper.defaultPackageName);
+        args.putInt(PowerUsageDetail.EXTRA_ICON_ID, sipper.iconId);
+        args.putDouble(PowerUsageDetail.EXTRA_NO_COVERAGE, sipper.noCoveragePercent);
         if (sipper.uidObj != null) {
-            intent.putExtra(PowerUsageDetail.EXTRA_UID, sipper.uidObj.getUid());
+            args.putInt(PowerUsageDetail.EXTRA_UID, sipper.uidObj.getUid());
         }
-        intent.putExtra(PowerUsageDetail.EXTRA_DRAIN_TYPE, sipper.drainType);
+        args.putSerializable(PowerUsageDetail.EXTRA_DRAIN_TYPE, sipper.drainType);
 
         int[] types;
         double[] values;
@@ -190,12 +200,12 @@ public class PowerUsageSummary extends PreferenceActivity implements Runnable {
                 Writer result = new StringWriter();
                 PrintWriter printWriter = new PrintWriter(result);
                 mStats.dumpLocked(printWriter, "", mStatsType, uid.getUid());
-                intent.putExtra(PowerUsageDetail.EXTRA_REPORT_DETAILS, result.toString());
+                args.putString(PowerUsageDetail.EXTRA_REPORT_DETAILS, result.toString());
                 
                 result = new StringWriter();
                 printWriter = new PrintWriter(result);
                 mStats.dumpCheckinLocked(printWriter, mStatsType, uid.getUid());
-                intent.putExtra(PowerUsageDetail.EXTRA_REPORT_CHECKIN_DETAILS, result.toString());
+                args.putString(PowerUsageDetail.EXTRA_REPORT_CHECKIN_DETAILS, result.toString());
             }
             break;
             case CELL:
@@ -258,15 +268,17 @@ public class PowerUsageSummary extends PreferenceActivity implements Runnable {
                 };
             }
         }
-        intent.putExtra(PowerUsageDetail.EXTRA_DETAIL_TYPES, types);
-        intent.putExtra(PowerUsageDetail.EXTRA_DETAIL_VALUES, values);
-        startActivity(intent);
+        args.putIntArray(PowerUsageDetail.EXTRA_DETAIL_TYPES, types);
+        args.putDoubleArray(PowerUsageDetail.EXTRA_DETAIL_VALUES, values);
+        PreferenceActivity pa = (PreferenceActivity)getActivity();
+        pa.startPreferencePanel(PowerUsageDetail.class.getName(), args,
+                R.string.details_title, null, null, 0);
 
         return super.onPreferenceTreeClick(preferenceScreen, preference);
     }
 
     @Override
-    public boolean onCreateOptionsMenu(Menu menu) {
+    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
         if (DEBUG) {
             menu.add(0, MENU_STATS_TYPE, 0, R.string.menu_stats_total)
                     .setIcon(com.android.internal.R.drawable.ic_menu_info_details)
@@ -275,17 +287,6 @@ public class PowerUsageSummary extends PreferenceActivity implements Runnable {
         menu.add(0, MENU_STATS_REFRESH, 0, R.string.menu_stats_refresh)
                 .setIcon(com.android.internal.R.drawable.ic_menu_refresh)
                 .setAlphabeticShortcut('r');
-        return true;
-    }
-
-    @Override
-    public boolean onPrepareOptionsMenu(Menu menu) {
-        if (DEBUG) {
-            menu.findItem(MENU_STATS_TYPE).setTitle(mStatsType == BatteryStats.STATS_SINCE_CHARGED
-                    ? R.string.menu_stats_unplugged
-                    : R.string.menu_stats_total);
-        }
-        return true;
     }
 
     @Override
@@ -327,7 +328,7 @@ public class PowerUsageSummary extends PreferenceActivity implements Runnable {
 
         mAppListGroup.setOrderingAsAdded(false);
 
-        BatteryHistoryPreference hist = new BatteryHistoryPreference(this, mStats);
+        BatteryHistoryPreference hist = new BatteryHistoryPreference(getActivity(), mStats);
         hist.setOrder(-1);
         mAppListGroup.addPreference(hist);
         
@@ -336,7 +337,7 @@ public class PowerUsageSummary extends PreferenceActivity implements Runnable {
             if (sipper.getSortValue() < MIN_POWER_THRESHOLD) continue;
             final double percentOfTotal =  ((sipper.getSortValue() / mTotalPower) * 100);
             if (percentOfTotal < 1) continue;
-            PowerGaugePreference pref = new PowerGaugePreference(this, sipper.getIcon(), sipper);
+            PowerGaugePreference pref = new PowerGaugePreference(getActivity(), sipper.getIcon(), sipper);
             double percentOfMax = (sipper.getSortValue() * 100) / mMaxPower;
             sipper.percent = percentOfTotal;
             pref.setTitle(sipper.name);
@@ -349,7 +350,6 @@ public class PowerUsageSummary extends PreferenceActivity implements Runnable {
             mAppListGroup.addPreference(pref);
             if (mAppListGroup.getPreferenceCount() > (MAX_ITEMS_TO_LIST+1)) break;
         }
-        if (DEBUG) setTitle("Battery total uAh = " + ((mTotalPower * 1000) / 3600));
         synchronized (mRequestQueue) {
             if (!mRequestQueue.isEmpty()) {
                 if (mRequestThread == null) {
@@ -362,16 +362,9 @@ public class PowerUsageSummary extends PreferenceActivity implements Runnable {
         }
     }
 
-    private void updateStatsPeriod(long duration) {
-        String durationString = Utils.formatElapsedTime(this, duration / 1000);
-        String label = getString(mStats.isOnBattery()
-                ? R.string.battery_stats_duration
-                : R.string.battery_stats_last_duration, durationString);
-        setTitle(label);
-    }
-
     private void processAppUsage() {
-        SensorManager sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
+        SensorManager sensorManager = (SensorManager)getActivity().getSystemService(
+                Context.SENSOR_SERVICE);
         final int which = mStatsType;
         final int speedSteps = mPowerProfile.getNumSpeedSteps();
         final double[] powerCpuNormal = new double[speedSteps];
@@ -382,7 +375,6 @@ public class PowerUsageSummary extends PreferenceActivity implements Runnable {
         final double averageCostPerByte = getAverageDataCost();
         long uSecTime = mStats.computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which);
         mStatsPeriod = uSecTime;
-        updateStatsPeriod(uSecTime);
         SparseArray<? extends Uid> uidStats = mStats.getUidStats();
         final int NU = uidStats.size();
         for (int iu = 0; iu < NU; iu++) {
@@ -504,7 +496,7 @@ public class PowerUsageSummary extends PreferenceActivity implements Runnable {
 
             // Add the app to the list if it is consuming power
             if (power != 0) {
-                BatterySipper app = new BatterySipper(this, mRequestQueue, mHandler,
+                BatterySipper app = new BatterySipper(getActivity(), mRequestQueue, mHandler,
                         packageWithHighestDrain, DrainType.APP, 0, u,
                         new double[] {power});
                 app.cpuTime = cpuTime;
@@ -538,7 +530,7 @@ public class PowerUsageSummary extends PreferenceActivity implements Runnable {
         long phoneOnTimeMs = mStats.getPhoneOnTime(uSecNow, mStatsType) / 1000;
         double phoneOnPower = mPowerProfile.getAveragePower(PowerProfile.POWER_RADIO_ACTIVE)
                 * phoneOnTimeMs / 1000;
-        addEntry(getString(R.string.power_phone), DrainType.PHONE, phoneOnTimeMs,
+        addEntry(getActivity().getString(R.string.power_phone), DrainType.PHONE, phoneOnTimeMs,
                 R.drawable.ic_settings_voice_calls, phoneOnPower);
     }
 
@@ -559,7 +551,7 @@ public class PowerUsageSummary extends PreferenceActivity implements Runnable {
             }
         }
         power /= 1000; // To seconds
-        addEntry(getString(R.string.power_screen), DrainType.SCREEN, screenOnTimeMs,
+        addEntry(getActivity().getString(R.string.power_screen), DrainType.SCREEN, screenOnTimeMs,
                 R.drawable.ic_settings_display, power);
     }
 
@@ -577,8 +569,8 @@ public class PowerUsageSummary extends PreferenceActivity implements Runnable {
         power += scanningTimeMs / 1000 * mPowerProfile.getAveragePower(
                 PowerProfile.POWER_RADIO_SCANNING);
         BatterySipper bs =
-                addEntry(getString(R.string.power_cell), DrainType.CELL, signalTimeMs,
-                R.drawable.ic_settings_cell_standby, power);
+                addEntry(getActivity().getString(R.string.power_cell), DrainType.CELL,
+                        signalTimeMs, R.drawable.ic_settings_cell_standby, power);
         if (signalTimeMs != 0) {
             bs.noCoveragePercent = mStats.getPhoneSignalStrengthTime(0, uSecNow, mStatsType)
                     / 1000 * 100.0 / signalTimeMs;
@@ -610,8 +602,8 @@ public class PowerUsageSummary extends PreferenceActivity implements Runnable {
                 * mPowerProfile.getAveragePower(PowerProfile.POWER_WIFI_ON)
             + runningTimeMs * mPowerProfile.getAveragePower(PowerProfile.POWER_WIFI_ON)) / 1000;
         if (DEBUG) Log.i(TAG, "WIFI power=" + wifiPower + " from procs=" + mWifiPower);
-        BatterySipper bs = addEntry(getString(R.string.power_wifi), DrainType.WIFI, runningTimeMs,
-                R.drawable.ic_settings_wifi, wifiPower + mWifiPower);
+        BatterySipper bs = addEntry(getActivity().getString(R.string.power_wifi), DrainType.WIFI,
+                runningTimeMs, R.drawable.ic_settings_wifi, wifiPower + mWifiPower);
         aggregateSippers(bs, mWifiSippers, "WIFI");
     }
 
@@ -619,7 +611,7 @@ public class PowerUsageSummary extends PreferenceActivity implements Runnable {
         long idleTimeMs = (uSecNow - mStats.getScreenOnTime(uSecNow, mStatsType)) / 1000;
         double idlePower = (idleTimeMs * mPowerProfile.getAveragePower(PowerProfile.POWER_CPU_IDLE))
                 / 1000;
-        addEntry(getString(R.string.power_idle), DrainType.IDLE, idleTimeMs,
+        addEntry(getActivity().getString(R.string.power_idle), DrainType.IDLE, idleTimeMs,
                 R.drawable.ic_settings_phone_idle, idlePower);
     }
 
@@ -630,8 +622,9 @@ public class PowerUsageSummary extends PreferenceActivity implements Runnable {
         int btPingCount = mStats.getBluetoothPingCount();
         btPower += (btPingCount
                 * mPowerProfile.getAveragePower(PowerProfile.POWER_BLUETOOTH_AT_CMD)) / 1000;
-        BatterySipper bs = addEntry(getString(R.string.power_bluetooth), DrainType.BLUETOOTH,
-                btOnTimeMs, R.drawable.ic_settings_bluetooth, btPower + mBluetoothPower);
+        BatterySipper bs = addEntry(getActivity().getString(R.string.power_bluetooth),
+                DrainType.BLUETOOTH, btOnTimeMs, R.drawable.ic_settings_bluetooth,
+                btPower + mBluetoothPower);
         aggregateSippers(bs, mBluetoothSippers, "Bluetooth");
     }
 
@@ -682,7 +675,7 @@ public class PowerUsageSummary extends PreferenceActivity implements Runnable {
             double power) {
         if (power > mMaxPower) mMaxPower = power;
         mTotalPower += power;
-        BatterySipper bs = new BatterySipper(this, mRequestQueue, mHandler,
+        BatterySipper bs = new BatterySipper(getActivity(), mRequestQueue, mHandler,
                 label, drainType, iconId, null, new double[] {power});
         bs.usageTime = time;
         bs.iconId = iconId;