Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(449)

Side by Side Diff: chrome/android/java/src/org/chromium/chrome/browser/webapps/ActivityAssigner.java

Issue 1989283002: Upstream: Launch WebApkActivity from WebAPK. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Update ActivityAssigner. Created 4 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 2015 The Chromium Authors. All rights reserved. 1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 package org.chromium.chrome.browser.webapps; 5 package org.chromium.chrome.browser.webapps;
6 6
7 import android.content.Context; 7 import android.content.Context;
8 import android.content.SharedPreferences; 8 import android.content.SharedPreferences;
9 import android.os.SystemClock; 9 import android.os.SystemClock;
10 import android.util.Log; 10 import android.util.Log;
11 11
12 import org.chromium.base.ThreadUtils; 12 import org.chromium.base.ThreadUtils;
13 import org.chromium.base.VisibleForTesting; 13 import org.chromium.base.VisibleForTesting;
14 import org.chromium.base.metrics.RecordHistogram; 14 import org.chromium.base.metrics.RecordHistogram;
15 import org.chromium.webapk.lib.common.WebApkConstants;
15 16
16 import java.util.ArrayList; 17 import java.util.ArrayList;
17 import java.util.HashSet; 18 import java.util.HashSet;
18 import java.util.List; 19 import java.util.List;
19 import java.util.Set; 20 import java.util.Set;
20 import java.util.concurrent.TimeUnit; 21 import java.util.concurrent.TimeUnit;
21 22
22 /** 23 /**
23 * Manages a rotating LRU buffer of WebappActivities to assign webapps to. 24 * Before Lollipop, the only way to create multiple retargetable instances of th e same Activity
25 * was to explicitly define them in the Manifest. Given that the user can poten tially have an
26 * unlimited number of shortcuts for launching these Activities, we have to acti vely assign
27 * shortcuts when they launch. Activities are reused in order of when they were last used, with
28 * the least recently used ones reassigned first.
24 * 29 *
25 * In order to accommodate a limited number of WebappActivities with a potential ly unlimited number 30 * In order to accommodate a limited number of WebappActivities with a potential ly unlimited number
26 * of webapps, we have to rotate the available WebappActivities between the weba pps we start up. 31 * of webapps, we have to rotate the available WebappActivities between the weba pps we start up.
27 * Activities are reused in order of when they were last used, with the least re cently used 32 * Activities are reused in order of when they were last used, with the least re cently used
28 * ones culled first. 33 * ones culled first.
29 * 34 *
30 * It is impossible to know whether Tasks have been removed from the Recent Task list without the 35 * It is impossible to know whether Tasks have been removed from the Recent Task list without the
31 * GET_TASKS permission. As a result, the list of Activities inside the Recent Task list will 36 * GET_TASKS permission. As a result, the list of Activities inside the Recent Task list will
32 * be highly unlikely to match the list maintained in memory. Instead, we store the mapping as it 37 * be highly unlikely to match the list maintained in memory. Instead, we store the mapping as it
33 * was the last time we changed it, which allows us to launch webapps in the Web appActivity they 38 * was the last time we changed it, which allows us to launch webapps in the Web appActivity they
(...skipping 22 matching lines...) Expand all
56 // Don't ever change this. 10 is enough for everyone. 61 // Don't ever change this. 10 is enough for everyone.
57 static final int NUM_WEBAPP_ACTIVITIES = 10; 62 static final int NUM_WEBAPP_ACTIVITIES = 10;
58 63
59 // A sanity check limit to ensure that we aren't reading an unreasonable num ber of preferences. 64 // A sanity check limit to ensure that we aren't reading an unreasonable num ber of preferences.
60 // This number is different from above because the number of WebappActivitie s available may 65 // This number is different from above because the number of WebappActivitie s available may
61 // change. 66 // change.
62 static final int MAX_WEBAPP_ACTIVITIES_EVER = 100; 67 static final int MAX_WEBAPP_ACTIVITIES_EVER = 100;
63 68
64 // Don't ever change the package. Left for backwards compatibility. 69 // Don't ever change the package. Left for backwards compatibility.
65 @VisibleForTesting 70 @VisibleForTesting
66 static final String PREF_PACKAGE = "com.google.android.apps.chrome.webapps"; 71 static final String PREF_PACKAGE[] = {"com.google.android.apps.chrome.webapp s",
67 static final String PREF_NUM_SAVED_ENTRIES = "ActivityAssigner.numSavedEntri es"; 72 "com.google.android.apps.chrome.webapps.webapk"};
68 static final String PREF_ACTIVITY_INDEX = "ActivityAssigner.activityIndex"; 73
69 static final String PREF_WEBAPP_ID = "ActivityAssigner.webappId"; 74 static final String PREF_NUM_SAVED_ENTRIES[] = {"ActivityAssigner.numSavedEn tries",
75 "ActivityAssigner.numSavedEntries.webapk"};
76 static final String PREF_ACTIVITY_INDEX[] = {"ActivityAssigner.activityIndex ",
77 "ActivityAssigner.activityIndex.webapk"};
78 static final String PREF_WEBAPP_ID[] = {"ActivityAssigner.webappId",
79 "ActivityAssigner.webappId.webapk"};
70 80
71 static final int INVALID_ACTIVITY_INDEX = -1; 81 static final int INVALID_ACTIVITY_INDEX = -1;
82 static final int WEBAPP_ACTIVITY_INDEX = 0;
83 static final int WEBAPK_ACTIVITY_INDEX = 1;
84 static final int ACTIVITY_TYPE_COUNT = 2;
72 85
73 private static ActivityAssigner sInstance; 86 private static List<ActivityAssigner> sInstances;
74 87
75 private final Context mContext; 88 private final Context mContext;
76 private final List<ActivityEntry> mActivityList; 89 private final List<ActivityEntry> mActivityList;
90 // The type index of the Activities managed. Either {@link WEBAPP_ACTIVITY_I NDEX} or
91 // {@link WEBAPK_ACTIVITY_INDEX}.
92 private final int mActivityTypeIndex;
77 93
78 /** 94 /**
79 * Pre-load shared prefs to avoid being blocked on the 95 * Pre-load shared prefs to avoid being blocked on the
80 * disk access async task in the future. 96 * disk access async task in the future.
81 */ 97 */
82 public static void warmUpSharedPrefs(Context context) { 98 public static void warmUpSharedPrefs(Context context) {
83 context.getSharedPreferences(PREF_PACKAGE, Context.MODE_PRIVATE); 99 for (int i = 0; i < ACTIVITY_TYPE_COUNT; ++i) {
100 context.getSharedPreferences(PREF_PACKAGE[i], Context.MODE_PRIVATE);
101 }
84 } 102 }
85 103
86 static class ActivityEntry { 104 static class ActivityEntry {
87 final int mActivityIndex; 105 final int mActivityIndex;
88 final String mWebappId; 106 final String mWebappId;
89 107
90 ActivityEntry(int activity, String webapp) { 108 ActivityEntry(int activity, String webapp) {
91 mActivityIndex = activity; 109 mActivityIndex = activity;
92 mWebappId = webapp; 110 mWebappId = webapp;
93 } 111 }
94 } 112 }
95 113
96 /** 114 /**
97 * Returns the singleton instance, creating it if necessary. 115 * Returns the singleton instance, creating it if necessary.
116 * @param webappId The app ID.
98 */ 117 */
99 public static ActivityAssigner instance(Context context) { 118 public static ActivityAssigner instance(Context context, String webappId) {
gone 2016/05/26 18:20:36 Do we need the context passed in here, or can the
Xi Han 2016/05/26 20:54:57 Good point, removed.
100 ThreadUtils.assertOnUiThread(); 119 ThreadUtils.assertOnUiThread();
101 if (sInstance == null) { 120 if (sInstances == null) {
102 sInstance = new ActivityAssigner(context); 121 sInstances = new ArrayList<ActivityAssigner>(ACTIVITY_TYPE_COUNT);
122 for (int i = 0; i < ACTIVITY_TYPE_COUNT; ++i) {
123 sInstances.add(new ActivityAssigner(context, i));
124 }
103 } 125 }
104 return sInstance; 126 return sInstances.get(ActivityAssigner.getIndex(webappId));
105 } 127 }
106 128
107 private ActivityAssigner(Context context) { 129 private ActivityAssigner(Context context, int activityTypeIndex) {
108 mContext = context.getApplicationContext(); 130 mContext = context.getApplicationContext();
131 mActivityTypeIndex = activityTypeIndex;
109 mActivityList = new ArrayList<ActivityEntry>(); 132 mActivityList = new ArrayList<ActivityEntry>();
110
111 restoreActivityList(); 133 restoreActivityList();
112 } 134 }
113 135
114 /** 136 /**
115 * Assigns the webapp with the given ID to one of the available WebappActivi ties. 137 * Assigns the app with the given ID to one of the available Activity instan ces.
116 * If we know that the webapp was previously launched in one of the Activiti es, re-use it. 138 * If we know that the app was previously launched in one of the Activities, re-use it.
117 * Otherwise, take the least recently used WebappActivity ID and use that. 139 * Otherwise, take the least recently used ID and use that.
118 * @param webappId ID of the webapp. 140 * @param webappId ID of the webapp.
119 * @return Index of the Activity to use for the webapp. 141 * @return Index of the Activity to use for the webapp.
120 */ 142 */
121 int assign(String webappId) { 143 int assign(String webappId) {
122 // Reuse a running Activity with the same ID, if it exists. 144 // Reuse a running Activity with the same ID, if it exists.
123 int activityIndex = checkIfAssigned(webappId); 145 int activityIndex = checkIfAssigned(webappId);
124 146
125 // Allocate the one in the front of the list. 147 // Allocate the one in the front of the list.
126 if (activityIndex == INVALID_ACTIVITY_INDEX) { 148 if (activityIndex == INVALID_ACTIVITY_INDEX) {
127 activityIndex = mActivityList.get(0).mActivityIndex; 149 activityIndex = mActivityList.get(0).mActivityIndex;
128 ActivityEntry newEntry = new ActivityEntry(activityIndex, webappId); 150 ActivityEntry newEntry = new ActivityEntry(activityIndex, webappId);
129 mActivityList.set(0, newEntry); 151 mActivityList.set(0, newEntry);
130 } 152 }
131 153
132 markActivityUsed(activityIndex, webappId); 154 markActivityUsed(activityIndex, webappId);
133 return activityIndex; 155 return activityIndex;
134 } 156 }
135 157
136 /** 158 /**
159 * Returns {@link WEBAPP_ACTIVITY_INDEX} for WebappActivity, {@link WEBAPK_A CTIVITY_INDEX} for
160 * WebApkActivity whose webappId starts with "webapk:".
161 */
162 static int getIndex(String webappId) {
163 return webappId.startsWith(WebApkConstants.WEBAPK_ID_PREFIX) ? WEBAPK_AC TIVITY_INDEX
164 : WEBAPP_ACTIVITY_INDEX;
165 }
166
167 /**
137 * Checks if the webapp with the given ID has been assigned to an Activity a lready. 168 * Checks if the webapp with the given ID has been assigned to an Activity a lready.
138 * @param webappId ID of the webapp being displayed. 169 * @param webappId ID of the webapp being displayed.
139 * @return Index of the Activity for the webapp if assigned, INVALID_ACTIVIT Y_INDEX otherwise. 170 * @return Index of the Activity for the webapp if assigned, INVALID_ACTIVIT Y_INDEX otherwise.
140 */ 171 */
141 int checkIfAssigned(String webappId) { 172 int checkIfAssigned(String webappId) {
142 if (webappId == null) { 173 if (webappId == null) {
143 return INVALID_ACTIVITY_INDEX; 174 return INVALID_ACTIVITY_INDEX;
144 } 175 }
145 176
146 // Go backwards in the queue to catch more recent instances of any dupli cated webapps. 177 // Go backwards in the queue to catch more recent instances of any dupli cated webapps.
147 for (int i = mActivityList.size() - 1; i >= 0; i--) { 178 for (int i = mActivityList.size() - 1; i >= 0; i--) {
148 if (webappId.equals(mActivityList.get(i).mWebappId)) { 179 if (webappId.equals(mActivityList.get(i).mWebappId)) {
149 return mActivityList.get(i).mActivityIndex; 180 return mActivityList.get(i).mActivityIndex;
150 } 181 }
151 } 182 }
152 return INVALID_ACTIVITY_INDEX; 183 return INVALID_ACTIVITY_INDEX;
153 } 184 }
154 185
155 /** 186 /**
156 * Moves a WebappActivity to the back of the queue, indicating that the Weba pp is still in use 187 * Moves an Activity to the back of the queue, indicating that the app is st ill in use and
157 * and shouldn't be killed. 188 * shouldn't be killed.
158 * @param activityIndex Index of the WebappActivity. 189 * @param activityIndex Index of the Activity in the LRU buffer.
159 * @param webappId ID of the webapp being shown in the WebappActivity. 190 * @param webappId The ID of the app being shown in the Activity.
160 */ 191 */
161 void markActivityUsed(int activityIndex, String webappId) { 192 void markActivityUsed(int activityIndex, String webappId) {
162 // Find the entry corresponding to the Activity. 193 // Find the entry corresponding to the Activity.
163 int elementIndex = findActivityElement(activityIndex); 194 int elementIndex = findActivityElement(activityIndex);
164 195
165 if (elementIndex == -1) { 196 if (elementIndex == -1) {
166 Log.e(TAG, "Failed to find WebappActivity entry: " + activityIndex + ", " + webappId); 197 Log.e(TAG, "Failed to find WebappActivity entry: " + activityIndex + ", " + webappId);
167 return; 198 return;
168 } 199 }
169 200
170 // We have to reassign the webapp ID in case WebappActivities get repurp osed. 201 // We have to reassign the app ID in case Activities get repurposed.
171 ActivityEntry updatedEntry = new ActivityEntry(activityIndex, webappId); 202 ActivityEntry updatedEntry = new ActivityEntry(activityIndex, webappId);
172 mActivityList.remove(elementIndex); 203 mActivityList.remove(elementIndex);
173 mActivityList.add(updatedEntry); 204 mActivityList.add(updatedEntry);
174 storeActivityList(); 205 storeActivityList();
175 } 206 }
176 207
177 /** 208 /**
178 * Finds the index of the ActivityElement corresponding to the given activit yIndex. 209 * Finds the index of the ActivityElement corresponding to the given activit yIndex.
179 * @param activityIndex Index of the activity to find. 210 * @param activityIndex Index of the activity to find.
180 * @return The index of the ActivityElement in the activity list, or -1 if i t couldn't be found. 211 * @return The index of the ActivityElement in the activity list, or -1 if i t couldn't be found.
181 */ 212 */
182 private int findActivityElement(int activityIndex) { 213 private int findActivityElement(int activityIndex) {
183 for (int elementIndex = 0; elementIndex < mActivityList.size(); elementI ndex++) { 214 for (int elementIndex = 0; elementIndex < mActivityList.size(); elementI ndex++) {
184 if (mActivityList.get(elementIndex).mActivityIndex == activityIndex) { 215 if (mActivityList.get(elementIndex).mActivityIndex == activityIndex) {
185 return elementIndex; 216 return elementIndex;
186 } 217 }
187 } 218 }
188 return -1; 219 return -1;
189 } 220 }
190 221
191 /** 222 /**
192 * Returns the current mapping between Activities and webapps. 223 * Returns the current mapping between Activities and apps.
193 */ 224 */
194 @VisibleForTesting 225 @VisibleForTesting
195 List<ActivityEntry> getEntries() { 226 List<ActivityEntry> getEntries() {
196 return mActivityList; 227 return mActivityList;
197 } 228 }
198 229
199 /** 230 /**
200 * Restores/creates the mapping between webapps and WebappActivities. 231 * Returns the type index of the Activities managed.
232 */
233 @VisibleForTesting
234 int getActivityTypeIndex() {
235 return mActivityTypeIndex;
236 }
237
238 /**
239 * Restores/creates the mapping between apps and activities.
201 * The logic is slightly complicated to future-proof against situations wher e the number of 240 * The logic is slightly complicated to future-proof against situations wher e the number of
202 * WebappActivities is changed. 241 * Activity is changed.
203 */ 242 */
204 private void restoreActivityList() { 243 private void restoreActivityList() {
205 boolean isMapDirty = false; 244 boolean isMapDirty = false;
206 mActivityList.clear(); 245 mActivityList.clear();
207 246
208 // Create a Set of indices corresponding to every possible Activity. 247 // Create a Set of indices corresponding to every possible Activity.
209 // As ActivityEntries are read, they are and removed from this list to i ndicate that the 248 // As ActivityEntries are read, they are and removed from this list to i ndicate that the
210 // Activity has already been assigned. 249 // Activity has already been assigned.
211 Set<Integer> availableWebapps = new HashSet<Integer>(); 250 Set<Integer> availableWebapps = new HashSet<Integer>();
212 for (int i = 0; i < NUM_WEBAPP_ACTIVITIES; ++i) { 251 for (int i = 0; i < NUM_WEBAPP_ACTIVITIES; ++i) {
213 availableWebapps.add(i); 252 availableWebapps.add(i);
214 } 253 }
215 254
216 // Restore any entries that were previously saved. If it seems that the preferences have 255 // Restore any entries that were previously saved. If it seems that the preferences have
217 // been corrupted somehow, just discard the whole map. 256 // been corrupted somehow, just discard the whole map.
218 SharedPreferences prefs = mContext.getSharedPreferences(PREF_PACKAGE, Co ntext.MODE_PRIVATE); 257 SharedPreferences prefs = mContext.getSharedPreferences(PREF_PACKAGE[mAc tivityTypeIndex],
258 Context.MODE_PRIVATE);
219 try { 259 try {
220 long time = SystemClock.elapsedRealtime(); 260 long time = SystemClock.elapsedRealtime();
221 final int numSavedEntries = prefs.getInt(PREF_NUM_SAVED_ENTRIES, 0); 261 final int numSavedEntries = prefs.getInt(PREF_NUM_SAVED_ENTRIES[mAct ivityTypeIndex], 0);
222 try { 262 try {
223 RecordHistogram.recordTimesHistogram("Android.StrictMode.WebappS haredPrefs", 263 RecordHistogram.recordTimesHistogram("Android.StrictMode.WebappS haredPrefs",
224 SystemClock.elapsedRealtime() - time, TimeUnit.MILLISECO NDS); 264 SystemClock.elapsedRealtime() - time, TimeUnit.MILLISECO NDS);
225 } catch (UnsatisfiedLinkError error) { 265 } catch (UnsatisfiedLinkError error) {
226 // Intentionally ignored - it's ok to miss recording the metric occasionally. 266 // Intentionally ignored - it's ok to miss recording the metric occasionally.
227 } 267 }
228 if (numSavedEntries <= NUM_WEBAPP_ACTIVITIES) { 268 if (numSavedEntries <= NUM_WEBAPP_ACTIVITIES) {
229 for (int i = 0; i < numSavedEntries; ++i) { 269 for (int i = 0; i < numSavedEntries; ++i) {
230 String currentActivityIndexPref = PREF_ACTIVITY_INDEX + i; 270 String currentActivityIndexPref = PREF_ACTIVITY_INDEX[mActiv ityTypeIndex] + i;
231 String currentWebappIdPref = PREF_WEBAPP_ID + i; 271 String currentWebappIdPref = PREF_WEBAPP_ID[mActivityTypeInd ex] + i;
232 272
233 int activityIndex = prefs.getInt(currentActivityIndexPref, i ); 273 int activityIndex = prefs.getInt(currentActivityIndexPref, i );
234 String webappId = prefs.getString(currentWebappIdPref, null) ; 274 String webappId = prefs.getString(currentWebappIdPref, null) ;
235 ActivityEntry entry = new ActivityEntry(activityIndex, webap pId); 275 ActivityEntry entry = new ActivityEntry(activityIndex, webap pId);
236 276
237 if (availableWebapps.remove(entry.mActivityIndex)) { 277 if (availableWebapps.remove(entry.mActivityIndex)) {
238 mActivityList.add(entry); 278 mActivityList.add(entry);
239 } else { 279 } else {
240 // If the same activity was assigned to two different en tries, or if the 280 // If the same activity was assigned to two different en tries, or if the
241 // number of activities changed, discard it and mark tha t it needs to be 281 // number of activities changed, discard it and mark tha t it needs to be
242 // rewritten. 282 // rewritten.
243 isMapDirty = true; 283 isMapDirty = true;
244 } 284 }
245 } 285 }
246 } 286 }
247 } catch (ClassCastException exception) { 287 } catch (ClassCastException exception) {
248 // Something went wrong reading the preferences. Nuke everything. 288 // Something went wrong reading the preferences. Nuke everything.
249 mActivityList.clear(); 289 mActivityList.clear();
250 availableWebapps.clear(); 290 availableWebapps.clear();
251 for (int i = 0; i < NUM_WEBAPP_ACTIVITIES; ++i) { 291 for (int i = 0; i < NUM_WEBAPP_ACTIVITIES; ++i) {
252 availableWebapps.add(i); 292 availableWebapps.add(i);
253 } 293 }
254 } 294 }
255 295
256 // Add entries for any missing WebappActivities. 296 // Add entries for any missing Activities.
257 for (Integer availableIndex : availableWebapps) { 297 for (Integer availableIndex : availableWebapps) {
258 ActivityEntry entry = new ActivityEntry(availableIndex, null); 298 ActivityEntry entry = new ActivityEntry(availableIndex, null);
259 mActivityList.add(entry); 299 mActivityList.add(entry);
260 isMapDirty = true; 300 isMapDirty = true;
261 } 301 }
262 302
263 if (isMapDirty) { 303 if (isMapDirty) {
264 storeActivityList(); 304 storeActivityList();
265 } 305 }
266 } 306 }
267 307
268 /** 308 /**
269 * Saves the mapping between webapps and WebappActivities. 309 * Saves the mapping between apps and Activities.
270 */ 310 */
271 private void storeActivityList() { 311 private void storeActivityList() {
272 SharedPreferences prefs = mContext.getSharedPreferences(PREF_PACKAGE, Co ntext.MODE_PRIVATE); 312 SharedPreferences prefs = mContext.getSharedPreferences(PREF_PACKAGE[mAc tivityTypeIndex],
313 Context.MODE_PRIVATE);
273 SharedPreferences.Editor editor = prefs.edit(); 314 SharedPreferences.Editor editor = prefs.edit();
274 editor.clear(); 315 editor.clear();
275 editor.putInt(PREF_NUM_SAVED_ENTRIES, mActivityList.size()); 316 editor.putInt(PREF_NUM_SAVED_ENTRIES[mActivityTypeIndex], mActivityList. size());
276 for (int i = 0; i < mActivityList.size(); ++i) { 317 for (int i = 0; i < mActivityList.size(); ++i) {
277 String currentActivityIndexPref = PREF_ACTIVITY_INDEX + i; 318 String currentActivityIndexPref = PREF_ACTIVITY_INDEX[mActivityTypeI ndex] + i;
278 String currentWebappIdPref = PREF_WEBAPP_ID + i; 319 String currentWebappIdPref = PREF_WEBAPP_ID[mActivityTypeIndex] + i;
279 editor.putInt(currentActivityIndexPref, mActivityList.get(i).mActivi tyIndex); 320 editor.putInt(currentActivityIndexPref, mActivityList.get(i).mActivi tyIndex);
280 editor.putString(currentWebappIdPref, mActivityList.get(i).mWebappId ); 321 editor.putString(currentWebappIdPref, mActivityList.get(i).mWebappId );
281 } 322 }
282 editor.apply(); 323 editor.apply();
283 } 324 }
284 } 325 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698