blob: a8611d14facf3ece045bbded4ec9fee5fb55322c [file] [log] [blame]
Amith Yamasani742a6712011-05-04 14:49:28 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import android.app.AlarmManager;
Amith Yamasani483f3b02012-03-13 16:08:00 -070020import android.app.AppGlobals;
Amith Yamasani742a6712011-05-04 14:49:28 -070021import android.app.PendingIntent;
22import android.appwidget.AppWidgetManager;
23import android.appwidget.AppWidgetProviderInfo;
24import android.content.ComponentName;
25import android.content.Context;
26import android.content.Intent;
Amith Yamasani742a6712011-05-04 14:49:28 -070027import android.content.Intent.FilterComparison;
Michael Jurka61a5b012012-04-13 10:39:45 -070028import android.content.ServiceConnection;
Amith Yamasani742a6712011-05-04 14:49:28 -070029import android.content.pm.ActivityInfo;
30import android.content.pm.ApplicationInfo;
Amith Yamasani483f3b02012-03-13 16:08:00 -070031import android.content.pm.IPackageManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070032import android.content.pm.PackageInfo;
33import android.content.pm.PackageManager;
34import android.content.pm.ResolveInfo;
35import android.content.pm.ServiceInfo;
36import android.content.res.Resources;
37import android.content.res.TypedArray;
38import android.content.res.XmlResourceParser;
Jeff Browna8b9def2012-07-23 14:22:49 -070039import android.graphics.Point;
Amith Yamasani742a6712011-05-04 14:49:28 -070040import android.net.Uri;
41import android.os.Binder;
42import android.os.Bundle;
Amith Yamasani61f57372012-08-31 12:12:28 -070043import android.os.Environment;
Adam Cohena1a2f962012-11-01 14:06:16 -070044import android.os.Handler;
45import android.os.HandlerThread;
Amith Yamasani742a6712011-05-04 14:49:28 -070046import android.os.IBinder;
Adam Cohena1a2f962012-11-01 14:06:16 -070047import android.os.Looper;
Jim Millerf229e4d32012-09-12 20:32:50 -070048import android.os.Process;
Amith Yamasani742a6712011-05-04 14:49:28 -070049import android.os.RemoteException;
50import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070051import android.os.UserHandle;
Dianne Hackborn39606a02012-07-31 17:54:35 -070052import android.util.AtomicFile;
Amith Yamasani742a6712011-05-04 14:49:28 -070053import android.util.AttributeSet;
54import android.util.Log;
55import android.util.Pair;
56import android.util.Slog;
57import android.util.TypedValue;
58import android.util.Xml;
Jeff Browna8b9def2012-07-23 14:22:49 -070059import android.view.Display;
Adam Cohen311c79c2012-05-10 14:44:38 -070060import android.view.WindowManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070061import android.widget.RemoteViews;
62
63import com.android.internal.appwidget.IAppWidgetHost;
Amith Yamasani742a6712011-05-04 14:49:28 -070064import com.android.internal.util.FastXmlSerializer;
65import com.android.internal.widget.IRemoteViewsAdapterConnection;
66import com.android.internal.widget.IRemoteViewsFactory;
Amith Yamasani742a6712011-05-04 14:49:28 -070067
68import org.xmlpull.v1.XmlPullParser;
69import org.xmlpull.v1.XmlPullParserException;
70import org.xmlpull.v1.XmlSerializer;
71
72import java.io.File;
73import java.io.FileDescriptor;
74import java.io.FileInputStream;
75import java.io.FileNotFoundException;
76import java.io.FileOutputStream;
77import java.io.IOException;
78import java.io.PrintWriter;
79import java.util.ArrayList;
80import java.util.HashMap;
81import java.util.HashSet;
82import java.util.Iterator;
83import java.util.List;
84import java.util.Locale;
85import java.util.Set;
86
87class AppWidgetServiceImpl {
88
89 private static final String TAG = "AppWidgetServiceImpl";
90 private static final String SETTINGS_FILENAME = "appwidgets.xml";
91 private static final int MIN_UPDATE_PERIOD = 30 * 60 * 1000; // 30 minutes
92
Amith Yamasani8320de82012-10-05 16:10:38 -070093 private static boolean DBG = false;
94
Amith Yamasani742a6712011-05-04 14:49:28 -070095 /*
96 * When identifying a Host or Provider based on the calling process, use the uid field. When
97 * identifying a Host or Provider based on a package manager broadcast, use the package given.
98 */
99
100 static class Provider {
101 int uid;
102 AppWidgetProviderInfo info;
103 ArrayList<AppWidgetId> instances = new ArrayList<AppWidgetId>();
104 PendingIntent broadcast;
105 boolean zombie; // if we're in safe mode, don't prune this just because nobody references it
106
107 int tag; // for use while saving state (the index)
108 }
109
110 static class Host {
111 int uid;
112 int hostId;
113 String packageName;
114 ArrayList<AppWidgetId> instances = new ArrayList<AppWidgetId>();
115 IAppWidgetHost callbacks;
116 boolean zombie; // if we're in safe mode, don't prune this just because nobody references it
117
118 int tag; // for use while saving state (the index)
119 }
120
121 static class AppWidgetId {
122 int appWidgetId;
123 Provider provider;
124 RemoteViews views;
Adam Cohend2097eb2012-05-01 18:10:28 -0700125 Bundle options;
Amith Yamasani742a6712011-05-04 14:49:28 -0700126 Host host;
127 }
128
129 /**
130 * Acts as a proxy between the ServiceConnection and the RemoteViewsAdapterConnection. This
131 * needs to be a static inner class since a reference to the ServiceConnection is held globally
132 * and may lead us to leak AppWidgetService instances (if there were more than one).
133 */
134 static class ServiceConnectionProxy implements ServiceConnection {
135 private final IBinder mConnectionCb;
136
137 ServiceConnectionProxy(Pair<Integer, Intent.FilterComparison> key, IBinder connectionCb) {
138 mConnectionCb = connectionCb;
139 }
140
141 public void onServiceConnected(ComponentName name, IBinder service) {
142 final IRemoteViewsAdapterConnection cb = IRemoteViewsAdapterConnection.Stub
143 .asInterface(mConnectionCb);
144 try {
145 cb.onServiceConnected(service);
146 } catch (Exception e) {
147 e.printStackTrace();
148 }
149 }
150
151 public void onServiceDisconnected(ComponentName name) {
152 disconnect();
153 }
154
155 public void disconnect() {
156 final IRemoteViewsAdapterConnection cb = IRemoteViewsAdapterConnection.Stub
157 .asInterface(mConnectionCb);
158 try {
159 cb.onServiceDisconnected();
160 } catch (Exception e) {
161 e.printStackTrace();
162 }
163 }
164 }
165
166 // Manages active connections to RemoteViewsServices
167 private final HashMap<Pair<Integer, FilterComparison>, ServiceConnection> mBoundRemoteViewsServices = new HashMap<Pair<Integer, FilterComparison>, ServiceConnection>();
168 // Manages persistent references to RemoteViewsServices from different App Widgets
169 private final HashMap<FilterComparison, HashSet<Integer>> mRemoteViewsServicesAppWidgets = new HashMap<FilterComparison, HashSet<Integer>>();
170
171 Context mContext;
172 Locale mLocale;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700173 IPackageManager mPm;
Amith Yamasani742a6712011-05-04 14:49:28 -0700174 AlarmManager mAlarmManager;
175 ArrayList<Provider> mInstalledProviders = new ArrayList<Provider>();
176 int mNextAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID + 1;
177 final ArrayList<AppWidgetId> mAppWidgetIds = new ArrayList<AppWidgetId>();
178 ArrayList<Host> mHosts = new ArrayList<Host>();
Michael Jurka61a5b012012-04-13 10:39:45 -0700179 // set of package names
180 HashSet<String> mPackagesWithBindWidgetPermission = new HashSet<String>();
Amith Yamasani742a6712011-05-04 14:49:28 -0700181 boolean mSafeMode;
182 int mUserId;
183 boolean mStateLoaded;
Adam Cohen311c79c2012-05-10 14:44:38 -0700184 int mMaxWidgetBitmapMemory;
Amith Yamasani742a6712011-05-04 14:49:28 -0700185
Adam Cohena1a2f962012-11-01 14:06:16 -0700186 private final Handler mSaveStateHandler;
187
Amith Yamasani742a6712011-05-04 14:49:28 -0700188 // These are for debugging only -- widgets are going missing in some rare instances
189 ArrayList<Provider> mDeletedProviders = new ArrayList<Provider>();
190 ArrayList<Host> mDeletedHosts = new ArrayList<Host>();
191
Adam Cohena1a2f962012-11-01 14:06:16 -0700192 AppWidgetServiceImpl(Context context, int userId, Handler saveStateHandler) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700193 mContext = context;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700194 mPm = AppGlobals.getPackageManager();
Amith Yamasani742a6712011-05-04 14:49:28 -0700195 mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
196 mUserId = userId;
Adam Cohena1a2f962012-11-01 14:06:16 -0700197 mSaveStateHandler = saveStateHandler;
Adam Cohen311c79c2012-05-10 14:44:38 -0700198 computeMaximumWidgetBitmapMemory();
199 }
200
201 void computeMaximumWidgetBitmapMemory() {
202 WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
Jeff Browna8b9def2012-07-23 14:22:49 -0700203 Display display = wm.getDefaultDisplay();
204 Point size = new Point();
205 display.getRealSize(size);
Winson Chunge92aad42012-06-22 14:11:47 -0700206 // Cap memory usage at 1.5 times the size of the display
207 // 1.5 * 4 bytes/pixel * w * h ==> 6 * w * h
Jeff Browna8b9def2012-07-23 14:22:49 -0700208 mMaxWidgetBitmapMemory = 6 * size.x * size.y;
Amith Yamasani742a6712011-05-04 14:49:28 -0700209 }
210
211 public void systemReady(boolean safeMode) {
212 mSafeMode = safeMode;
213
214 synchronized (mAppWidgetIds) {
215 ensureStateLoadedLocked();
216 }
217 }
218
Amith Yamasani8320de82012-10-05 16:10:38 -0700219 private void log(String msg) {
220 Slog.i(TAG, "u=" + mUserId + ": " + msg);
221 }
222
Amith Yamasani742a6712011-05-04 14:49:28 -0700223 void onConfigurationChanged() {
Amith Yamasani8320de82012-10-05 16:10:38 -0700224 if (DBG) log("Got onConfigurationChanged()");
Amith Yamasani742a6712011-05-04 14:49:28 -0700225 Locale revised = Locale.getDefault();
226 if (revised == null || mLocale == null || !(revised.equals(mLocale))) {
227 mLocale = revised;
228
229 synchronized (mAppWidgetIds) {
230 ensureStateLoadedLocked();
Winson Chunga3195052012-06-25 10:02:10 -0700231 // Note: updateProvidersForPackageLocked() may remove providers, so we must copy the
232 // list of installed providers and skip providers that we don't need to update.
233 // Also note that remove the provider does not clear the Provider component data.
234 ArrayList<Provider> installedProviders =
235 new ArrayList<Provider>(mInstalledProviders);
236 HashSet<ComponentName> removedProviders = new HashSet<ComponentName>();
237 int N = installedProviders.size();
Amith Yamasani742a6712011-05-04 14:49:28 -0700238 for (int i = N - 1; i >= 0; i--) {
Winson Chunga3195052012-06-25 10:02:10 -0700239 Provider p = installedProviders.get(i);
240 ComponentName cn = p.info.provider;
241 if (!removedProviders.contains(cn)) {
242 updateProvidersForPackageLocked(cn.getPackageName(), removedProviders);
243 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700244 }
Adam Cohena1a2f962012-11-01 14:06:16 -0700245 saveStateAsync();
Amith Yamasani742a6712011-05-04 14:49:28 -0700246 }
247 }
248 }
249
250 void onBroadcastReceived(Intent intent) {
Amith Yamasani8320de82012-10-05 16:10:38 -0700251 if (DBG) log("onBroadcast " + intent);
Amith Yamasani742a6712011-05-04 14:49:28 -0700252 final String action = intent.getAction();
253 boolean added = false;
254 boolean changed = false;
Winson Chung7fbd2842012-06-13 10:35:51 -0700255 boolean providersModified = false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700256 String pkgList[] = null;
257 if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
258 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
259 added = true;
260 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
261 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
262 added = false;
263 } else {
264 Uri uri = intent.getData();
265 if (uri == null) {
266 return;
267 }
268 String pkgName = uri.getSchemeSpecificPart();
269 if (pkgName == null) {
270 return;
271 }
272 pkgList = new String[] { pkgName };
273 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
274 changed = Intent.ACTION_PACKAGE_CHANGED.equals(action);
275 }
276 if (pkgList == null || pkgList.length == 0) {
277 return;
278 }
279 if (added || changed) {
280 synchronized (mAppWidgetIds) {
281 ensureStateLoadedLocked();
282 Bundle extras = intent.getExtras();
283 if (changed
284 || (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false))) {
285 for (String pkgName : pkgList) {
286 // The package was just upgraded
Winson Chunga3195052012-06-25 10:02:10 -0700287 providersModified |= updateProvidersForPackageLocked(pkgName, null);
Amith Yamasani742a6712011-05-04 14:49:28 -0700288 }
289 } else {
290 // The package was just added
291 for (String pkgName : pkgList) {
Winson Chung7fbd2842012-06-13 10:35:51 -0700292 providersModified |= addProvidersForPackageLocked(pkgName);
Amith Yamasani742a6712011-05-04 14:49:28 -0700293 }
294 }
Adam Cohena1a2f962012-11-01 14:06:16 -0700295 saveStateAsync();
Amith Yamasani742a6712011-05-04 14:49:28 -0700296 }
297 } else {
298 Bundle extras = intent.getExtras();
299 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
300 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
301 } else {
302 synchronized (mAppWidgetIds) {
303 ensureStateLoadedLocked();
304 for (String pkgName : pkgList) {
Winson Chung7fbd2842012-06-13 10:35:51 -0700305 providersModified |= removeProvidersForPackageLocked(pkgName);
Adam Cohena1a2f962012-11-01 14:06:16 -0700306 saveStateAsync();
Amith Yamasani742a6712011-05-04 14:49:28 -0700307 }
308 }
309 }
310 }
Winson Chung7fbd2842012-06-13 10:35:51 -0700311
312 if (providersModified) {
313 // If the set of providers has been modified, notify each active AppWidgetHost
314 synchronized (mAppWidgetIds) {
315 ensureStateLoadedLocked();
316 notifyHostsForProvidersChangedLocked();
317 }
318 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700319 }
320
321 private void dumpProvider(Provider p, int index, PrintWriter pw) {
322 AppWidgetProviderInfo info = p.info;
323 pw.print(" ["); pw.print(index); pw.print("] provider ");
324 pw.print(info.provider.flattenToShortString());
325 pw.println(':');
326 pw.print(" min=("); pw.print(info.minWidth);
327 pw.print("x"); pw.print(info.minHeight);
328 pw.print(") minResize=("); pw.print(info.minResizeWidth);
329 pw.print("x"); pw.print(info.minResizeHeight);
330 pw.print(") updatePeriodMillis=");
331 pw.print(info.updatePeriodMillis);
332 pw.print(" resizeMode=");
333 pw.print(info.resizeMode);
Adam Cohen0aa2d422012-09-07 17:37:26 -0700334 pw.print(info.widgetCategory);
Amith Yamasani742a6712011-05-04 14:49:28 -0700335 pw.print(" autoAdvanceViewId=");
336 pw.print(info.autoAdvanceViewId);
337 pw.print(" initialLayout=#");
338 pw.print(Integer.toHexString(info.initialLayout));
339 pw.print(" zombie="); pw.println(p.zombie);
340 }
341
342 private void dumpHost(Host host, int index, PrintWriter pw) {
343 pw.print(" ["); pw.print(index); pw.print("] hostId=");
344 pw.print(host.hostId); pw.print(' ');
345 pw.print(host.packageName); pw.print('/');
346 pw.print(host.uid); pw.println(':');
347 pw.print(" callbacks="); pw.println(host.callbacks);
348 pw.print(" instances.size="); pw.print(host.instances.size());
349 pw.print(" zombie="); pw.println(host.zombie);
350 }
351
352 private void dumpAppWidgetId(AppWidgetId id, int index, PrintWriter pw) {
353 pw.print(" ["); pw.print(index); pw.print("] id=");
354 pw.println(id.appWidgetId);
355 pw.print(" hostId=");
356 pw.print(id.host.hostId); pw.print(' ');
357 pw.print(id.host.packageName); pw.print('/');
358 pw.println(id.host.uid);
359 if (id.provider != null) {
360 pw.print(" provider=");
361 pw.println(id.provider.info.provider.flattenToShortString());
362 }
363 if (id.host != null) {
364 pw.print(" host.callbacks="); pw.println(id.host.callbacks);
365 }
366 if (id.views != null) {
367 pw.print(" views="); pw.println(id.views);
368 }
369 }
370
371 void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
372 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
373 != PackageManager.PERMISSION_GRANTED) {
374 pw.println("Permission Denial: can't dump from from pid="
375 + Binder.getCallingPid()
376 + ", uid=" + Binder.getCallingUid());
377 return;
378 }
379
380 synchronized (mAppWidgetIds) {
381 int N = mInstalledProviders.size();
382 pw.println("Providers:");
383 for (int i=0; i<N; i++) {
384 dumpProvider(mInstalledProviders.get(i), i, pw);
385 }
386
387 N = mAppWidgetIds.size();
388 pw.println(" ");
389 pw.println("AppWidgetIds:");
390 for (int i=0; i<N; i++) {
391 dumpAppWidgetId(mAppWidgetIds.get(i), i, pw);
392 }
393
394 N = mHosts.size();
395 pw.println(" ");
396 pw.println("Hosts:");
397 for (int i=0; i<N; i++) {
398 dumpHost(mHosts.get(i), i, pw);
399 }
400
401 N = mDeletedProviders.size();
402 pw.println(" ");
403 pw.println("Deleted Providers:");
404 for (int i=0; i<N; i++) {
405 dumpProvider(mDeletedProviders.get(i), i, pw);
406 }
407
408 N = mDeletedHosts.size();
409 pw.println(" ");
410 pw.println("Deleted Hosts:");
411 for (int i=0; i<N; i++) {
412 dumpHost(mDeletedHosts.get(i), i, pw);
413 }
414 }
415 }
416
417 private void ensureStateLoadedLocked() {
418 if (!mStateLoaded) {
Adam Cohena1a2f962012-11-01 14:06:16 -0700419 loadAppWidgetListLocked();
Amith Yamasani742a6712011-05-04 14:49:28 -0700420 loadStateLocked();
421 mStateLoaded = true;
422 }
423 }
424
425 public int allocateAppWidgetId(String packageName, int hostId) {
Jim Millerf229e4d32012-09-12 20:32:50 -0700426 int callingUid = enforceSystemOrCallingUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -0700427 synchronized (mAppWidgetIds) {
428 ensureStateLoadedLocked();
429 int appWidgetId = mNextAppWidgetId++;
430
431 Host host = lookupOrAddHostLocked(callingUid, packageName, hostId);
432
433 AppWidgetId id = new AppWidgetId();
434 id.appWidgetId = appWidgetId;
435 id.host = host;
436
437 host.instances.add(id);
438 mAppWidgetIds.add(id);
439
Adam Cohena1a2f962012-11-01 14:06:16 -0700440 saveStateAsync();
Amith Yamasani8320de82012-10-05 16:10:38 -0700441 if (DBG) log("Allocating AppWidgetId for " + packageName + " host=" + hostId
442 + " id=" + appWidgetId);
Amith Yamasani742a6712011-05-04 14:49:28 -0700443 return appWidgetId;
444 }
445 }
446
447 public void deleteAppWidgetId(int appWidgetId) {
448 synchronized (mAppWidgetIds) {
449 ensureStateLoadedLocked();
450 AppWidgetId id = lookupAppWidgetIdLocked(appWidgetId);
451 if (id != null) {
452 deleteAppWidgetLocked(id);
Adam Cohena1a2f962012-11-01 14:06:16 -0700453 saveStateAsync();
Amith Yamasani742a6712011-05-04 14:49:28 -0700454 }
455 }
456 }
457
458 public void deleteHost(int hostId) {
459 synchronized (mAppWidgetIds) {
460 ensureStateLoadedLocked();
461 int callingUid = Binder.getCallingUid();
462 Host host = lookupHostLocked(callingUid, hostId);
463 if (host != null) {
464 deleteHostLocked(host);
Adam Cohena1a2f962012-11-01 14:06:16 -0700465 saveStateAsync();
Amith Yamasani742a6712011-05-04 14:49:28 -0700466 }
467 }
468 }
469
470 public void deleteAllHosts() {
471 synchronized (mAppWidgetIds) {
472 ensureStateLoadedLocked();
473 int callingUid = Binder.getCallingUid();
474 final int N = mHosts.size();
475 boolean changed = false;
476 for (int i = N - 1; i >= 0; i--) {
477 Host host = mHosts.get(i);
478 if (host.uid == callingUid) {
479 deleteHostLocked(host);
480 changed = true;
481 }
482 }
483 if (changed) {
Adam Cohena1a2f962012-11-01 14:06:16 -0700484 saveStateAsync();
Amith Yamasani742a6712011-05-04 14:49:28 -0700485 }
486 }
487 }
488
489 void deleteHostLocked(Host host) {
490 final int N = host.instances.size();
491 for (int i = N - 1; i >= 0; i--) {
492 AppWidgetId id = host.instances.get(i);
493 deleteAppWidgetLocked(id);
494 }
495 host.instances.clear();
496 mHosts.remove(host);
497 mDeletedHosts.add(host);
498 // it's gone or going away, abruptly drop the callback connection
499 host.callbacks = null;
500 }
501
502 void deleteAppWidgetLocked(AppWidgetId id) {
503 // We first unbind all services that are bound to this id
504 unbindAppWidgetRemoteViewsServicesLocked(id);
505
506 Host host = id.host;
507 host.instances.remove(id);
508 pruneHostLocked(host);
509
510 mAppWidgetIds.remove(id);
511
512 Provider p = id.provider;
513 if (p != null) {
514 p.instances.remove(id);
515 if (!p.zombie) {
516 // send the broacast saying that this appWidgetId has been deleted
517 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_DELETED);
518 intent.setComponent(p.info.provider);
519 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id.appWidgetId);
Dianne Hackborn79af1dd2012-08-16 16:42:52 -0700520 mContext.sendBroadcastAsUser(intent, new UserHandle(mUserId));
Amith Yamasani742a6712011-05-04 14:49:28 -0700521 if (p.instances.size() == 0) {
522 // cancel the future updates
523 cancelBroadcasts(p);
524
525 // send the broacast saying that the provider is not in use any more
526 intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_DISABLED);
527 intent.setComponent(p.info.provider);
Dianne Hackborn79af1dd2012-08-16 16:42:52 -0700528 mContext.sendBroadcastAsUser(intent, new UserHandle(mUserId));
Amith Yamasani742a6712011-05-04 14:49:28 -0700529 }
530 }
531 }
532 }
533
534 void cancelBroadcasts(Provider p) {
Amith Yamasani8320de82012-10-05 16:10:38 -0700535 if (DBG) log("cancelBroadcasts for " + p);
Amith Yamasani742a6712011-05-04 14:49:28 -0700536 if (p.broadcast != null) {
537 mAlarmManager.cancel(p.broadcast);
538 long token = Binder.clearCallingIdentity();
539 try {
540 p.broadcast.cancel();
541 } finally {
542 Binder.restoreCallingIdentity(token);
543 }
544 p.broadcast = null;
545 }
546 }
547
Adam Cohen0aa2d422012-09-07 17:37:26 -0700548 private void bindAppWidgetIdImpl(int appWidgetId, ComponentName provider, Bundle options) {
Amith Yamasani8320de82012-10-05 16:10:38 -0700549 if (DBG) log("bindAppWidgetIdImpl appwid=" + appWidgetId
550 + " provider=" + provider);
Amith Yamasani742a6712011-05-04 14:49:28 -0700551 final long ident = Binder.clearCallingIdentity();
552 try {
553 synchronized (mAppWidgetIds) {
Adam Cohen3ff2d862012-09-26 14:07:57 -0700554 options = cloneIfLocalBinder(options);
Amith Yamasani742a6712011-05-04 14:49:28 -0700555 ensureStateLoadedLocked();
556 AppWidgetId id = lookupAppWidgetIdLocked(appWidgetId);
557 if (id == null) {
558 throw new IllegalArgumentException("bad appWidgetId");
559 }
560 if (id.provider != null) {
561 throw new IllegalArgumentException("appWidgetId " + appWidgetId
562 + " already bound to " + id.provider.info.provider);
563 }
564 Provider p = lookupProviderLocked(provider);
565 if (p == null) {
566 throw new IllegalArgumentException("not a appwidget provider: " + provider);
567 }
568 if (p.zombie) {
569 throw new IllegalArgumentException("can't bind to a 3rd party provider in"
570 + " safe mode: " + provider);
571 }
572
Amith Yamasani742a6712011-05-04 14:49:28 -0700573 id.provider = p;
Adam Cohen0aa2d422012-09-07 17:37:26 -0700574 if (options == null) {
575 options = new Bundle();
576 }
577 id.options = options;
578
579 // We need to provide a default value for the widget category if it is not specified
580 if (!options.containsKey(AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY)) {
581 options.putInt(AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY,
582 AppWidgetProviderInfo.WIDGET_CATEGORY_HOME_SCREEN);
583 }
584
Amith Yamasani742a6712011-05-04 14:49:28 -0700585 p.instances.add(id);
586 int instancesSize = p.instances.size();
587 if (instancesSize == 1) {
588 // tell the provider that it's ready
589 sendEnableIntentLocked(p);
590 }
591
592 // send an update now -- We need this update now, and just for this appWidgetId.
593 // It's less critical when the next one happens, so when we schedule the next one,
594 // we add updatePeriodMillis to its start time. That time will have some slop,
595 // but that's okay.
596 sendUpdateIntentLocked(p, new int[] { appWidgetId });
597
598 // schedule the future updates
599 registerForBroadcastsLocked(p, getAppWidgetIds(p));
Adam Cohena1a2f962012-11-01 14:06:16 -0700600 saveStateAsync();
Amith Yamasani742a6712011-05-04 14:49:28 -0700601 }
602 } finally {
603 Binder.restoreCallingIdentity(ident);
604 }
605 }
606
Adam Cohen0aa2d422012-09-07 17:37:26 -0700607 public void bindAppWidgetId(int appWidgetId, ComponentName provider, Bundle options) {
Michael Jurka67a871d2012-11-01 18:26:01 -0700608 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BIND_APPWIDGET,
Michael Jurka61a5b012012-04-13 10:39:45 -0700609 "bindAppWidgetId appWidgetId=" + appWidgetId + " provider=" + provider);
Adam Cohen0aa2d422012-09-07 17:37:26 -0700610 bindAppWidgetIdImpl(appWidgetId, provider, options);
Michael Jurka61a5b012012-04-13 10:39:45 -0700611 }
612
613 public boolean bindAppWidgetIdIfAllowed(
Adam Cohen0aa2d422012-09-07 17:37:26 -0700614 String packageName, int appWidgetId, ComponentName provider, Bundle options) {
Michael Jurka61a5b012012-04-13 10:39:45 -0700615 try {
Michael Jurka67a871d2012-11-01 18:26:01 -0700616 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BIND_APPWIDGET, null);
Michael Jurka61a5b012012-04-13 10:39:45 -0700617 } catch (SecurityException se) {
618 if (!callerHasBindAppWidgetPermission(packageName)) {
619 return false;
620 }
621 }
Adam Cohen0aa2d422012-09-07 17:37:26 -0700622 bindAppWidgetIdImpl(appWidgetId, provider, options);
Michael Jurka61a5b012012-04-13 10:39:45 -0700623 return true;
624 }
625
626 private boolean callerHasBindAppWidgetPermission(String packageName) {
627 int callingUid = Binder.getCallingUid();
628 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700629 if (!UserHandle.isSameApp(callingUid, getUidForPackage(packageName))) {
Michael Jurka61a5b012012-04-13 10:39:45 -0700630 return false;
631 }
632 } catch (Exception e) {
633 return false;
634 }
635 synchronized (mAppWidgetIds) {
636 ensureStateLoadedLocked();
637 return mPackagesWithBindWidgetPermission.contains(packageName);
638 }
639 }
640
641 public boolean hasBindAppWidgetPermission(String packageName) {
642 mContext.enforceCallingPermission(
643 android.Manifest.permission.MODIFY_APPWIDGET_BIND_PERMISSIONS,
644 "hasBindAppWidgetPermission packageName=" + packageName);
645
646 synchronized (mAppWidgetIds) {
647 ensureStateLoadedLocked();
648 return mPackagesWithBindWidgetPermission.contains(packageName);
649 }
650 }
651
652 public void setBindAppWidgetPermission(String packageName, boolean permission) {
653 mContext.enforceCallingPermission(
654 android.Manifest.permission.MODIFY_APPWIDGET_BIND_PERMISSIONS,
655 "setBindAppWidgetPermission packageName=" + packageName);
656
657 synchronized (mAppWidgetIds) {
658 ensureStateLoadedLocked();
659 if (permission) {
660 mPackagesWithBindWidgetPermission.add(packageName);
661 } else {
662 mPackagesWithBindWidgetPermission.remove(packageName);
663 }
Adam Cohena1a2f962012-11-01 14:06:16 -0700664 saveStateAsync();
Michael Jurka61a5b012012-04-13 10:39:45 -0700665 }
Michael Jurka61a5b012012-04-13 10:39:45 -0700666 }
667
Amith Yamasani742a6712011-05-04 14:49:28 -0700668 // Binds to a specific RemoteViewsService
669 public void bindRemoteViewsService(int appWidgetId, Intent intent, IBinder connection) {
670 synchronized (mAppWidgetIds) {
671 ensureStateLoadedLocked();
672 AppWidgetId id = lookupAppWidgetIdLocked(appWidgetId);
673 if (id == null) {
674 throw new IllegalArgumentException("bad appWidgetId");
675 }
676 final ComponentName componentName = intent.getComponent();
677 try {
Amith Yamasani98edc952012-09-25 14:09:27 -0700678 final ServiceInfo si = AppGlobals.getPackageManager().getServiceInfo(componentName,
679 PackageManager.GET_PERMISSIONS, mUserId);
Amith Yamasani742a6712011-05-04 14:49:28 -0700680 if (!android.Manifest.permission.BIND_REMOTEVIEWS.equals(si.permission)) {
681 throw new SecurityException("Selected service does not require "
682 + android.Manifest.permission.BIND_REMOTEVIEWS + ": " + componentName);
683 }
Amith Yamasani98edc952012-09-25 14:09:27 -0700684 } catch (RemoteException e) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700685 throw new IllegalArgumentException("Unknown component " + componentName);
686 }
687
688 // If there is already a connection made for this service intent, then disconnect from
689 // that first. (This does not allow multiple connections to the same service under
690 // the same key)
691 ServiceConnectionProxy conn = null;
692 FilterComparison fc = new FilterComparison(intent);
693 Pair<Integer, FilterComparison> key = Pair.create(appWidgetId, fc);
694 if (mBoundRemoteViewsServices.containsKey(key)) {
695 conn = (ServiceConnectionProxy) mBoundRemoteViewsServices.get(key);
696 conn.disconnect();
697 mContext.unbindService(conn);
698 mBoundRemoteViewsServices.remove(key);
699 }
700
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700701 int userId = UserHandle.getUserId(id.provider.uid);
Amith Yamasani742a6712011-05-04 14:49:28 -0700702 // Bind to the RemoteViewsService (which will trigger a callback to the
703 // RemoteViewsAdapter.onServiceConnected())
704 final long token = Binder.clearCallingIdentity();
705 try {
706 conn = new ServiceConnectionProxy(key, connection);
Amith Yamasani37ce3a82012-02-06 12:04:42 -0800707 mContext.bindService(intent, conn, Context.BIND_AUTO_CREATE, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -0700708 mBoundRemoteViewsServices.put(key, conn);
709 } finally {
710 Binder.restoreCallingIdentity(token);
711 }
712
713 // Add it to the mapping of RemoteViewsService to appWidgetIds so that we can determine
714 // when we can call back to the RemoteViewsService later to destroy associated
715 // factories.
716 incrementAppWidgetServiceRefCount(appWidgetId, fc);
717 }
718 }
719
720 // Unbinds from a specific RemoteViewsService
721 public void unbindRemoteViewsService(int appWidgetId, Intent intent) {
722 synchronized (mAppWidgetIds) {
723 ensureStateLoadedLocked();
724 // Unbind from the RemoteViewsService (which will trigger a callback to the bound
725 // RemoteViewsAdapter)
726 Pair<Integer, FilterComparison> key = Pair.create(appWidgetId, new FilterComparison(
727 intent));
728 if (mBoundRemoteViewsServices.containsKey(key)) {
729 // We don't need to use the appWidgetId until after we are sure there is something
730 // to unbind. Note that this may mask certain issues with apps calling unbind()
731 // more than necessary.
732 AppWidgetId id = lookupAppWidgetIdLocked(appWidgetId);
733 if (id == null) {
734 throw new IllegalArgumentException("bad appWidgetId");
735 }
736
737 ServiceConnectionProxy conn = (ServiceConnectionProxy) mBoundRemoteViewsServices
738 .get(key);
739 conn.disconnect();
740 mContext.unbindService(conn);
741 mBoundRemoteViewsServices.remove(key);
742 } else {
743 Log.e("AppWidgetService", "Error (unbindRemoteViewsService): Connection not bound");
744 }
745 }
746 }
747
748 // Unbinds from a RemoteViewsService when we delete an app widget
749 private void unbindAppWidgetRemoteViewsServicesLocked(AppWidgetId id) {
750 int appWidgetId = id.appWidgetId;
751 // Unbind all connections to Services bound to this AppWidgetId
752 Iterator<Pair<Integer, Intent.FilterComparison>> it = mBoundRemoteViewsServices.keySet()
753 .iterator();
754 while (it.hasNext()) {
755 final Pair<Integer, Intent.FilterComparison> key = it.next();
756 if (key.first.intValue() == appWidgetId) {
757 final ServiceConnectionProxy conn = (ServiceConnectionProxy) mBoundRemoteViewsServices
758 .get(key);
759 conn.disconnect();
760 mContext.unbindService(conn);
761 it.remove();
762 }
763 }
764
765 // Check if we need to destroy any services (if no other app widgets are
766 // referencing the same service)
Amith Yamasani37ce3a82012-02-06 12:04:42 -0800767 decrementAppWidgetServiceRefCount(id);
Amith Yamasani742a6712011-05-04 14:49:28 -0700768 }
769
770 // Destroys the cached factory on the RemoteViewsService's side related to the specified intent
Amith Yamasani37ce3a82012-02-06 12:04:42 -0800771 private void destroyRemoteViewsService(final Intent intent, AppWidgetId id) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700772 final ServiceConnection conn = new ServiceConnection() {
773 @Override
774 public void onServiceConnected(ComponentName name, IBinder service) {
775 final IRemoteViewsFactory cb = IRemoteViewsFactory.Stub.asInterface(service);
776 try {
777 cb.onDestroy(intent);
778 } catch (RemoteException e) {
779 e.printStackTrace();
780 } catch (RuntimeException e) {
781 e.printStackTrace();
782 }
783 mContext.unbindService(this);
784 }
785
786 @Override
787 public void onServiceDisconnected(android.content.ComponentName name) {
788 // Do nothing
789 }
790 };
791
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700792 int userId = UserHandle.getUserId(id.provider.uid);
Amith Yamasani742a6712011-05-04 14:49:28 -0700793 // Bind to the service and remove the static intent->factory mapping in the
794 // RemoteViewsService.
795 final long token = Binder.clearCallingIdentity();
796 try {
Amith Yamasani37ce3a82012-02-06 12:04:42 -0800797 mContext.bindService(intent, conn, Context.BIND_AUTO_CREATE, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -0700798 } finally {
799 Binder.restoreCallingIdentity(token);
800 }
801 }
802
803 // Adds to the ref-count for a given RemoteViewsService intent
804 private void incrementAppWidgetServiceRefCount(int appWidgetId, FilterComparison fc) {
805 HashSet<Integer> appWidgetIds = null;
806 if (mRemoteViewsServicesAppWidgets.containsKey(fc)) {
807 appWidgetIds = mRemoteViewsServicesAppWidgets.get(fc);
808 } else {
809 appWidgetIds = new HashSet<Integer>();
810 mRemoteViewsServicesAppWidgets.put(fc, appWidgetIds);
811 }
812 appWidgetIds.add(appWidgetId);
813 }
814
815 // Subtracts from the ref-count for a given RemoteViewsService intent, prompting a delete if
816 // the ref-count reaches zero.
Amith Yamasani37ce3a82012-02-06 12:04:42 -0800817 private void decrementAppWidgetServiceRefCount(AppWidgetId id) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700818 Iterator<FilterComparison> it = mRemoteViewsServicesAppWidgets.keySet().iterator();
819 while (it.hasNext()) {
820 final FilterComparison key = it.next();
821 final HashSet<Integer> ids = mRemoteViewsServicesAppWidgets.get(key);
Amith Yamasani37ce3a82012-02-06 12:04:42 -0800822 if (ids.remove(id.appWidgetId)) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700823 // If we have removed the last app widget referencing this service, then we
824 // should destroy it and remove it from this set
825 if (ids.isEmpty()) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -0800826 destroyRemoteViewsService(key.getIntent(), id);
Amith Yamasani742a6712011-05-04 14:49:28 -0700827 it.remove();
828 }
829 }
830 }
831 }
832
833 public AppWidgetProviderInfo getAppWidgetInfo(int appWidgetId) {
834 synchronized (mAppWidgetIds) {
835 ensureStateLoadedLocked();
836 AppWidgetId id = lookupAppWidgetIdLocked(appWidgetId);
837 if (id != null && id.provider != null && !id.provider.zombie) {
Adam Cohen3ff2d862012-09-26 14:07:57 -0700838 return cloneIfLocalBinder(id.provider.info);
Amith Yamasani742a6712011-05-04 14:49:28 -0700839 }
840 return null;
841 }
842 }
843
844 public RemoteViews getAppWidgetViews(int appWidgetId) {
Amith Yamasani8320de82012-10-05 16:10:38 -0700845 if (DBG) log("getAppWidgetViews id=" + appWidgetId);
Amith Yamasani742a6712011-05-04 14:49:28 -0700846 synchronized (mAppWidgetIds) {
847 ensureStateLoadedLocked();
848 AppWidgetId id = lookupAppWidgetIdLocked(appWidgetId);
849 if (id != null) {
Adam Cohen3ff2d862012-09-26 14:07:57 -0700850 return cloneIfLocalBinder(id.views);
Amith Yamasani742a6712011-05-04 14:49:28 -0700851 }
Amith Yamasani8320de82012-10-05 16:10:38 -0700852 if (DBG) log(" couldn't find appwidgetid");
Amith Yamasani742a6712011-05-04 14:49:28 -0700853 return null;
854 }
855 }
856
857 public List<AppWidgetProviderInfo> getInstalledProviders() {
858 synchronized (mAppWidgetIds) {
859 ensureStateLoadedLocked();
860 final int N = mInstalledProviders.size();
861 ArrayList<AppWidgetProviderInfo> result = new ArrayList<AppWidgetProviderInfo>(N);
862 for (int i = 0; i < N; i++) {
863 Provider p = mInstalledProviders.get(i);
864 if (!p.zombie) {
Adam Cohen3ff2d862012-09-26 14:07:57 -0700865 result.add(cloneIfLocalBinder(p.info));
Amith Yamasani742a6712011-05-04 14:49:28 -0700866 }
867 }
868 return result;
869 }
870 }
871
872 public void updateAppWidgetIds(int[] appWidgetIds, RemoteViews views) {
873 if (appWidgetIds == null) {
874 return;
875 }
Amith Yamasani8320de82012-10-05 16:10:38 -0700876 if (DBG) log("updateAppWidgetIds views: " + views);
Adam Cohenf08a8b72012-07-16 12:02:10 -0700877 int bitmapMemoryUsage = 0;
878 if (views != null) {
879 bitmapMemoryUsage = views.estimateMemoryUsage();
880 }
Adam Cohen311c79c2012-05-10 14:44:38 -0700881 if (bitmapMemoryUsage > mMaxWidgetBitmapMemory) {
882 throw new IllegalArgumentException("RemoteViews for widget update exceeds maximum" +
883 " bitmap memory usage (used: " + bitmapMemoryUsage + ", max: " +
884 mMaxWidgetBitmapMemory + ") The total memory cannot exceed that required to" +
885 " fill the device's screen once.");
886 }
887
Amith Yamasani742a6712011-05-04 14:49:28 -0700888 if (appWidgetIds.length == 0) {
889 return;
890 }
891 final int N = appWidgetIds.length;
892
893 synchronized (mAppWidgetIds) {
894 ensureStateLoadedLocked();
895 for (int i = 0; i < N; i++) {
896 AppWidgetId id = lookupAppWidgetIdLocked(appWidgetIds[i]);
897 updateAppWidgetInstanceLocked(id, views);
898 }
899 }
900 }
901
Adam Cohena1a2f962012-11-01 14:06:16 -0700902 private void saveStateAsync() {
903 mSaveStateHandler.post(mSaveStateRunnable);
904 }
905
906 private final Runnable mSaveStateRunnable = new Runnable() {
907 @Override
908 public void run() {
909 synchronized (mAppWidgetIds) {
910 ensureStateLoadedLocked();
911 saveStateLocked();
912 }
913 }
914 };
915
Adam Cohend2097eb2012-05-01 18:10:28 -0700916 public void updateAppWidgetOptions(int appWidgetId, Bundle options) {
Adam Cohene8724c82012-04-19 17:11:40 -0700917 synchronized (mAppWidgetIds) {
Adam Cohen3ff2d862012-09-26 14:07:57 -0700918 options = cloneIfLocalBinder(options);
Adam Cohene8724c82012-04-19 17:11:40 -0700919 ensureStateLoadedLocked();
920 AppWidgetId id = lookupAppWidgetIdLocked(appWidgetId);
921
922 if (id == null) {
923 return;
924 }
Adam Cohen0aa2d422012-09-07 17:37:26 -0700925
Adam Cohene8724c82012-04-19 17:11:40 -0700926 Provider p = id.provider;
Adam Cohen0aa2d422012-09-07 17:37:26 -0700927 // Merge the options
928 id.options.putAll(options);
Adam Cohene8724c82012-04-19 17:11:40 -0700929
930 // send the broacast saying that this appWidgetId has been deleted
Adam Cohend2097eb2012-05-01 18:10:28 -0700931 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_OPTIONS_CHANGED);
Adam Cohene8724c82012-04-19 17:11:40 -0700932 intent.setComponent(p.info.provider);
933 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id.appWidgetId);
Adam Cohen0aa2d422012-09-07 17:37:26 -0700934 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_OPTIONS, id.options);
Dianne Hackborn79af1dd2012-08-16 16:42:52 -0700935 mContext.sendBroadcastAsUser(intent, new UserHandle(mUserId));
Adam Cohena1a2f962012-11-01 14:06:16 -0700936 saveStateAsync();
Adam Cohene8724c82012-04-19 17:11:40 -0700937 }
938 }
939
Adam Cohend2097eb2012-05-01 18:10:28 -0700940 public Bundle getAppWidgetOptions(int appWidgetId) {
Adam Cohene8724c82012-04-19 17:11:40 -0700941 synchronized (mAppWidgetIds) {
942 ensureStateLoadedLocked();
943 AppWidgetId id = lookupAppWidgetIdLocked(appWidgetId);
Adam Cohend2097eb2012-05-01 18:10:28 -0700944 if (id != null && id.options != null) {
Adam Cohen3ff2d862012-09-26 14:07:57 -0700945 return cloneIfLocalBinder(id.options);
Adam Cohene8724c82012-04-19 17:11:40 -0700946 } else {
947 return Bundle.EMPTY;
948 }
949 }
950 }
951
Amith Yamasani742a6712011-05-04 14:49:28 -0700952 public void partiallyUpdateAppWidgetIds(int[] appWidgetIds, RemoteViews views) {
953 if (appWidgetIds == null) {
954 return;
955 }
956 if (appWidgetIds.length == 0) {
957 return;
958 }
959 final int N = appWidgetIds.length;
960
961 synchronized (mAppWidgetIds) {
962 ensureStateLoadedLocked();
963 for (int i = 0; i < N; i++) {
964 AppWidgetId id = lookupAppWidgetIdLocked(appWidgetIds[i]);
Winson Chung66119882012-10-11 14:26:25 -0700965 if (id.views != null) {
966 // Only trigger a partial update for a widget if it has received a full update
967 updateAppWidgetInstanceLocked(id, views, true);
968 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700969 }
970 }
971 }
972
973 public void notifyAppWidgetViewDataChanged(int[] appWidgetIds, int viewId) {
974 if (appWidgetIds == null) {
975 return;
976 }
977 if (appWidgetIds.length == 0) {
978 return;
979 }
980 final int N = appWidgetIds.length;
981
982 synchronized (mAppWidgetIds) {
983 ensureStateLoadedLocked();
984 for (int i = 0; i < N; i++) {
985 AppWidgetId id = lookupAppWidgetIdLocked(appWidgetIds[i]);
986 notifyAppWidgetViewDataChangedInstanceLocked(id, viewId);
987 }
988 }
989 }
990
991 public void updateAppWidgetProvider(ComponentName provider, RemoteViews views) {
992 synchronized (mAppWidgetIds) {
993 ensureStateLoadedLocked();
994 Provider p = lookupProviderLocked(provider);
995 if (p == null) {
996 Slog.w(TAG, "updateAppWidgetProvider: provider doesn't exist: " + provider);
997 return;
998 }
999 ArrayList<AppWidgetId> instances = p.instances;
1000 final int callingUid = Binder.getCallingUid();
1001 final int N = instances.size();
1002 for (int i = 0; i < N; i++) {
1003 AppWidgetId id = instances.get(i);
1004 if (canAccessAppWidgetId(id, callingUid)) {
1005 updateAppWidgetInstanceLocked(id, views);
1006 }
1007 }
1008 }
1009 }
1010
1011 void updateAppWidgetInstanceLocked(AppWidgetId id, RemoteViews views) {
1012 updateAppWidgetInstanceLocked(id, views, false);
1013 }
1014
1015 void updateAppWidgetInstanceLocked(AppWidgetId id, RemoteViews views, boolean isPartialUpdate) {
1016 // allow for stale appWidgetIds and other badness
1017 // lookup also checks that the calling process can access the appWidgetId
1018 // drop unbound appWidgetIds (shouldn't be possible under normal circumstances)
1019 if (id != null && id.provider != null && !id.provider.zombie && !id.host.zombie) {
1020
Winson Chung66119882012-10-11 14:26:25 -07001021 if (!isPartialUpdate) {
Adam Cohenfbe44b72012-09-19 20:36:23 -07001022 // For a full update we replace the RemoteViews completely.
Amith Yamasani742a6712011-05-04 14:49:28 -07001023 id.views = views;
Adam Cohenfbe44b72012-09-19 20:36:23 -07001024 } else {
1025 // For a partial update, we merge the new RemoteViews with the old.
1026 id.views.mergeRemoteViews(views);
1027 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001028
1029 // is anyone listening?
1030 if (id.host.callbacks != null) {
1031 try {
1032 // the lock is held, but this is a oneway call
1033 id.host.callbacks.updateAppWidget(id.appWidgetId, views);
1034 } catch (RemoteException e) {
1035 // It failed; remove the callback. No need to prune because
1036 // we know that this host is still referenced by this instance.
1037 id.host.callbacks = null;
1038 }
1039 }
1040 }
1041 }
1042
1043 void notifyAppWidgetViewDataChangedInstanceLocked(AppWidgetId id, int viewId) {
1044 // allow for stale appWidgetIds and other badness
1045 // lookup also checks that the calling process can access the appWidgetId
1046 // drop unbound appWidgetIds (shouldn't be possible under normal circumstances)
1047 if (id != null && id.provider != null && !id.provider.zombie && !id.host.zombie) {
1048 // is anyone listening?
1049 if (id.host.callbacks != null) {
1050 try {
1051 // the lock is held, but this is a oneway call
1052 id.host.callbacks.viewDataChanged(id.appWidgetId, viewId);
1053 } catch (RemoteException e) {
1054 // It failed; remove the callback. No need to prune because
1055 // we know that this host is still referenced by this instance.
1056 id.host.callbacks = null;
1057 }
1058 }
1059
1060 // If the host is unavailable, then we call the associated
1061 // RemoteViewsFactory.onDataSetChanged() directly
1062 if (id.host.callbacks == null) {
1063 Set<FilterComparison> keys = mRemoteViewsServicesAppWidgets.keySet();
1064 for (FilterComparison key : keys) {
1065 if (mRemoteViewsServicesAppWidgets.get(key).contains(id.appWidgetId)) {
1066 Intent intent = key.getIntent();
1067
1068 final ServiceConnection conn = new ServiceConnection() {
1069 @Override
1070 public void onServiceConnected(ComponentName name, IBinder service) {
1071 IRemoteViewsFactory cb = IRemoteViewsFactory.Stub
1072 .asInterface(service);
1073 try {
1074 cb.onDataSetChangedAsync();
1075 } catch (RemoteException e) {
1076 e.printStackTrace();
1077 } catch (RuntimeException e) {
1078 e.printStackTrace();
1079 }
1080 mContext.unbindService(this);
1081 }
1082
1083 @Override
1084 public void onServiceDisconnected(android.content.ComponentName name) {
1085 // Do nothing
1086 }
1087 };
1088
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001089 int userId = UserHandle.getUserId(id.provider.uid);
Amith Yamasani742a6712011-05-04 14:49:28 -07001090 // Bind to the service and call onDataSetChanged()
1091 final long token = Binder.clearCallingIdentity();
1092 try {
Amith Yamasani37ce3a82012-02-06 12:04:42 -08001093 mContext.bindService(intent, conn, Context.BIND_AUTO_CREATE, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07001094 } finally {
1095 Binder.restoreCallingIdentity(token);
1096 }
1097 }
1098 }
1099 }
1100 }
1101 }
1102
Adam Cohen3ff2d862012-09-26 14:07:57 -07001103 private boolean isLocalBinder() {
1104 return Process.myPid() == Binder.getCallingPid();
1105 }
1106
1107 private RemoteViews cloneIfLocalBinder(RemoteViews rv) {
1108 if (isLocalBinder() && rv != null) {
1109 return rv.clone();
1110 }
1111 return rv;
1112 }
1113
1114 private AppWidgetProviderInfo cloneIfLocalBinder(AppWidgetProviderInfo info) {
1115 if (isLocalBinder() && info != null) {
1116 return info.clone();
1117 }
1118 return info;
1119 }
1120
1121 private Bundle cloneIfLocalBinder(Bundle bundle) {
1122 // Note: this is only a shallow copy. For now this will be fine, but it could be problematic
1123 // if we start adding objects to the options. Further, it would only be an issue if keyguard
1124 // used such options.
1125 if (isLocalBinder() && bundle != null) {
1126 return (Bundle) bundle.clone();
1127 }
1128 return bundle;
1129 }
1130
Amith Yamasani742a6712011-05-04 14:49:28 -07001131 public int[] startListening(IAppWidgetHost callbacks, String packageName, int hostId,
1132 List<RemoteViews> updatedViews) {
1133 int callingUid = enforceCallingUid(packageName);
1134 synchronized (mAppWidgetIds) {
1135 ensureStateLoadedLocked();
1136 Host host = lookupOrAddHostLocked(callingUid, packageName, hostId);
1137 host.callbacks = callbacks;
1138
1139 updatedViews.clear();
1140
1141 ArrayList<AppWidgetId> instances = host.instances;
1142 int N = instances.size();
1143 int[] updatedIds = new int[N];
1144 for (int i = 0; i < N; i++) {
1145 AppWidgetId id = instances.get(i);
1146 updatedIds[i] = id.appWidgetId;
Adam Cohen3ff2d862012-09-26 14:07:57 -07001147 updatedViews.add(cloneIfLocalBinder(id.views));
Amith Yamasani742a6712011-05-04 14:49:28 -07001148 }
1149 return updatedIds;
1150 }
1151 }
1152
1153 public void stopListening(int hostId) {
1154 synchronized (mAppWidgetIds) {
1155 ensureStateLoadedLocked();
1156 Host host = lookupHostLocked(Binder.getCallingUid(), hostId);
1157 if (host != null) {
1158 host.callbacks = null;
1159 pruneHostLocked(host);
1160 }
1161 }
1162 }
1163
1164 boolean canAccessAppWidgetId(AppWidgetId id, int callingUid) {
1165 if (id.host.uid == callingUid) {
1166 // Apps hosting the AppWidget have access to it.
1167 return true;
1168 }
1169 if (id.provider != null && id.provider.uid == callingUid) {
1170 // Apps providing the AppWidget have access to it (if the appWidgetId has been bound)
1171 return true;
1172 }
1173 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.BIND_APPWIDGET) == PackageManager.PERMISSION_GRANTED) {
1174 // Apps that can bind have access to all appWidgetIds.
1175 return true;
1176 }
1177 // Nobody else can access it.
1178 return false;
1179 }
1180
1181 AppWidgetId lookupAppWidgetIdLocked(int appWidgetId) {
1182 int callingUid = Binder.getCallingUid();
1183 final int N = mAppWidgetIds.size();
1184 for (int i = 0; i < N; i++) {
1185 AppWidgetId id = mAppWidgetIds.get(i);
1186 if (id.appWidgetId == appWidgetId && canAccessAppWidgetId(id, callingUid)) {
1187 return id;
1188 }
1189 }
1190 return null;
1191 }
1192
1193 Provider lookupProviderLocked(ComponentName provider) {
1194 final int N = mInstalledProviders.size();
1195 for (int i = 0; i < N; i++) {
1196 Provider p = mInstalledProviders.get(i);
1197 if (p.info.provider.equals(provider)) {
1198 return p;
1199 }
1200 }
1201 return null;
1202 }
1203
1204 Host lookupHostLocked(int uid, int hostId) {
1205 final int N = mHosts.size();
1206 for (int i = 0; i < N; i++) {
1207 Host h = mHosts.get(i);
1208 if (h.uid == uid && h.hostId == hostId) {
1209 return h;
1210 }
1211 }
1212 return null;
1213 }
1214
1215 Host lookupOrAddHostLocked(int uid, String packageName, int hostId) {
1216 final int N = mHosts.size();
1217 for (int i = 0; i < N; i++) {
1218 Host h = mHosts.get(i);
1219 if (h.hostId == hostId && h.packageName.equals(packageName)) {
1220 return h;
1221 }
1222 }
1223 Host host = new Host();
1224 host.packageName = packageName;
1225 host.uid = uid;
1226 host.hostId = hostId;
1227 mHosts.add(host);
1228 return host;
1229 }
1230
1231 void pruneHostLocked(Host host) {
1232 if (host.instances.size() == 0 && host.callbacks == null) {
1233 mHosts.remove(host);
1234 }
1235 }
1236
Adam Cohena1a2f962012-11-01 14:06:16 -07001237 void loadAppWidgetListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -07001238 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001239 try {
1240 List<ResolveInfo> broadcastReceivers = mPm.queryIntentReceivers(intent,
1241 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
1242 PackageManager.GET_META_DATA, mUserId);
Amith Yamasani742a6712011-05-04 14:49:28 -07001243
Amith Yamasani483f3b02012-03-13 16:08:00 -07001244 final int N = broadcastReceivers == null ? 0 : broadcastReceivers.size();
1245 for (int i = 0; i < N; i++) {
1246 ResolveInfo ri = broadcastReceivers.get(i);
1247 addProviderLocked(ri);
1248 }
1249 } catch (RemoteException re) {
1250 // Shouldn't happen, local call
Amith Yamasani742a6712011-05-04 14:49:28 -07001251 }
1252 }
1253
1254 boolean addProviderLocked(ResolveInfo ri) {
1255 if ((ri.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
1256 return false;
1257 }
1258 if (!ri.activityInfo.isEnabled()) {
1259 return false;
1260 }
1261 Provider p = parseProviderInfoXml(new ComponentName(ri.activityInfo.packageName,
1262 ri.activityInfo.name), ri);
1263 if (p != null) {
1264 mInstalledProviders.add(p);
1265 return true;
1266 } else {
1267 return false;
1268 }
1269 }
1270
1271 void removeProviderLocked(int index, Provider p) {
1272 int N = p.instances.size();
1273 for (int i = 0; i < N; i++) {
1274 AppWidgetId id = p.instances.get(i);
1275 // Call back with empty RemoteViews
1276 updateAppWidgetInstanceLocked(id, null);
1277 // Stop telling the host about updates for this from now on
1278 cancelBroadcasts(p);
1279 // clear out references to this appWidgetId
1280 id.host.instances.remove(id);
1281 mAppWidgetIds.remove(id);
1282 id.provider = null;
1283 pruneHostLocked(id.host);
1284 id.host = null;
1285 }
1286 p.instances.clear();
1287 mInstalledProviders.remove(index);
1288 mDeletedProviders.add(p);
1289 // no need to send the DISABLE broadcast, since the receiver is gone anyway
1290 cancelBroadcasts(p);
1291 }
1292
1293 void sendEnableIntentLocked(Provider p) {
1294 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_ENABLED);
1295 intent.setComponent(p.info.provider);
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001296 mContext.sendBroadcastAsUser(intent, new UserHandle(mUserId));
Amith Yamasani742a6712011-05-04 14:49:28 -07001297 }
1298
1299 void sendUpdateIntentLocked(Provider p, int[] appWidgetIds) {
1300 if (appWidgetIds != null && appWidgetIds.length > 0) {
1301 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
1302 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
1303 intent.setComponent(p.info.provider);
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001304 mContext.sendBroadcastAsUser(intent, new UserHandle(mUserId));
Amith Yamasani742a6712011-05-04 14:49:28 -07001305 }
1306 }
1307
1308 void registerForBroadcastsLocked(Provider p, int[] appWidgetIds) {
1309 if (p.info.updatePeriodMillis > 0) {
1310 // if this is the first instance, set the alarm. otherwise,
1311 // rely on the fact that we've already set it and that
1312 // PendingIntent.getBroadcast will update the extras.
1313 boolean alreadyRegistered = p.broadcast != null;
1314 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
1315 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
1316 intent.setComponent(p.info.provider);
1317 long token = Binder.clearCallingIdentity();
1318 try {
Amith Yamasani8320de82012-10-05 16:10:38 -07001319 p.broadcast = PendingIntent.getBroadcastAsUser(mContext, 1, intent,
1320 PendingIntent.FLAG_UPDATE_CURRENT, new UserHandle(mUserId));
Amith Yamasani742a6712011-05-04 14:49:28 -07001321 } finally {
1322 Binder.restoreCallingIdentity(token);
1323 }
1324 if (!alreadyRegistered) {
1325 long period = p.info.updatePeriodMillis;
1326 if (period < MIN_UPDATE_PERIOD) {
1327 period = MIN_UPDATE_PERIOD;
1328 }
1329 mAlarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock
1330 .elapsedRealtime()
1331 + period, period, p.broadcast);
1332 }
1333 }
1334 }
1335
1336 static int[] getAppWidgetIds(Provider p) {
1337 int instancesSize = p.instances.size();
1338 int appWidgetIds[] = new int[instancesSize];
1339 for (int i = 0; i < instancesSize; i++) {
1340 appWidgetIds[i] = p.instances.get(i).appWidgetId;
1341 }
1342 return appWidgetIds;
1343 }
1344
1345 public int[] getAppWidgetIds(ComponentName provider) {
1346 synchronized (mAppWidgetIds) {
1347 ensureStateLoadedLocked();
1348 Provider p = lookupProviderLocked(provider);
1349 if (p != null && Binder.getCallingUid() == p.uid) {
1350 return getAppWidgetIds(p);
1351 } else {
1352 return new int[0];
1353 }
1354 }
1355 }
1356
1357 private Provider parseProviderInfoXml(ComponentName component, ResolveInfo ri) {
1358 Provider p = null;
1359
1360 ActivityInfo activityInfo = ri.activityInfo;
1361 XmlResourceParser parser = null;
1362 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001363 parser = activityInfo.loadXmlMetaData(mContext.getPackageManager(),
Amith Yamasani742a6712011-05-04 14:49:28 -07001364 AppWidgetManager.META_DATA_APPWIDGET_PROVIDER);
1365 if (parser == null) {
1366 Slog.w(TAG, "No " + AppWidgetManager.META_DATA_APPWIDGET_PROVIDER
1367 + " meta-data for " + "AppWidget provider '" + component + '\'');
1368 return null;
1369 }
1370
1371 AttributeSet attrs = Xml.asAttributeSet(parser);
1372
1373 int type;
1374 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1375 && type != XmlPullParser.START_TAG) {
1376 // drain whitespace, comments, etc.
1377 }
1378
1379 String nodeName = parser.getName();
1380 if (!"appwidget-provider".equals(nodeName)) {
1381 Slog.w(TAG, "Meta-data does not start with appwidget-provider tag for"
1382 + " AppWidget provider '" + component + '\'');
1383 return null;
1384 }
1385
1386 p = new Provider();
1387 AppWidgetProviderInfo info = p.info = new AppWidgetProviderInfo();
1388 info.provider = component;
1389 p.uid = activityInfo.applicationInfo.uid;
1390
Amith Yamasani483f3b02012-03-13 16:08:00 -07001391 Resources res = mContext.getPackageManager()
Amith Yamasani8320de82012-10-05 16:10:38 -07001392 .getResourcesForApplicationAsUser(activityInfo.packageName, mUserId);
Amith Yamasani742a6712011-05-04 14:49:28 -07001393
1394 TypedArray sa = res.obtainAttributes(attrs,
1395 com.android.internal.R.styleable.AppWidgetProviderInfo);
1396
1397 // These dimensions has to be resolved in the application's context.
1398 // We simply send back the raw complex data, which will be
1399 // converted to dp in {@link AppWidgetManager#getAppWidgetInfo}.
1400 TypedValue value = sa
1401 .peekValue(com.android.internal.R.styleable.AppWidgetProviderInfo_minWidth);
1402 info.minWidth = value != null ? value.data : 0;
1403 value = sa.peekValue(com.android.internal.R.styleable.AppWidgetProviderInfo_minHeight);
1404 info.minHeight = value != null ? value.data : 0;
1405 value = sa.peekValue(
1406 com.android.internal.R.styleable.AppWidgetProviderInfo_minResizeWidth);
1407 info.minResizeWidth = value != null ? value.data : info.minWidth;
1408 value = sa.peekValue(
1409 com.android.internal.R.styleable.AppWidgetProviderInfo_minResizeHeight);
1410 info.minResizeHeight = value != null ? value.data : info.minHeight;
1411 info.updatePeriodMillis = sa.getInt(
1412 com.android.internal.R.styleable.AppWidgetProviderInfo_updatePeriodMillis, 0);
1413 info.initialLayout = sa.getResourceId(
1414 com.android.internal.R.styleable.AppWidgetProviderInfo_initialLayout, 0);
Adam Cohen0aa2d422012-09-07 17:37:26 -07001415 info.initialKeyguardLayout = sa.getResourceId(com.android.internal.R.styleable.
1416 AppWidgetProviderInfo_initialKeyguardLayout, 0);
Amith Yamasani742a6712011-05-04 14:49:28 -07001417 String className = sa
1418 .getString(com.android.internal.R.styleable.AppWidgetProviderInfo_configure);
1419 if (className != null) {
1420 info.configure = new ComponentName(component.getPackageName(), className);
1421 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07001422 info.label = activityInfo.loadLabel(mContext.getPackageManager()).toString();
Amith Yamasani742a6712011-05-04 14:49:28 -07001423 info.icon = ri.getIconResource();
1424 info.previewImage = sa.getResourceId(
1425 com.android.internal.R.styleable.AppWidgetProviderInfo_previewImage, 0);
1426 info.autoAdvanceViewId = sa.getResourceId(
1427 com.android.internal.R.styleable.AppWidgetProviderInfo_autoAdvanceViewId, -1);
1428 info.resizeMode = sa.getInt(
1429 com.android.internal.R.styleable.AppWidgetProviderInfo_resizeMode,
1430 AppWidgetProviderInfo.RESIZE_NONE);
Adam Cohen0aa2d422012-09-07 17:37:26 -07001431 info.widgetCategory = sa.getInt(
Michael Jurkaca5e3412012-09-14 12:18:51 -07001432 com.android.internal.R.styleable.AppWidgetProviderInfo_widgetCategory,
Adam Cohen0aa2d422012-09-07 17:37:26 -07001433 AppWidgetProviderInfo.WIDGET_CATEGORY_HOME_SCREEN);
Amith Yamasani742a6712011-05-04 14:49:28 -07001434
1435 sa.recycle();
1436 } catch (Exception e) {
1437 // Ok to catch Exception here, because anything going wrong because
1438 // of what a client process passes to us should not be fatal for the
1439 // system process.
1440 Slog.w(TAG, "XML parsing failed for AppWidget provider '" + component + '\'', e);
1441 return null;
1442 } finally {
1443 if (parser != null)
1444 parser.close();
1445 }
1446 return p;
1447 }
1448
1449 int getUidForPackage(String packageName) throws PackageManager.NameNotFoundException {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001450 PackageInfo pkgInfo = null;
1451 try {
1452 pkgInfo = mPm.getPackageInfo(packageName, 0, mUserId);
1453 } catch (RemoteException re) {
1454 // Shouldn't happen, local call
1455 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001456 if (pkgInfo == null || pkgInfo.applicationInfo == null) {
1457 throw new PackageManager.NameNotFoundException();
1458 }
1459 return pkgInfo.applicationInfo.uid;
1460 }
1461
Jim Millerf229e4d32012-09-12 20:32:50 -07001462 int enforceSystemOrCallingUid(String packageName) throws IllegalArgumentException {
1463 int callingUid = Binder.getCallingUid();
Michael Jurka03bdc8a2012-09-21 16:10:21 -07001464 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID || callingUid == 0) {
Jim Millerf229e4d32012-09-12 20:32:50 -07001465 return callingUid;
1466 }
1467 return enforceCallingUid(packageName);
1468 }
1469
Amith Yamasani742a6712011-05-04 14:49:28 -07001470 int enforceCallingUid(String packageName) throws IllegalArgumentException {
1471 int callingUid = Binder.getCallingUid();
1472 int packageUid;
1473 try {
1474 packageUid = getUidForPackage(packageName);
1475 } catch (PackageManager.NameNotFoundException ex) {
1476 throw new IllegalArgumentException("packageName and uid don't match packageName="
1477 + packageName);
1478 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001479 if (!UserHandle.isSameApp(callingUid, packageUid)) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001480 throw new IllegalArgumentException("packageName and uid don't match packageName="
1481 + packageName);
1482 }
1483 return callingUid;
1484 }
1485
1486 void sendInitialBroadcasts() {
1487 synchronized (mAppWidgetIds) {
1488 ensureStateLoadedLocked();
1489 final int N = mInstalledProviders.size();
1490 for (int i = 0; i < N; i++) {
1491 Provider p = mInstalledProviders.get(i);
1492 if (p.instances.size() > 0) {
1493 sendEnableIntentLocked(p);
1494 int[] appWidgetIds = getAppWidgetIds(p);
1495 sendUpdateIntentLocked(p, appWidgetIds);
1496 registerForBroadcastsLocked(p, appWidgetIds);
1497 }
1498 }
1499 }
1500 }
1501
1502 // only call from initialization -- it assumes that the data structures are all empty
1503 void loadStateLocked() {
1504 AtomicFile file = savedStateFile();
1505 try {
1506 FileInputStream stream = file.openRead();
1507 readStateFromFileLocked(stream);
1508
1509 if (stream != null) {
1510 try {
1511 stream.close();
1512 } catch (IOException e) {
1513 Slog.w(TAG, "Failed to close state FileInputStream " + e);
1514 }
1515 }
1516 } catch (FileNotFoundException e) {
1517 Slog.w(TAG, "Failed to read state: " + e);
1518 }
1519 }
1520
1521 void saveStateLocked() {
1522 AtomicFile file = savedStateFile();
1523 FileOutputStream stream;
1524 try {
1525 stream = file.startWrite();
1526 if (writeStateToFileLocked(stream)) {
1527 file.finishWrite(stream);
1528 } else {
1529 file.failWrite(stream);
1530 Slog.w(TAG, "Failed to save state, restoring backup.");
1531 }
1532 } catch (IOException e) {
1533 Slog.w(TAG, "Failed open state file for write: " + e);
1534 }
1535 }
1536
1537 boolean writeStateToFileLocked(FileOutputStream stream) {
1538 int N;
1539
1540 try {
1541 XmlSerializer out = new FastXmlSerializer();
1542 out.setOutput(stream, "utf-8");
1543 out.startDocument(null, true);
1544 out.startTag(null, "gs");
1545
1546 int providerIndex = 0;
1547 N = mInstalledProviders.size();
1548 for (int i = 0; i < N; i++) {
1549 Provider p = mInstalledProviders.get(i);
1550 if (p.instances.size() > 0) {
1551 out.startTag(null, "p");
1552 out.attribute(null, "pkg", p.info.provider.getPackageName());
1553 out.attribute(null, "cl", p.info.provider.getClassName());
1554 out.endTag(null, "p");
1555 p.tag = providerIndex;
1556 providerIndex++;
1557 }
1558 }
1559
1560 N = mHosts.size();
1561 for (int i = 0; i < N; i++) {
1562 Host host = mHosts.get(i);
1563 out.startTag(null, "h");
1564 out.attribute(null, "pkg", host.packageName);
1565 out.attribute(null, "id", Integer.toHexString(host.hostId));
1566 out.endTag(null, "h");
1567 host.tag = i;
1568 }
1569
1570 N = mAppWidgetIds.size();
1571 for (int i = 0; i < N; i++) {
1572 AppWidgetId id = mAppWidgetIds.get(i);
1573 out.startTag(null, "g");
1574 out.attribute(null, "id", Integer.toHexString(id.appWidgetId));
1575 out.attribute(null, "h", Integer.toHexString(id.host.tag));
1576 if (id.provider != null) {
1577 out.attribute(null, "p", Integer.toHexString(id.provider.tag));
1578 }
Adam Cohen0aa2d422012-09-07 17:37:26 -07001579 if (id.options != null) {
1580 out.attribute(null, "min_width", Integer.toHexString(id.options.getInt(
1581 AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH)));
1582 out.attribute(null, "min_height", Integer.toHexString(id.options.getInt(
1583 AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT)));
1584 out.attribute(null, "max_width", Integer.toHexString(id.options.getInt(
1585 AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH)));
1586 out.attribute(null, "max_height", Integer.toHexString(id.options.getInt(
1587 AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT)));
1588 out.attribute(null, "host_category", Integer.toHexString(id.options.getInt(
1589 AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY)));
1590 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001591 out.endTag(null, "g");
1592 }
1593
Michael Jurka61a5b012012-04-13 10:39:45 -07001594 Iterator<String> it = mPackagesWithBindWidgetPermission.iterator();
1595 while (it.hasNext()) {
1596 out.startTag(null, "b");
1597 out.attribute(null, "packageName", it.next());
1598 out.endTag(null, "b");
1599 }
1600
Amith Yamasani742a6712011-05-04 14:49:28 -07001601 out.endTag(null, "gs");
1602
1603 out.endDocument();
1604 return true;
1605 } catch (IOException e) {
1606 Slog.w(TAG, "Failed to write state: " + e);
1607 return false;
1608 }
1609 }
1610
Adam Cohen0aa2d422012-09-07 17:37:26 -07001611 @SuppressWarnings("unused")
Amith Yamasani742a6712011-05-04 14:49:28 -07001612 void readStateFromFileLocked(FileInputStream stream) {
1613 boolean success = false;
Amith Yamasani742a6712011-05-04 14:49:28 -07001614 try {
1615 XmlPullParser parser = Xml.newPullParser();
1616 parser.setInput(stream, null);
1617
1618 int type;
1619 int providerIndex = 0;
1620 HashMap<Integer, Provider> loadedProviders = new HashMap<Integer, Provider>();
1621 do {
1622 type = parser.next();
1623 if (type == XmlPullParser.START_TAG) {
1624 String tag = parser.getName();
1625 if ("p".equals(tag)) {
1626 // TODO: do we need to check that this package has the same signature
1627 // as before?
1628 String pkg = parser.getAttributeValue(null, "pkg");
1629 String cl = parser.getAttributeValue(null, "cl");
1630
Amith Yamasanif203aee2012-08-29 18:41:53 -07001631 final IPackageManager packageManager = AppGlobals.getPackageManager();
Amith Yamasani742a6712011-05-04 14:49:28 -07001632 try {
Amith Yamasani8320de82012-10-05 16:10:38 -07001633 packageManager.getReceiverInfo(new ComponentName(pkg, cl), 0, mUserId);
Amith Yamasanif203aee2012-08-29 18:41:53 -07001634 } catch (RemoteException e) {
1635 String[] pkgs = mContext.getPackageManager()
Amith Yamasani742a6712011-05-04 14:49:28 -07001636 .currentToCanonicalPackageNames(new String[] { pkg });
1637 pkg = pkgs[0];
1638 }
1639
1640 Provider p = lookupProviderLocked(new ComponentName(pkg, cl));
1641 if (p == null && mSafeMode) {
1642 // if we're in safe mode, make a temporary one
1643 p = new Provider();
1644 p.info = new AppWidgetProviderInfo();
1645 p.info.provider = new ComponentName(pkg, cl);
1646 p.zombie = true;
1647 mInstalledProviders.add(p);
1648 }
1649 if (p != null) {
1650 // if it wasn't uninstalled or something
1651 loadedProviders.put(providerIndex, p);
1652 }
1653 providerIndex++;
1654 } else if ("h".equals(tag)) {
1655 Host host = new Host();
1656
1657 // TODO: do we need to check that this package has the same signature
1658 // as before?
1659 host.packageName = parser.getAttributeValue(null, "pkg");
1660 try {
1661 host.uid = getUidForPackage(host.packageName);
1662 } catch (PackageManager.NameNotFoundException ex) {
1663 host.zombie = true;
1664 }
1665 if (!host.zombie || mSafeMode) {
1666 // In safe mode, we don't discard the hosts we don't recognize
1667 // so that they're not pruned from our list. Otherwise, we do.
1668 host.hostId = Integer
1669 .parseInt(parser.getAttributeValue(null, "id"), 16);
1670 mHosts.add(host);
1671 }
Michael Jurka61a5b012012-04-13 10:39:45 -07001672 } else if ("b".equals(tag)) {
1673 String packageName = parser.getAttributeValue(null, "packageName");
1674 if (packageName != null) {
1675 mPackagesWithBindWidgetPermission.add(packageName);
1676 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001677 } else if ("g".equals(tag)) {
1678 AppWidgetId id = new AppWidgetId();
1679 id.appWidgetId = Integer.parseInt(parser.getAttributeValue(null, "id"), 16);
1680 if (id.appWidgetId >= mNextAppWidgetId) {
1681 mNextAppWidgetId = id.appWidgetId + 1;
1682 }
1683
Adam Cohen0aa2d422012-09-07 17:37:26 -07001684 Bundle options = new Bundle();
1685 String minWidthString = parser.getAttributeValue(null, "min_width");
1686 if (minWidthString != null) {
1687 options.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH,
1688 Integer.parseInt(minWidthString, 16));
1689 }
1690 String minHeightString = parser.getAttributeValue(null, "min_height");
Adam Cohendb38d8a2012-09-21 18:14:58 -07001691 if (minHeightString != null) {
Adam Cohen0aa2d422012-09-07 17:37:26 -07001692 options.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT,
1693 Integer.parseInt(minHeightString, 16));
1694 }
Adam Cohendb38d8a2012-09-21 18:14:58 -07001695 String maxWidthString = parser.getAttributeValue(null, "max_width");
1696 if (maxWidthString != null) {
Adam Cohen0aa2d422012-09-07 17:37:26 -07001697 options.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH,
1698 Integer.parseInt(maxWidthString, 16));
1699 }
1700 String maxHeightString = parser.getAttributeValue(null, "max_height");
Adam Cohendb38d8a2012-09-21 18:14:58 -07001701 if (maxHeightString != null) {
Adam Cohen0aa2d422012-09-07 17:37:26 -07001702 options.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT,
1703 Integer.parseInt(maxHeightString, 16));
1704 }
1705 String categoryString = parser.getAttributeValue(null, "host_category");
Adam Cohendb38d8a2012-09-21 18:14:58 -07001706 if (categoryString != null) {
Adam Cohen0aa2d422012-09-07 17:37:26 -07001707 options.putInt(AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY,
1708 Integer.parseInt(categoryString, 16));
1709 }
1710 id.options = options;
1711
Amith Yamasani742a6712011-05-04 14:49:28 -07001712 String providerString = parser.getAttributeValue(null, "p");
1713 if (providerString != null) {
1714 // there's no provider if it hasn't been bound yet.
1715 // maybe we don't have to save this, but it brings the system
1716 // to the state it was in.
1717 int pIndex = Integer.parseInt(providerString, 16);
1718 id.provider = loadedProviders.get(pIndex);
1719 if (false) {
1720 Slog.d(TAG, "bound appWidgetId=" + id.appWidgetId + " to provider "
1721 + pIndex + " which is " + id.provider);
1722 }
1723 if (id.provider == null) {
1724 // This provider is gone. We just let the host figure out
1725 // that this happened when it fails to load it.
1726 continue;
1727 }
1728 }
1729
1730 int hIndex = Integer.parseInt(parser.getAttributeValue(null, "h"), 16);
1731 id.host = mHosts.get(hIndex);
1732 if (id.host == null) {
1733 // This host is gone.
1734 continue;
1735 }
1736
1737 if (id.provider != null) {
1738 id.provider.instances.add(id);
1739 }
1740 id.host.instances.add(id);
1741 mAppWidgetIds.add(id);
1742 }
1743 }
1744 } while (type != XmlPullParser.END_DOCUMENT);
1745 success = true;
1746 } catch (NullPointerException e) {
1747 Slog.w(TAG, "failed parsing " + e);
1748 } catch (NumberFormatException e) {
1749 Slog.w(TAG, "failed parsing " + e);
1750 } catch (XmlPullParserException e) {
1751 Slog.w(TAG, "failed parsing " + e);
1752 } catch (IOException e) {
1753 Slog.w(TAG, "failed parsing " + e);
1754 } catch (IndexOutOfBoundsException e) {
1755 Slog.w(TAG, "failed parsing " + e);
1756 }
1757
1758 if (success) {
1759 // delete any hosts that didn't manage to get connected (should happen)
1760 // if it matters, they'll be reconnected.
1761 for (int i = mHosts.size() - 1; i >= 0; i--) {
1762 pruneHostLocked(mHosts.get(i));
1763 }
1764 } else {
1765 // failed reading, clean up
1766 Slog.w(TAG, "Failed to read state, clearing widgets and hosts.");
1767
1768 mAppWidgetIds.clear();
1769 mHosts.clear();
1770 final int N = mInstalledProviders.size();
1771 for (int i = 0; i < N; i++) {
1772 mInstalledProviders.get(i).instances.clear();
1773 }
1774 }
1775 }
1776
Amith Yamasani13593602012-03-22 16:16:17 -07001777 static File getSettingsFile(int userId) {
Amith Yamasani61f57372012-08-31 12:12:28 -07001778 return new File(Environment.getUserSystemDirectory(userId), SETTINGS_FILENAME);
Amith Yamasani13593602012-03-22 16:16:17 -07001779 }
1780
Amith Yamasani742a6712011-05-04 14:49:28 -07001781 AtomicFile savedStateFile() {
Amith Yamasani61f57372012-08-31 12:12:28 -07001782 File dir = Environment.getUserSystemDirectory(mUserId);
Amith Yamasani13593602012-03-22 16:16:17 -07001783 File settingsFile = getSettingsFile(mUserId);
Amith Yamasanie0eb39b52012-05-01 13:48:48 -07001784 if (!settingsFile.exists() && mUserId == 0) {
1785 if (!dir.exists()) {
1786 dir.mkdirs();
Amith Yamasani742a6712011-05-04 14:49:28 -07001787 }
Amith Yamasanie0eb39b52012-05-01 13:48:48 -07001788 // Migrate old data
1789 File oldFile = new File("/data/system/" + SETTINGS_FILENAME);
1790 // Method doesn't throw an exception on failure. Ignore any errors
1791 // in moving the file (like non-existence)
1792 oldFile.renameTo(settingsFile);
Amith Yamasani742a6712011-05-04 14:49:28 -07001793 }
1794 return new AtomicFile(settingsFile);
1795 }
1796
Amith Yamasani756901d2012-10-12 12:30:07 -07001797 void onUserStopping() {
Amith Yamasani13593602012-03-22 16:16:17 -07001798 // prune the ones we don't want to keep
1799 int N = mInstalledProviders.size();
1800 for (int i = N - 1; i >= 0; i--) {
1801 Provider p = mInstalledProviders.get(i);
1802 cancelBroadcasts(p);
1803 }
Amith Yamasani756901d2012-10-12 12:30:07 -07001804 }
1805
1806 void onUserRemoved() {
Amith Yamasani13593602012-03-22 16:16:17 -07001807 getSettingsFile(mUserId).delete();
1808 }
1809
Winson Chung7fbd2842012-06-13 10:35:51 -07001810 boolean addProvidersForPackageLocked(String pkgName) {
1811 boolean providersAdded = false;
Amith Yamasani742a6712011-05-04 14:49:28 -07001812 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
1813 intent.setPackage(pkgName);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001814 List<ResolveInfo> broadcastReceivers;
1815 try {
1816 broadcastReceivers = mPm.queryIntentReceivers(intent,
1817 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
1818 PackageManager.GET_META_DATA, mUserId);
1819 } catch (RemoteException re) {
1820 // Shouldn't happen, local call
Winson Chung7fbd2842012-06-13 10:35:51 -07001821 return false;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001822 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001823 final int N = broadcastReceivers == null ? 0 : broadcastReceivers.size();
1824 for (int i = 0; i < N; i++) {
1825 ResolveInfo ri = broadcastReceivers.get(i);
1826 ActivityInfo ai = ri.activityInfo;
1827 if ((ai.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
1828 continue;
1829 }
1830 if (pkgName.equals(ai.packageName)) {
1831 addProviderLocked(ri);
Winson Chung7fbd2842012-06-13 10:35:51 -07001832 providersAdded = true;
Amith Yamasani742a6712011-05-04 14:49:28 -07001833 }
1834 }
Winson Chung7fbd2842012-06-13 10:35:51 -07001835
1836 return providersAdded;
Amith Yamasani742a6712011-05-04 14:49:28 -07001837 }
1838
Winson Chunga3195052012-06-25 10:02:10 -07001839 /**
1840 * Updates all providers with the specified package names, and records any providers that were
1841 * pruned.
1842 *
1843 * @return whether any providers were updated
1844 */
1845 boolean updateProvidersForPackageLocked(String pkgName, Set<ComponentName> removedProviders) {
Winson Chung7fbd2842012-06-13 10:35:51 -07001846 boolean providersUpdated = false;
Amith Yamasani742a6712011-05-04 14:49:28 -07001847 HashSet<String> keep = new HashSet<String>();
1848 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
1849 intent.setPackage(pkgName);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001850 List<ResolveInfo> broadcastReceivers;
1851 try {
1852 broadcastReceivers = mPm.queryIntentReceivers(intent,
1853 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
1854 PackageManager.GET_META_DATA, mUserId);
1855 } catch (RemoteException re) {
1856 // Shouldn't happen, local call
Winson Chung7fbd2842012-06-13 10:35:51 -07001857 return false;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001858 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001859
1860 // add the missing ones and collect which ones to keep
1861 int N = broadcastReceivers == null ? 0 : broadcastReceivers.size();
1862 for (int i = 0; i < N; i++) {
1863 ResolveInfo ri = broadcastReceivers.get(i);
1864 ActivityInfo ai = ri.activityInfo;
1865 if ((ai.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
1866 continue;
1867 }
1868 if (pkgName.equals(ai.packageName)) {
1869 ComponentName component = new ComponentName(ai.packageName, ai.name);
1870 Provider p = lookupProviderLocked(component);
1871 if (p == null) {
1872 if (addProviderLocked(ri)) {
1873 keep.add(ai.name);
Winson Chung7fbd2842012-06-13 10:35:51 -07001874 providersUpdated = true;
Amith Yamasani742a6712011-05-04 14:49:28 -07001875 }
1876 } else {
1877 Provider parsed = parseProviderInfoXml(component, ri);
1878 if (parsed != null) {
1879 keep.add(ai.name);
1880 // Use the new AppWidgetProviderInfo.
1881 p.info = parsed.info;
1882 // If it's enabled
1883 final int M = p.instances.size();
1884 if (M > 0) {
1885 int[] appWidgetIds = getAppWidgetIds(p);
1886 // Reschedule for the new updatePeriodMillis (don't worry about handling
1887 // it specially if updatePeriodMillis didn't change because we just sent
1888 // an update, and the next one will be updatePeriodMillis from now).
1889 cancelBroadcasts(p);
1890 registerForBroadcastsLocked(p, appWidgetIds);
1891 // If it's currently showing, call back with the new
1892 // AppWidgetProviderInfo.
1893 for (int j = 0; j < M; j++) {
1894 AppWidgetId id = p.instances.get(j);
1895 id.views = null;
1896 if (id.host != null && id.host.callbacks != null) {
1897 try {
1898 id.host.callbacks.providerChanged(id.appWidgetId, p.info);
1899 } catch (RemoteException ex) {
1900 // It failed; remove the callback. No need to prune because
1901 // we know that this host is still referenced by this
1902 // instance.
1903 id.host.callbacks = null;
1904 }
1905 }
1906 }
1907 // Now that we've told the host, push out an update.
1908 sendUpdateIntentLocked(p, appWidgetIds);
Winson Chung7fbd2842012-06-13 10:35:51 -07001909 providersUpdated = true;
Amith Yamasani742a6712011-05-04 14:49:28 -07001910 }
1911 }
1912 }
1913 }
1914 }
1915
1916 // prune the ones we don't want to keep
1917 N = mInstalledProviders.size();
1918 for (int i = N - 1; i >= 0; i--) {
1919 Provider p = mInstalledProviders.get(i);
1920 if (pkgName.equals(p.info.provider.getPackageName())
1921 && !keep.contains(p.info.provider.getClassName())) {
Winson Chunga3195052012-06-25 10:02:10 -07001922 if (removedProviders != null) {
1923 removedProviders.add(p.info.provider);
1924 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001925 removeProviderLocked(i, p);
Winson Chung7fbd2842012-06-13 10:35:51 -07001926 providersUpdated = true;
Amith Yamasani742a6712011-05-04 14:49:28 -07001927 }
1928 }
Winson Chung7fbd2842012-06-13 10:35:51 -07001929
1930 return providersUpdated;
Amith Yamasani742a6712011-05-04 14:49:28 -07001931 }
1932
Winson Chung7fbd2842012-06-13 10:35:51 -07001933 boolean removeProvidersForPackageLocked(String pkgName) {
1934 boolean providersRemoved = false;
Amith Yamasani742a6712011-05-04 14:49:28 -07001935 int N = mInstalledProviders.size();
1936 for (int i = N - 1; i >= 0; i--) {
1937 Provider p = mInstalledProviders.get(i);
1938 if (pkgName.equals(p.info.provider.getPackageName())) {
1939 removeProviderLocked(i, p);
Winson Chung7fbd2842012-06-13 10:35:51 -07001940 providersRemoved = true;
Amith Yamasani742a6712011-05-04 14:49:28 -07001941 }
1942 }
1943
1944 // Delete the hosts for this package too
1945 //
1946 // By now, we have removed any AppWidgets that were in any hosts here,
1947 // so we don't need to worry about sending DISABLE broadcasts to them.
1948 N = mHosts.size();
1949 for (int i = N - 1; i >= 0; i--) {
1950 Host host = mHosts.get(i);
1951 if (pkgName.equals(host.packageName)) {
1952 deleteHostLocked(host);
1953 }
1954 }
Winson Chung7fbd2842012-06-13 10:35:51 -07001955
1956 return providersRemoved;
1957 }
1958
1959 void notifyHostsForProvidersChangedLocked() {
1960 final int N = mHosts.size();
1961 for (int i = N - 1; i >= 0; i--) {
1962 Host host = mHosts.get(i);
1963 try {
1964 if (host.callbacks != null) {
1965 host.callbacks.providersChanged();
1966 }
1967 } catch (RemoteException ex) {
1968 // It failed; remove the callback. No need to prune because
1969 // we know that this host is still referenced by this
1970 // instance.
1971 host.callbacks = null;
1972 }
1973 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001974 }
1975}