blob: 7725f3505c61a3bb58959f85e625de0607986327 [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;
39import android.net.Uri;
40import android.os.Binder;
41import android.os.Bundle;
42import android.os.IBinder;
43import android.os.RemoteException;
44import android.os.SystemClock;
45import android.os.UserId;
46import android.util.AttributeSet;
47import android.util.Log;
48import android.util.Pair;
49import android.util.Slog;
50import android.util.TypedValue;
51import android.util.Xml;
Adam Cohen311c79c2012-05-10 14:44:38 -070052import android.view.WindowManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070053import android.widget.RemoteViews;
54
55import com.android.internal.appwidget.IAppWidgetHost;
56import com.android.internal.os.AtomicFile;
57import com.android.internal.util.FastXmlSerializer;
58import com.android.internal.widget.IRemoteViewsAdapterConnection;
59import com.android.internal.widget.IRemoteViewsFactory;
Amith Yamasani742a6712011-05-04 14:49:28 -070060
61import org.xmlpull.v1.XmlPullParser;
62import org.xmlpull.v1.XmlPullParserException;
63import org.xmlpull.v1.XmlSerializer;
64
65import java.io.File;
66import java.io.FileDescriptor;
67import java.io.FileInputStream;
68import java.io.FileNotFoundException;
69import java.io.FileOutputStream;
70import java.io.IOException;
71import java.io.PrintWriter;
72import java.util.ArrayList;
73import java.util.HashMap;
74import java.util.HashSet;
75import java.util.Iterator;
76import java.util.List;
77import java.util.Locale;
78import java.util.Set;
79
80class AppWidgetServiceImpl {
81
82 private static final String TAG = "AppWidgetServiceImpl";
83 private static final String SETTINGS_FILENAME = "appwidgets.xml";
84 private static final int MIN_UPDATE_PERIOD = 30 * 60 * 1000; // 30 minutes
85
86 /*
87 * When identifying a Host or Provider based on the calling process, use the uid field. When
88 * identifying a Host or Provider based on a package manager broadcast, use the package given.
89 */
90
91 static class Provider {
92 int uid;
93 AppWidgetProviderInfo info;
94 ArrayList<AppWidgetId> instances = new ArrayList<AppWidgetId>();
95 PendingIntent broadcast;
96 boolean zombie; // if we're in safe mode, don't prune this just because nobody references it
97
98 int tag; // for use while saving state (the index)
99 }
100
101 static class Host {
102 int uid;
103 int hostId;
104 String packageName;
105 ArrayList<AppWidgetId> instances = new ArrayList<AppWidgetId>();
106 IAppWidgetHost callbacks;
107 boolean zombie; // if we're in safe mode, don't prune this just because nobody references it
108
109 int tag; // for use while saving state (the index)
110 }
111
112 static class AppWidgetId {
113 int appWidgetId;
114 Provider provider;
115 RemoteViews views;
Adam Cohend2097eb2012-05-01 18:10:28 -0700116 Bundle options;
Amith Yamasani742a6712011-05-04 14:49:28 -0700117 Host host;
118 }
119
120 /**
121 * Acts as a proxy between the ServiceConnection and the RemoteViewsAdapterConnection. This
122 * needs to be a static inner class since a reference to the ServiceConnection is held globally
123 * and may lead us to leak AppWidgetService instances (if there were more than one).
124 */
125 static class ServiceConnectionProxy implements ServiceConnection {
126 private final IBinder mConnectionCb;
127
128 ServiceConnectionProxy(Pair<Integer, Intent.FilterComparison> key, IBinder connectionCb) {
129 mConnectionCb = connectionCb;
130 }
131
132 public void onServiceConnected(ComponentName name, IBinder service) {
133 final IRemoteViewsAdapterConnection cb = IRemoteViewsAdapterConnection.Stub
134 .asInterface(mConnectionCb);
135 try {
136 cb.onServiceConnected(service);
137 } catch (Exception e) {
138 e.printStackTrace();
139 }
140 }
141
142 public void onServiceDisconnected(ComponentName name) {
143 disconnect();
144 }
145
146 public void disconnect() {
147 final IRemoteViewsAdapterConnection cb = IRemoteViewsAdapterConnection.Stub
148 .asInterface(mConnectionCb);
149 try {
150 cb.onServiceDisconnected();
151 } catch (Exception e) {
152 e.printStackTrace();
153 }
154 }
155 }
156
157 // Manages active connections to RemoteViewsServices
158 private final HashMap<Pair<Integer, FilterComparison>, ServiceConnection> mBoundRemoteViewsServices = new HashMap<Pair<Integer, FilterComparison>, ServiceConnection>();
159 // Manages persistent references to RemoteViewsServices from different App Widgets
160 private final HashMap<FilterComparison, HashSet<Integer>> mRemoteViewsServicesAppWidgets = new HashMap<FilterComparison, HashSet<Integer>>();
161
162 Context mContext;
163 Locale mLocale;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700164 IPackageManager mPm;
Amith Yamasani742a6712011-05-04 14:49:28 -0700165 AlarmManager mAlarmManager;
166 ArrayList<Provider> mInstalledProviders = new ArrayList<Provider>();
167 int mNextAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID + 1;
168 final ArrayList<AppWidgetId> mAppWidgetIds = new ArrayList<AppWidgetId>();
169 ArrayList<Host> mHosts = new ArrayList<Host>();
Michael Jurka61a5b012012-04-13 10:39:45 -0700170 // set of package names
171 HashSet<String> mPackagesWithBindWidgetPermission = new HashSet<String>();
Amith Yamasani742a6712011-05-04 14:49:28 -0700172 boolean mSafeMode;
173 int mUserId;
174 boolean mStateLoaded;
Adam Cohen311c79c2012-05-10 14:44:38 -0700175 int mMaxWidgetBitmapMemory;
Amith Yamasani742a6712011-05-04 14:49:28 -0700176
177 // These are for debugging only -- widgets are going missing in some rare instances
178 ArrayList<Provider> mDeletedProviders = new ArrayList<Provider>();
179 ArrayList<Host> mDeletedHosts = new ArrayList<Host>();
180
181 AppWidgetServiceImpl(Context context, int userId) {
182 mContext = context;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700183 mPm = AppGlobals.getPackageManager();
Amith Yamasani742a6712011-05-04 14:49:28 -0700184 mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
185 mUserId = userId;
Adam Cohen311c79c2012-05-10 14:44:38 -0700186 computeMaximumWidgetBitmapMemory();
187 }
188
189 void computeMaximumWidgetBitmapMemory() {
190 WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
191 int height = wm.getDefaultDisplay().getRawHeight();
192 int width = wm.getDefaultDisplay().getRawWidth();
Winson Chunge92aad42012-06-22 14:11:47 -0700193 // Cap memory usage at 1.5 times the size of the display
194 // 1.5 * 4 bytes/pixel * w * h ==> 6 * w * h
195 mMaxWidgetBitmapMemory = 6 * width * height;
Amith Yamasani742a6712011-05-04 14:49:28 -0700196 }
197
198 public void systemReady(boolean safeMode) {
199 mSafeMode = safeMode;
200
201 synchronized (mAppWidgetIds) {
202 ensureStateLoadedLocked();
203 }
204 }
205
206 void onConfigurationChanged() {
207 Locale revised = Locale.getDefault();
208 if (revised == null || mLocale == null || !(revised.equals(mLocale))) {
209 mLocale = revised;
210
211 synchronized (mAppWidgetIds) {
212 ensureStateLoadedLocked();
Winson Chunga3195052012-06-25 10:02:10 -0700213 // Note: updateProvidersForPackageLocked() may remove providers, so we must copy the
214 // list of installed providers and skip providers that we don't need to update.
215 // Also note that remove the provider does not clear the Provider component data.
216 ArrayList<Provider> installedProviders =
217 new ArrayList<Provider>(mInstalledProviders);
218 HashSet<ComponentName> removedProviders = new HashSet<ComponentName>();
219 int N = installedProviders.size();
Amith Yamasani742a6712011-05-04 14:49:28 -0700220 for (int i = N - 1; i >= 0; i--) {
Winson Chunga3195052012-06-25 10:02:10 -0700221 Provider p = installedProviders.get(i);
222 ComponentName cn = p.info.provider;
223 if (!removedProviders.contains(cn)) {
224 updateProvidersForPackageLocked(cn.getPackageName(), removedProviders);
225 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700226 }
227 saveStateLocked();
228 }
229 }
230 }
231
232 void onBroadcastReceived(Intent intent) {
233 final String action = intent.getAction();
234 boolean added = false;
235 boolean changed = false;
Winson Chung7fbd2842012-06-13 10:35:51 -0700236 boolean providersModified = false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700237 String pkgList[] = null;
238 if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
239 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
240 added = true;
241 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
242 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
243 added = false;
244 } else {
245 Uri uri = intent.getData();
246 if (uri == null) {
247 return;
248 }
249 String pkgName = uri.getSchemeSpecificPart();
250 if (pkgName == null) {
251 return;
252 }
253 pkgList = new String[] { pkgName };
254 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
255 changed = Intent.ACTION_PACKAGE_CHANGED.equals(action);
256 }
257 if (pkgList == null || pkgList.length == 0) {
258 return;
259 }
260 if (added || changed) {
261 synchronized (mAppWidgetIds) {
262 ensureStateLoadedLocked();
263 Bundle extras = intent.getExtras();
264 if (changed
265 || (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false))) {
266 for (String pkgName : pkgList) {
267 // The package was just upgraded
Winson Chunga3195052012-06-25 10:02:10 -0700268 providersModified |= updateProvidersForPackageLocked(pkgName, null);
Amith Yamasani742a6712011-05-04 14:49:28 -0700269 }
270 } else {
271 // The package was just added
272 for (String pkgName : pkgList) {
Winson Chung7fbd2842012-06-13 10:35:51 -0700273 providersModified |= addProvidersForPackageLocked(pkgName);
Amith Yamasani742a6712011-05-04 14:49:28 -0700274 }
275 }
276 saveStateLocked();
277 }
278 } else {
279 Bundle extras = intent.getExtras();
280 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
281 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
282 } else {
283 synchronized (mAppWidgetIds) {
284 ensureStateLoadedLocked();
285 for (String pkgName : pkgList) {
Winson Chung7fbd2842012-06-13 10:35:51 -0700286 providersModified |= removeProvidersForPackageLocked(pkgName);
Amith Yamasani742a6712011-05-04 14:49:28 -0700287 saveStateLocked();
288 }
289 }
290 }
291 }
Winson Chung7fbd2842012-06-13 10:35:51 -0700292
293 if (providersModified) {
294 // If the set of providers has been modified, notify each active AppWidgetHost
295 synchronized (mAppWidgetIds) {
296 ensureStateLoadedLocked();
297 notifyHostsForProvidersChangedLocked();
298 }
299 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700300 }
301
302 private void dumpProvider(Provider p, int index, PrintWriter pw) {
303 AppWidgetProviderInfo info = p.info;
304 pw.print(" ["); pw.print(index); pw.print("] provider ");
305 pw.print(info.provider.flattenToShortString());
306 pw.println(':');
307 pw.print(" min=("); pw.print(info.minWidth);
308 pw.print("x"); pw.print(info.minHeight);
309 pw.print(") minResize=("); pw.print(info.minResizeWidth);
310 pw.print("x"); pw.print(info.minResizeHeight);
311 pw.print(") updatePeriodMillis=");
312 pw.print(info.updatePeriodMillis);
313 pw.print(" resizeMode=");
314 pw.print(info.resizeMode);
315 pw.print(" autoAdvanceViewId=");
316 pw.print(info.autoAdvanceViewId);
317 pw.print(" initialLayout=#");
318 pw.print(Integer.toHexString(info.initialLayout));
319 pw.print(" zombie="); pw.println(p.zombie);
320 }
321
322 private void dumpHost(Host host, int index, PrintWriter pw) {
323 pw.print(" ["); pw.print(index); pw.print("] hostId=");
324 pw.print(host.hostId); pw.print(' ');
325 pw.print(host.packageName); pw.print('/');
326 pw.print(host.uid); pw.println(':');
327 pw.print(" callbacks="); pw.println(host.callbacks);
328 pw.print(" instances.size="); pw.print(host.instances.size());
329 pw.print(" zombie="); pw.println(host.zombie);
330 }
331
332 private void dumpAppWidgetId(AppWidgetId id, int index, PrintWriter pw) {
333 pw.print(" ["); pw.print(index); pw.print("] id=");
334 pw.println(id.appWidgetId);
335 pw.print(" hostId=");
336 pw.print(id.host.hostId); pw.print(' ');
337 pw.print(id.host.packageName); pw.print('/');
338 pw.println(id.host.uid);
339 if (id.provider != null) {
340 pw.print(" provider=");
341 pw.println(id.provider.info.provider.flattenToShortString());
342 }
343 if (id.host != null) {
344 pw.print(" host.callbacks="); pw.println(id.host.callbacks);
345 }
346 if (id.views != null) {
347 pw.print(" views="); pw.println(id.views);
348 }
349 }
350
351 void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
352 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
353 != PackageManager.PERMISSION_GRANTED) {
354 pw.println("Permission Denial: can't dump from from pid="
355 + Binder.getCallingPid()
356 + ", uid=" + Binder.getCallingUid());
357 return;
358 }
359
360 synchronized (mAppWidgetIds) {
361 int N = mInstalledProviders.size();
362 pw.println("Providers:");
363 for (int i=0; i<N; i++) {
364 dumpProvider(mInstalledProviders.get(i), i, pw);
365 }
366
367 N = mAppWidgetIds.size();
368 pw.println(" ");
369 pw.println("AppWidgetIds:");
370 for (int i=0; i<N; i++) {
371 dumpAppWidgetId(mAppWidgetIds.get(i), i, pw);
372 }
373
374 N = mHosts.size();
375 pw.println(" ");
376 pw.println("Hosts:");
377 for (int i=0; i<N; i++) {
378 dumpHost(mHosts.get(i), i, pw);
379 }
380
381 N = mDeletedProviders.size();
382 pw.println(" ");
383 pw.println("Deleted Providers:");
384 for (int i=0; i<N; i++) {
385 dumpProvider(mDeletedProviders.get(i), i, pw);
386 }
387
388 N = mDeletedHosts.size();
389 pw.println(" ");
390 pw.println("Deleted Hosts:");
391 for (int i=0; i<N; i++) {
392 dumpHost(mDeletedHosts.get(i), i, pw);
393 }
394 }
395 }
396
397 private void ensureStateLoadedLocked() {
398 if (!mStateLoaded) {
399 loadAppWidgetList();
400 loadStateLocked();
401 mStateLoaded = true;
402 }
403 }
404
405 public int allocateAppWidgetId(String packageName, int hostId) {
406 int callingUid = enforceCallingUid(packageName);
407 synchronized (mAppWidgetIds) {
408 ensureStateLoadedLocked();
409 int appWidgetId = mNextAppWidgetId++;
410
411 Host host = lookupOrAddHostLocked(callingUid, packageName, hostId);
412
413 AppWidgetId id = new AppWidgetId();
414 id.appWidgetId = appWidgetId;
415 id.host = host;
416
417 host.instances.add(id);
418 mAppWidgetIds.add(id);
419
420 saveStateLocked();
421
422 return appWidgetId;
423 }
424 }
425
426 public void deleteAppWidgetId(int appWidgetId) {
427 synchronized (mAppWidgetIds) {
428 ensureStateLoadedLocked();
429 AppWidgetId id = lookupAppWidgetIdLocked(appWidgetId);
430 if (id != null) {
431 deleteAppWidgetLocked(id);
432 saveStateLocked();
433 }
434 }
435 }
436
437 public void deleteHost(int hostId) {
438 synchronized (mAppWidgetIds) {
439 ensureStateLoadedLocked();
440 int callingUid = Binder.getCallingUid();
441 Host host = lookupHostLocked(callingUid, hostId);
442 if (host != null) {
443 deleteHostLocked(host);
444 saveStateLocked();
445 }
446 }
447 }
448
449 public void deleteAllHosts() {
450 synchronized (mAppWidgetIds) {
451 ensureStateLoadedLocked();
452 int callingUid = Binder.getCallingUid();
453 final int N = mHosts.size();
454 boolean changed = false;
455 for (int i = N - 1; i >= 0; i--) {
456 Host host = mHosts.get(i);
457 if (host.uid == callingUid) {
458 deleteHostLocked(host);
459 changed = true;
460 }
461 }
462 if (changed) {
463 saveStateLocked();
464 }
465 }
466 }
467
468 void deleteHostLocked(Host host) {
469 final int N = host.instances.size();
470 for (int i = N - 1; i >= 0; i--) {
471 AppWidgetId id = host.instances.get(i);
472 deleteAppWidgetLocked(id);
473 }
474 host.instances.clear();
475 mHosts.remove(host);
476 mDeletedHosts.add(host);
477 // it's gone or going away, abruptly drop the callback connection
478 host.callbacks = null;
479 }
480
481 void deleteAppWidgetLocked(AppWidgetId id) {
482 // We first unbind all services that are bound to this id
483 unbindAppWidgetRemoteViewsServicesLocked(id);
484
485 Host host = id.host;
486 host.instances.remove(id);
487 pruneHostLocked(host);
488
489 mAppWidgetIds.remove(id);
490
491 Provider p = id.provider;
492 if (p != null) {
493 p.instances.remove(id);
494 if (!p.zombie) {
495 // send the broacast saying that this appWidgetId has been deleted
496 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_DELETED);
497 intent.setComponent(p.info.provider);
498 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id.appWidgetId);
Amith Yamasani67cf7d32012-02-16 14:31:23 -0800499 mContext.sendBroadcast(intent, mUserId);
Amith Yamasani742a6712011-05-04 14:49:28 -0700500 if (p.instances.size() == 0) {
501 // cancel the future updates
502 cancelBroadcasts(p);
503
504 // send the broacast saying that the provider is not in use any more
505 intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_DISABLED);
506 intent.setComponent(p.info.provider);
Amith Yamasani67cf7d32012-02-16 14:31:23 -0800507 mContext.sendBroadcast(intent, mUserId);
Amith Yamasani742a6712011-05-04 14:49:28 -0700508 }
509 }
510 }
511 }
512
513 void cancelBroadcasts(Provider p) {
514 if (p.broadcast != null) {
515 mAlarmManager.cancel(p.broadcast);
516 long token = Binder.clearCallingIdentity();
517 try {
518 p.broadcast.cancel();
519 } finally {
520 Binder.restoreCallingIdentity(token);
521 }
522 p.broadcast = null;
523 }
524 }
525
Michael Jurka61a5b012012-04-13 10:39:45 -0700526 private void bindAppWidgetIdImpl(int appWidgetId, ComponentName provider) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700527 final long ident = Binder.clearCallingIdentity();
528 try {
529 synchronized (mAppWidgetIds) {
530 ensureStateLoadedLocked();
531 AppWidgetId id = lookupAppWidgetIdLocked(appWidgetId);
532 if (id == null) {
533 throw new IllegalArgumentException("bad appWidgetId");
534 }
535 if (id.provider != null) {
536 throw new IllegalArgumentException("appWidgetId " + appWidgetId
537 + " already bound to " + id.provider.info.provider);
538 }
539 Provider p = lookupProviderLocked(provider);
540 if (p == null) {
541 throw new IllegalArgumentException("not a appwidget provider: " + provider);
542 }
543 if (p.zombie) {
544 throw new IllegalArgumentException("can't bind to a 3rd party provider in"
545 + " safe mode: " + provider);
546 }
547
Amith Yamasani742a6712011-05-04 14:49:28 -0700548 id.provider = p;
549 p.instances.add(id);
550 int instancesSize = p.instances.size();
551 if (instancesSize == 1) {
552 // tell the provider that it's ready
553 sendEnableIntentLocked(p);
554 }
555
556 // send an update now -- We need this update now, and just for this appWidgetId.
557 // It's less critical when the next one happens, so when we schedule the next one,
558 // we add updatePeriodMillis to its start time. That time will have some slop,
559 // but that's okay.
560 sendUpdateIntentLocked(p, new int[] { appWidgetId });
561
562 // schedule the future updates
563 registerForBroadcastsLocked(p, getAppWidgetIds(p));
564 saveStateLocked();
565 }
566 } finally {
567 Binder.restoreCallingIdentity(ident);
568 }
569 }
570
Michael Jurka61a5b012012-04-13 10:39:45 -0700571 public void bindAppWidgetId(int appWidgetId, ComponentName provider) {
572 mContext.enforceCallingPermission(android.Manifest.permission.BIND_APPWIDGET,
573 "bindAppWidgetId appWidgetId=" + appWidgetId + " provider=" + provider);
574 bindAppWidgetIdImpl(appWidgetId, provider);
575 }
576
577 public boolean bindAppWidgetIdIfAllowed(
578 String packageName, int appWidgetId, ComponentName provider) {
579 try {
580 mContext.enforceCallingPermission(android.Manifest.permission.BIND_APPWIDGET, null);
581 } catch (SecurityException se) {
582 if (!callerHasBindAppWidgetPermission(packageName)) {
583 return false;
584 }
585 }
586 bindAppWidgetIdImpl(appWidgetId, provider);
587 return true;
588 }
589
590 private boolean callerHasBindAppWidgetPermission(String packageName) {
591 int callingUid = Binder.getCallingUid();
592 try {
593 if (!UserId.isSameApp(callingUid, getUidForPackage(packageName))) {
594 return false;
595 }
596 } catch (Exception e) {
597 return false;
598 }
599 synchronized (mAppWidgetIds) {
600 ensureStateLoadedLocked();
601 return mPackagesWithBindWidgetPermission.contains(packageName);
602 }
603 }
604
605 public boolean hasBindAppWidgetPermission(String packageName) {
606 mContext.enforceCallingPermission(
607 android.Manifest.permission.MODIFY_APPWIDGET_BIND_PERMISSIONS,
608 "hasBindAppWidgetPermission packageName=" + packageName);
609
610 synchronized (mAppWidgetIds) {
611 ensureStateLoadedLocked();
612 return mPackagesWithBindWidgetPermission.contains(packageName);
613 }
614 }
615
616 public void setBindAppWidgetPermission(String packageName, boolean permission) {
617 mContext.enforceCallingPermission(
618 android.Manifest.permission.MODIFY_APPWIDGET_BIND_PERMISSIONS,
619 "setBindAppWidgetPermission packageName=" + packageName);
620
621 synchronized (mAppWidgetIds) {
622 ensureStateLoadedLocked();
623 if (permission) {
624 mPackagesWithBindWidgetPermission.add(packageName);
625 } else {
626 mPackagesWithBindWidgetPermission.remove(packageName);
627 }
628 }
629 saveStateLocked();
630 }
631
Amith Yamasani742a6712011-05-04 14:49:28 -0700632 // Binds to a specific RemoteViewsService
633 public void bindRemoteViewsService(int appWidgetId, Intent intent, IBinder connection) {
634 synchronized (mAppWidgetIds) {
635 ensureStateLoadedLocked();
636 AppWidgetId id = lookupAppWidgetIdLocked(appWidgetId);
637 if (id == null) {
638 throw new IllegalArgumentException("bad appWidgetId");
639 }
640 final ComponentName componentName = intent.getComponent();
641 try {
642 final ServiceInfo si = mContext.getPackageManager().getServiceInfo(componentName,
643 PackageManager.GET_PERMISSIONS);
644 if (!android.Manifest.permission.BIND_REMOTEVIEWS.equals(si.permission)) {
645 throw new SecurityException("Selected service does not require "
646 + android.Manifest.permission.BIND_REMOTEVIEWS + ": " + componentName);
647 }
648 } catch (PackageManager.NameNotFoundException e) {
649 throw new IllegalArgumentException("Unknown component " + componentName);
650 }
651
652 // If there is already a connection made for this service intent, then disconnect from
653 // that first. (This does not allow multiple connections to the same service under
654 // the same key)
655 ServiceConnectionProxy conn = null;
656 FilterComparison fc = new FilterComparison(intent);
657 Pair<Integer, FilterComparison> key = Pair.create(appWidgetId, fc);
658 if (mBoundRemoteViewsServices.containsKey(key)) {
659 conn = (ServiceConnectionProxy) mBoundRemoteViewsServices.get(key);
660 conn.disconnect();
661 mContext.unbindService(conn);
662 mBoundRemoteViewsServices.remove(key);
663 }
664
Amith Yamasani37ce3a82012-02-06 12:04:42 -0800665 int userId = UserId.getUserId(id.provider.uid);
Amith Yamasani742a6712011-05-04 14:49:28 -0700666 // Bind to the RemoteViewsService (which will trigger a callback to the
667 // RemoteViewsAdapter.onServiceConnected())
668 final long token = Binder.clearCallingIdentity();
669 try {
670 conn = new ServiceConnectionProxy(key, connection);
Amith Yamasani37ce3a82012-02-06 12:04:42 -0800671 mContext.bindService(intent, conn, Context.BIND_AUTO_CREATE, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -0700672 mBoundRemoteViewsServices.put(key, conn);
673 } finally {
674 Binder.restoreCallingIdentity(token);
675 }
676
677 // Add it to the mapping of RemoteViewsService to appWidgetIds so that we can determine
678 // when we can call back to the RemoteViewsService later to destroy associated
679 // factories.
680 incrementAppWidgetServiceRefCount(appWidgetId, fc);
681 }
682 }
683
684 // Unbinds from a specific RemoteViewsService
685 public void unbindRemoteViewsService(int appWidgetId, Intent intent) {
686 synchronized (mAppWidgetIds) {
687 ensureStateLoadedLocked();
688 // Unbind from the RemoteViewsService (which will trigger a callback to the bound
689 // RemoteViewsAdapter)
690 Pair<Integer, FilterComparison> key = Pair.create(appWidgetId, new FilterComparison(
691 intent));
692 if (mBoundRemoteViewsServices.containsKey(key)) {
693 // We don't need to use the appWidgetId until after we are sure there is something
694 // to unbind. Note that this may mask certain issues with apps calling unbind()
695 // more than necessary.
696 AppWidgetId id = lookupAppWidgetIdLocked(appWidgetId);
697 if (id == null) {
698 throw new IllegalArgumentException("bad appWidgetId");
699 }
700
701 ServiceConnectionProxy conn = (ServiceConnectionProxy) mBoundRemoteViewsServices
702 .get(key);
703 conn.disconnect();
704 mContext.unbindService(conn);
705 mBoundRemoteViewsServices.remove(key);
706 } else {
707 Log.e("AppWidgetService", "Error (unbindRemoteViewsService): Connection not bound");
708 }
709 }
710 }
711
712 // Unbinds from a RemoteViewsService when we delete an app widget
713 private void unbindAppWidgetRemoteViewsServicesLocked(AppWidgetId id) {
714 int appWidgetId = id.appWidgetId;
715 // Unbind all connections to Services bound to this AppWidgetId
716 Iterator<Pair<Integer, Intent.FilterComparison>> it = mBoundRemoteViewsServices.keySet()
717 .iterator();
718 while (it.hasNext()) {
719 final Pair<Integer, Intent.FilterComparison> key = it.next();
720 if (key.first.intValue() == appWidgetId) {
721 final ServiceConnectionProxy conn = (ServiceConnectionProxy) mBoundRemoteViewsServices
722 .get(key);
723 conn.disconnect();
724 mContext.unbindService(conn);
725 it.remove();
726 }
727 }
728
729 // Check if we need to destroy any services (if no other app widgets are
730 // referencing the same service)
Amith Yamasani37ce3a82012-02-06 12:04:42 -0800731 decrementAppWidgetServiceRefCount(id);
Amith Yamasani742a6712011-05-04 14:49:28 -0700732 }
733
734 // Destroys the cached factory on the RemoteViewsService's side related to the specified intent
Amith Yamasani37ce3a82012-02-06 12:04:42 -0800735 private void destroyRemoteViewsService(final Intent intent, AppWidgetId id) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700736 final ServiceConnection conn = new ServiceConnection() {
737 @Override
738 public void onServiceConnected(ComponentName name, IBinder service) {
739 final IRemoteViewsFactory cb = IRemoteViewsFactory.Stub.asInterface(service);
740 try {
741 cb.onDestroy(intent);
742 } catch (RemoteException e) {
743 e.printStackTrace();
744 } catch (RuntimeException e) {
745 e.printStackTrace();
746 }
747 mContext.unbindService(this);
748 }
749
750 @Override
751 public void onServiceDisconnected(android.content.ComponentName name) {
752 // Do nothing
753 }
754 };
755
Amith Yamasani37ce3a82012-02-06 12:04:42 -0800756 int userId = UserId.getUserId(id.provider.uid);
Amith Yamasani742a6712011-05-04 14:49:28 -0700757 // Bind to the service and remove the static intent->factory mapping in the
758 // RemoteViewsService.
759 final long token = Binder.clearCallingIdentity();
760 try {
Amith Yamasani37ce3a82012-02-06 12:04:42 -0800761 mContext.bindService(intent, conn, Context.BIND_AUTO_CREATE, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -0700762 } finally {
763 Binder.restoreCallingIdentity(token);
764 }
765 }
766
767 // Adds to the ref-count for a given RemoteViewsService intent
768 private void incrementAppWidgetServiceRefCount(int appWidgetId, FilterComparison fc) {
769 HashSet<Integer> appWidgetIds = null;
770 if (mRemoteViewsServicesAppWidgets.containsKey(fc)) {
771 appWidgetIds = mRemoteViewsServicesAppWidgets.get(fc);
772 } else {
773 appWidgetIds = new HashSet<Integer>();
774 mRemoteViewsServicesAppWidgets.put(fc, appWidgetIds);
775 }
776 appWidgetIds.add(appWidgetId);
777 }
778
779 // Subtracts from the ref-count for a given RemoteViewsService intent, prompting a delete if
780 // the ref-count reaches zero.
Amith Yamasani37ce3a82012-02-06 12:04:42 -0800781 private void decrementAppWidgetServiceRefCount(AppWidgetId id) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700782 Iterator<FilterComparison> it = mRemoteViewsServicesAppWidgets.keySet().iterator();
783 while (it.hasNext()) {
784 final FilterComparison key = it.next();
785 final HashSet<Integer> ids = mRemoteViewsServicesAppWidgets.get(key);
Amith Yamasani37ce3a82012-02-06 12:04:42 -0800786 if (ids.remove(id.appWidgetId)) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700787 // If we have removed the last app widget referencing this service, then we
788 // should destroy it and remove it from this set
789 if (ids.isEmpty()) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -0800790 destroyRemoteViewsService(key.getIntent(), id);
Amith Yamasani742a6712011-05-04 14:49:28 -0700791 it.remove();
792 }
793 }
794 }
795 }
796
797 public AppWidgetProviderInfo getAppWidgetInfo(int appWidgetId) {
798 synchronized (mAppWidgetIds) {
799 ensureStateLoadedLocked();
800 AppWidgetId id = lookupAppWidgetIdLocked(appWidgetId);
801 if (id != null && id.provider != null && !id.provider.zombie) {
802 return id.provider.info;
803 }
804 return null;
805 }
806 }
807
808 public RemoteViews getAppWidgetViews(int appWidgetId) {
809 synchronized (mAppWidgetIds) {
810 ensureStateLoadedLocked();
811 AppWidgetId id = lookupAppWidgetIdLocked(appWidgetId);
812 if (id != null) {
813 return id.views;
814 }
815 return null;
816 }
817 }
818
819 public List<AppWidgetProviderInfo> getInstalledProviders() {
820 synchronized (mAppWidgetIds) {
821 ensureStateLoadedLocked();
822 final int N = mInstalledProviders.size();
823 ArrayList<AppWidgetProviderInfo> result = new ArrayList<AppWidgetProviderInfo>(N);
824 for (int i = 0; i < N; i++) {
825 Provider p = mInstalledProviders.get(i);
826 if (!p.zombie) {
827 result.add(p.info);
828 }
829 }
830 return result;
831 }
832 }
833
834 public void updateAppWidgetIds(int[] appWidgetIds, RemoteViews views) {
835 if (appWidgetIds == null) {
836 return;
837 }
Adam Cohen311c79c2012-05-10 14:44:38 -0700838
839 int bitmapMemoryUsage = views.estimateMemoryUsage();
840 if (bitmapMemoryUsage > mMaxWidgetBitmapMemory) {
841 throw new IllegalArgumentException("RemoteViews for widget update exceeds maximum" +
842 " bitmap memory usage (used: " + bitmapMemoryUsage + ", max: " +
843 mMaxWidgetBitmapMemory + ") The total memory cannot exceed that required to" +
844 " fill the device's screen once.");
845 }
846
Amith Yamasani742a6712011-05-04 14:49:28 -0700847 if (appWidgetIds.length == 0) {
848 return;
849 }
850 final int N = appWidgetIds.length;
851
852 synchronized (mAppWidgetIds) {
853 ensureStateLoadedLocked();
854 for (int i = 0; i < N; i++) {
855 AppWidgetId id = lookupAppWidgetIdLocked(appWidgetIds[i]);
856 updateAppWidgetInstanceLocked(id, views);
857 }
858 }
859 }
860
Adam Cohend2097eb2012-05-01 18:10:28 -0700861 public void updateAppWidgetOptions(int appWidgetId, Bundle options) {
Adam Cohene8724c82012-04-19 17:11:40 -0700862 synchronized (mAppWidgetIds) {
863 ensureStateLoadedLocked();
864 AppWidgetId id = lookupAppWidgetIdLocked(appWidgetId);
865
866 if (id == null) {
867 return;
868 }
869 Provider p = id.provider;
Adam Cohend2097eb2012-05-01 18:10:28 -0700870 id.options = options;
Adam Cohene8724c82012-04-19 17:11:40 -0700871
872 // send the broacast saying that this appWidgetId has been deleted
Adam Cohend2097eb2012-05-01 18:10:28 -0700873 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_OPTIONS_CHANGED);
Adam Cohene8724c82012-04-19 17:11:40 -0700874 intent.setComponent(p.info.provider);
875 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id.appWidgetId);
Adam Cohend2097eb2012-05-01 18:10:28 -0700876 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_OPTIONS, options);
Adam Cohene8724c82012-04-19 17:11:40 -0700877 mContext.sendBroadcast(intent, mUserId);
878 }
879 }
880
Adam Cohend2097eb2012-05-01 18:10:28 -0700881 public Bundle getAppWidgetOptions(int appWidgetId) {
Adam Cohene8724c82012-04-19 17:11:40 -0700882 synchronized (mAppWidgetIds) {
883 ensureStateLoadedLocked();
884 AppWidgetId id = lookupAppWidgetIdLocked(appWidgetId);
Adam Cohend2097eb2012-05-01 18:10:28 -0700885 if (id != null && id.options != null) {
886 return id.options;
Adam Cohene8724c82012-04-19 17:11:40 -0700887 } else {
888 return Bundle.EMPTY;
889 }
890 }
891 }
892
Amith Yamasani742a6712011-05-04 14:49:28 -0700893 public void partiallyUpdateAppWidgetIds(int[] appWidgetIds, RemoteViews views) {
894 if (appWidgetIds == null) {
895 return;
896 }
897 if (appWidgetIds.length == 0) {
898 return;
899 }
900 final int N = appWidgetIds.length;
901
902 synchronized (mAppWidgetIds) {
903 ensureStateLoadedLocked();
904 for (int i = 0; i < N; i++) {
905 AppWidgetId id = lookupAppWidgetIdLocked(appWidgetIds[i]);
906 updateAppWidgetInstanceLocked(id, views, true);
907 }
908 }
909 }
910
911 public void notifyAppWidgetViewDataChanged(int[] appWidgetIds, int viewId) {
912 if (appWidgetIds == null) {
913 return;
914 }
915 if (appWidgetIds.length == 0) {
916 return;
917 }
918 final int N = appWidgetIds.length;
919
920 synchronized (mAppWidgetIds) {
921 ensureStateLoadedLocked();
922 for (int i = 0; i < N; i++) {
923 AppWidgetId id = lookupAppWidgetIdLocked(appWidgetIds[i]);
924 notifyAppWidgetViewDataChangedInstanceLocked(id, viewId);
925 }
926 }
927 }
928
929 public void updateAppWidgetProvider(ComponentName provider, RemoteViews views) {
930 synchronized (mAppWidgetIds) {
931 ensureStateLoadedLocked();
932 Provider p = lookupProviderLocked(provider);
933 if (p == null) {
934 Slog.w(TAG, "updateAppWidgetProvider: provider doesn't exist: " + provider);
935 return;
936 }
937 ArrayList<AppWidgetId> instances = p.instances;
938 final int callingUid = Binder.getCallingUid();
939 final int N = instances.size();
940 for (int i = 0; i < N; i++) {
941 AppWidgetId id = instances.get(i);
942 if (canAccessAppWidgetId(id, callingUid)) {
943 updateAppWidgetInstanceLocked(id, views);
944 }
945 }
946 }
947 }
948
949 void updateAppWidgetInstanceLocked(AppWidgetId id, RemoteViews views) {
950 updateAppWidgetInstanceLocked(id, views, false);
951 }
952
953 void updateAppWidgetInstanceLocked(AppWidgetId id, RemoteViews views, boolean isPartialUpdate) {
954 // allow for stale appWidgetIds and other badness
955 // lookup also checks that the calling process can access the appWidgetId
956 // drop unbound appWidgetIds (shouldn't be possible under normal circumstances)
957 if (id != null && id.provider != null && !id.provider.zombie && !id.host.zombie) {
958
959 // We do not want to save this RemoteViews
960 if (!isPartialUpdate)
961 id.views = views;
962
963 // is anyone listening?
964 if (id.host.callbacks != null) {
965 try {
966 // the lock is held, but this is a oneway call
967 id.host.callbacks.updateAppWidget(id.appWidgetId, views);
968 } catch (RemoteException e) {
969 // It failed; remove the callback. No need to prune because
970 // we know that this host is still referenced by this instance.
971 id.host.callbacks = null;
972 }
973 }
974 }
975 }
976
977 void notifyAppWidgetViewDataChangedInstanceLocked(AppWidgetId id, int viewId) {
978 // allow for stale appWidgetIds and other badness
979 // lookup also checks that the calling process can access the appWidgetId
980 // drop unbound appWidgetIds (shouldn't be possible under normal circumstances)
981 if (id != null && id.provider != null && !id.provider.zombie && !id.host.zombie) {
982 // is anyone listening?
983 if (id.host.callbacks != null) {
984 try {
985 // the lock is held, but this is a oneway call
986 id.host.callbacks.viewDataChanged(id.appWidgetId, viewId);
987 } catch (RemoteException e) {
988 // It failed; remove the callback. No need to prune because
989 // we know that this host is still referenced by this instance.
990 id.host.callbacks = null;
991 }
992 }
993
994 // If the host is unavailable, then we call the associated
995 // RemoteViewsFactory.onDataSetChanged() directly
996 if (id.host.callbacks == null) {
997 Set<FilterComparison> keys = mRemoteViewsServicesAppWidgets.keySet();
998 for (FilterComparison key : keys) {
999 if (mRemoteViewsServicesAppWidgets.get(key).contains(id.appWidgetId)) {
1000 Intent intent = key.getIntent();
1001
1002 final ServiceConnection conn = new ServiceConnection() {
1003 @Override
1004 public void onServiceConnected(ComponentName name, IBinder service) {
1005 IRemoteViewsFactory cb = IRemoteViewsFactory.Stub
1006 .asInterface(service);
1007 try {
1008 cb.onDataSetChangedAsync();
1009 } catch (RemoteException e) {
1010 e.printStackTrace();
1011 } catch (RuntimeException e) {
1012 e.printStackTrace();
1013 }
1014 mContext.unbindService(this);
1015 }
1016
1017 @Override
1018 public void onServiceDisconnected(android.content.ComponentName name) {
1019 // Do nothing
1020 }
1021 };
1022
Amith Yamasani37ce3a82012-02-06 12:04:42 -08001023 int userId = UserId.getUserId(id.provider.uid);
Amith Yamasani742a6712011-05-04 14:49:28 -07001024 // Bind to the service and call onDataSetChanged()
1025 final long token = Binder.clearCallingIdentity();
1026 try {
Amith Yamasani37ce3a82012-02-06 12:04:42 -08001027 mContext.bindService(intent, conn, Context.BIND_AUTO_CREATE, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07001028 } finally {
1029 Binder.restoreCallingIdentity(token);
1030 }
1031 }
1032 }
1033 }
1034 }
1035 }
1036
1037 public int[] startListening(IAppWidgetHost callbacks, String packageName, int hostId,
1038 List<RemoteViews> updatedViews) {
1039 int callingUid = enforceCallingUid(packageName);
1040 synchronized (mAppWidgetIds) {
1041 ensureStateLoadedLocked();
1042 Host host = lookupOrAddHostLocked(callingUid, packageName, hostId);
1043 host.callbacks = callbacks;
1044
1045 updatedViews.clear();
1046
1047 ArrayList<AppWidgetId> instances = host.instances;
1048 int N = instances.size();
1049 int[] updatedIds = new int[N];
1050 for (int i = 0; i < N; i++) {
1051 AppWidgetId id = instances.get(i);
1052 updatedIds[i] = id.appWidgetId;
1053 updatedViews.add(id.views);
1054 }
1055 return updatedIds;
1056 }
1057 }
1058
1059 public void stopListening(int hostId) {
1060 synchronized (mAppWidgetIds) {
1061 ensureStateLoadedLocked();
1062 Host host = lookupHostLocked(Binder.getCallingUid(), hostId);
1063 if (host != null) {
1064 host.callbacks = null;
1065 pruneHostLocked(host);
1066 }
1067 }
1068 }
1069
1070 boolean canAccessAppWidgetId(AppWidgetId id, int callingUid) {
1071 if (id.host.uid == callingUid) {
1072 // Apps hosting the AppWidget have access to it.
1073 return true;
1074 }
1075 if (id.provider != null && id.provider.uid == callingUid) {
1076 // Apps providing the AppWidget have access to it (if the appWidgetId has been bound)
1077 return true;
1078 }
1079 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.BIND_APPWIDGET) == PackageManager.PERMISSION_GRANTED) {
1080 // Apps that can bind have access to all appWidgetIds.
1081 return true;
1082 }
1083 // Nobody else can access it.
1084 return false;
1085 }
1086
1087 AppWidgetId lookupAppWidgetIdLocked(int appWidgetId) {
1088 int callingUid = Binder.getCallingUid();
1089 final int N = mAppWidgetIds.size();
1090 for (int i = 0; i < N; i++) {
1091 AppWidgetId id = mAppWidgetIds.get(i);
1092 if (id.appWidgetId == appWidgetId && canAccessAppWidgetId(id, callingUid)) {
1093 return id;
1094 }
1095 }
1096 return null;
1097 }
1098
1099 Provider lookupProviderLocked(ComponentName provider) {
1100 final int N = mInstalledProviders.size();
1101 for (int i = 0; i < N; i++) {
1102 Provider p = mInstalledProviders.get(i);
1103 if (p.info.provider.equals(provider)) {
1104 return p;
1105 }
1106 }
1107 return null;
1108 }
1109
1110 Host lookupHostLocked(int uid, int hostId) {
1111 final int N = mHosts.size();
1112 for (int i = 0; i < N; i++) {
1113 Host h = mHosts.get(i);
1114 if (h.uid == uid && h.hostId == hostId) {
1115 return h;
1116 }
1117 }
1118 return null;
1119 }
1120
1121 Host lookupOrAddHostLocked(int uid, String packageName, int hostId) {
1122 final int N = mHosts.size();
1123 for (int i = 0; i < N; i++) {
1124 Host h = mHosts.get(i);
1125 if (h.hostId == hostId && h.packageName.equals(packageName)) {
1126 return h;
1127 }
1128 }
1129 Host host = new Host();
1130 host.packageName = packageName;
1131 host.uid = uid;
1132 host.hostId = hostId;
1133 mHosts.add(host);
1134 return host;
1135 }
1136
1137 void pruneHostLocked(Host host) {
1138 if (host.instances.size() == 0 && host.callbacks == null) {
1139 mHosts.remove(host);
1140 }
1141 }
1142
1143 void loadAppWidgetList() {
Amith Yamasani742a6712011-05-04 14:49:28 -07001144 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001145 try {
1146 List<ResolveInfo> broadcastReceivers = mPm.queryIntentReceivers(intent,
1147 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
1148 PackageManager.GET_META_DATA, mUserId);
Amith Yamasani742a6712011-05-04 14:49:28 -07001149
Amith Yamasani483f3b02012-03-13 16:08:00 -07001150 final int N = broadcastReceivers == null ? 0 : broadcastReceivers.size();
1151 for (int i = 0; i < N; i++) {
1152 ResolveInfo ri = broadcastReceivers.get(i);
1153 addProviderLocked(ri);
1154 }
1155 } catch (RemoteException re) {
1156 // Shouldn't happen, local call
Amith Yamasani742a6712011-05-04 14:49:28 -07001157 }
1158 }
1159
1160 boolean addProviderLocked(ResolveInfo ri) {
1161 if ((ri.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
1162 return false;
1163 }
1164 if (!ri.activityInfo.isEnabled()) {
1165 return false;
1166 }
1167 Provider p = parseProviderInfoXml(new ComponentName(ri.activityInfo.packageName,
1168 ri.activityInfo.name), ri);
1169 if (p != null) {
1170 mInstalledProviders.add(p);
1171 return true;
1172 } else {
1173 return false;
1174 }
1175 }
1176
1177 void removeProviderLocked(int index, Provider p) {
1178 int N = p.instances.size();
1179 for (int i = 0; i < N; i++) {
1180 AppWidgetId id = p.instances.get(i);
1181 // Call back with empty RemoteViews
1182 updateAppWidgetInstanceLocked(id, null);
1183 // Stop telling the host about updates for this from now on
1184 cancelBroadcasts(p);
1185 // clear out references to this appWidgetId
1186 id.host.instances.remove(id);
1187 mAppWidgetIds.remove(id);
1188 id.provider = null;
1189 pruneHostLocked(id.host);
1190 id.host = null;
1191 }
1192 p.instances.clear();
1193 mInstalledProviders.remove(index);
1194 mDeletedProviders.add(p);
1195 // no need to send the DISABLE broadcast, since the receiver is gone anyway
1196 cancelBroadcasts(p);
1197 }
1198
1199 void sendEnableIntentLocked(Provider p) {
1200 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_ENABLED);
1201 intent.setComponent(p.info.provider);
Amith Yamasani67cf7d32012-02-16 14:31:23 -08001202 mContext.sendBroadcast(intent, mUserId);
Amith Yamasani742a6712011-05-04 14:49:28 -07001203 }
1204
1205 void sendUpdateIntentLocked(Provider p, int[] appWidgetIds) {
1206 if (appWidgetIds != null && appWidgetIds.length > 0) {
1207 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
1208 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
1209 intent.setComponent(p.info.provider);
Amith Yamasani67cf7d32012-02-16 14:31:23 -08001210 mContext.sendBroadcast(intent, mUserId);
Amith Yamasani742a6712011-05-04 14:49:28 -07001211 }
1212 }
1213
1214 void registerForBroadcastsLocked(Provider p, int[] appWidgetIds) {
1215 if (p.info.updatePeriodMillis > 0) {
1216 // if this is the first instance, set the alarm. otherwise,
1217 // rely on the fact that we've already set it and that
1218 // PendingIntent.getBroadcast will update the extras.
1219 boolean alreadyRegistered = p.broadcast != null;
1220 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
1221 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
1222 intent.setComponent(p.info.provider);
1223 long token = Binder.clearCallingIdentity();
1224 try {
1225 p.broadcast = PendingIntent.getBroadcast(mContext, 1, intent,
1226 PendingIntent.FLAG_UPDATE_CURRENT);
1227 } finally {
1228 Binder.restoreCallingIdentity(token);
1229 }
1230 if (!alreadyRegistered) {
1231 long period = p.info.updatePeriodMillis;
1232 if (period < MIN_UPDATE_PERIOD) {
1233 period = MIN_UPDATE_PERIOD;
1234 }
1235 mAlarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock
1236 .elapsedRealtime()
1237 + period, period, p.broadcast);
1238 }
1239 }
1240 }
1241
1242 static int[] getAppWidgetIds(Provider p) {
1243 int instancesSize = p.instances.size();
1244 int appWidgetIds[] = new int[instancesSize];
1245 for (int i = 0; i < instancesSize; i++) {
1246 appWidgetIds[i] = p.instances.get(i).appWidgetId;
1247 }
1248 return appWidgetIds;
1249 }
1250
1251 public int[] getAppWidgetIds(ComponentName provider) {
1252 synchronized (mAppWidgetIds) {
1253 ensureStateLoadedLocked();
1254 Provider p = lookupProviderLocked(provider);
1255 if (p != null && Binder.getCallingUid() == p.uid) {
1256 return getAppWidgetIds(p);
1257 } else {
1258 return new int[0];
1259 }
1260 }
1261 }
1262
1263 private Provider parseProviderInfoXml(ComponentName component, ResolveInfo ri) {
1264 Provider p = null;
1265
1266 ActivityInfo activityInfo = ri.activityInfo;
1267 XmlResourceParser parser = null;
1268 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001269 parser = activityInfo.loadXmlMetaData(mContext.getPackageManager(),
Amith Yamasani742a6712011-05-04 14:49:28 -07001270 AppWidgetManager.META_DATA_APPWIDGET_PROVIDER);
1271 if (parser == null) {
1272 Slog.w(TAG, "No " + AppWidgetManager.META_DATA_APPWIDGET_PROVIDER
1273 + " meta-data for " + "AppWidget provider '" + component + '\'');
1274 return null;
1275 }
1276
1277 AttributeSet attrs = Xml.asAttributeSet(parser);
1278
1279 int type;
1280 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1281 && type != XmlPullParser.START_TAG) {
1282 // drain whitespace, comments, etc.
1283 }
1284
1285 String nodeName = parser.getName();
1286 if (!"appwidget-provider".equals(nodeName)) {
1287 Slog.w(TAG, "Meta-data does not start with appwidget-provider tag for"
1288 + " AppWidget provider '" + component + '\'');
1289 return null;
1290 }
1291
1292 p = new Provider();
1293 AppWidgetProviderInfo info = p.info = new AppWidgetProviderInfo();
1294 info.provider = component;
1295 p.uid = activityInfo.applicationInfo.uid;
1296
Amith Yamasani483f3b02012-03-13 16:08:00 -07001297 Resources res = mContext.getPackageManager()
Amith Yamasani742a6712011-05-04 14:49:28 -07001298 .getResourcesForApplication(activityInfo.applicationInfo);
1299
1300 TypedArray sa = res.obtainAttributes(attrs,
1301 com.android.internal.R.styleable.AppWidgetProviderInfo);
1302
1303 // These dimensions has to be resolved in the application's context.
1304 // We simply send back the raw complex data, which will be
1305 // converted to dp in {@link AppWidgetManager#getAppWidgetInfo}.
1306 TypedValue value = sa
1307 .peekValue(com.android.internal.R.styleable.AppWidgetProviderInfo_minWidth);
1308 info.minWidth = value != null ? value.data : 0;
1309 value = sa.peekValue(com.android.internal.R.styleable.AppWidgetProviderInfo_minHeight);
1310 info.minHeight = value != null ? value.data : 0;
1311 value = sa.peekValue(
1312 com.android.internal.R.styleable.AppWidgetProviderInfo_minResizeWidth);
1313 info.minResizeWidth = value != null ? value.data : info.minWidth;
1314 value = sa.peekValue(
1315 com.android.internal.R.styleable.AppWidgetProviderInfo_minResizeHeight);
1316 info.minResizeHeight = value != null ? value.data : info.minHeight;
1317 info.updatePeriodMillis = sa.getInt(
1318 com.android.internal.R.styleable.AppWidgetProviderInfo_updatePeriodMillis, 0);
1319 info.initialLayout = sa.getResourceId(
1320 com.android.internal.R.styleable.AppWidgetProviderInfo_initialLayout, 0);
1321 String className = sa
1322 .getString(com.android.internal.R.styleable.AppWidgetProviderInfo_configure);
1323 if (className != null) {
1324 info.configure = new ComponentName(component.getPackageName(), className);
1325 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07001326 info.label = activityInfo.loadLabel(mContext.getPackageManager()).toString();
Amith Yamasani742a6712011-05-04 14:49:28 -07001327 info.icon = ri.getIconResource();
1328 info.previewImage = sa.getResourceId(
1329 com.android.internal.R.styleable.AppWidgetProviderInfo_previewImage, 0);
1330 info.autoAdvanceViewId = sa.getResourceId(
1331 com.android.internal.R.styleable.AppWidgetProviderInfo_autoAdvanceViewId, -1);
1332 info.resizeMode = sa.getInt(
1333 com.android.internal.R.styleable.AppWidgetProviderInfo_resizeMode,
1334 AppWidgetProviderInfo.RESIZE_NONE);
1335
1336 sa.recycle();
1337 } catch (Exception e) {
1338 // Ok to catch Exception here, because anything going wrong because
1339 // of what a client process passes to us should not be fatal for the
1340 // system process.
1341 Slog.w(TAG, "XML parsing failed for AppWidget provider '" + component + '\'', e);
1342 return null;
1343 } finally {
1344 if (parser != null)
1345 parser.close();
1346 }
1347 return p;
1348 }
1349
1350 int getUidForPackage(String packageName) throws PackageManager.NameNotFoundException {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001351 PackageInfo pkgInfo = null;
1352 try {
1353 pkgInfo = mPm.getPackageInfo(packageName, 0, mUserId);
1354 } catch (RemoteException re) {
1355 // Shouldn't happen, local call
1356 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001357 if (pkgInfo == null || pkgInfo.applicationInfo == null) {
1358 throw new PackageManager.NameNotFoundException();
1359 }
1360 return pkgInfo.applicationInfo.uid;
1361 }
1362
1363 int enforceCallingUid(String packageName) throws IllegalArgumentException {
1364 int callingUid = Binder.getCallingUid();
1365 int packageUid;
1366 try {
1367 packageUid = getUidForPackage(packageName);
1368 } catch (PackageManager.NameNotFoundException ex) {
1369 throw new IllegalArgumentException("packageName and uid don't match packageName="
1370 + packageName);
1371 }
1372 if (!UserId.isSameApp(callingUid, packageUid)) {
1373 throw new IllegalArgumentException("packageName and uid don't match packageName="
1374 + packageName);
1375 }
1376 return callingUid;
1377 }
1378
1379 void sendInitialBroadcasts() {
1380 synchronized (mAppWidgetIds) {
1381 ensureStateLoadedLocked();
1382 final int N = mInstalledProviders.size();
1383 for (int i = 0; i < N; i++) {
1384 Provider p = mInstalledProviders.get(i);
1385 if (p.instances.size() > 0) {
1386 sendEnableIntentLocked(p);
1387 int[] appWidgetIds = getAppWidgetIds(p);
1388 sendUpdateIntentLocked(p, appWidgetIds);
1389 registerForBroadcastsLocked(p, appWidgetIds);
1390 }
1391 }
1392 }
1393 }
1394
1395 // only call from initialization -- it assumes that the data structures are all empty
1396 void loadStateLocked() {
1397 AtomicFile file = savedStateFile();
1398 try {
1399 FileInputStream stream = file.openRead();
1400 readStateFromFileLocked(stream);
1401
1402 if (stream != null) {
1403 try {
1404 stream.close();
1405 } catch (IOException e) {
1406 Slog.w(TAG, "Failed to close state FileInputStream " + e);
1407 }
1408 }
1409 } catch (FileNotFoundException e) {
1410 Slog.w(TAG, "Failed to read state: " + e);
1411 }
1412 }
1413
1414 void saveStateLocked() {
1415 AtomicFile file = savedStateFile();
1416 FileOutputStream stream;
1417 try {
1418 stream = file.startWrite();
1419 if (writeStateToFileLocked(stream)) {
1420 file.finishWrite(stream);
1421 } else {
1422 file.failWrite(stream);
1423 Slog.w(TAG, "Failed to save state, restoring backup.");
1424 }
1425 } catch (IOException e) {
1426 Slog.w(TAG, "Failed open state file for write: " + e);
1427 }
1428 }
1429
1430 boolean writeStateToFileLocked(FileOutputStream stream) {
1431 int N;
1432
1433 try {
1434 XmlSerializer out = new FastXmlSerializer();
1435 out.setOutput(stream, "utf-8");
1436 out.startDocument(null, true);
1437 out.startTag(null, "gs");
1438
1439 int providerIndex = 0;
1440 N = mInstalledProviders.size();
1441 for (int i = 0; i < N; i++) {
1442 Provider p = mInstalledProviders.get(i);
1443 if (p.instances.size() > 0) {
1444 out.startTag(null, "p");
1445 out.attribute(null, "pkg", p.info.provider.getPackageName());
1446 out.attribute(null, "cl", p.info.provider.getClassName());
1447 out.endTag(null, "p");
1448 p.tag = providerIndex;
1449 providerIndex++;
1450 }
1451 }
1452
1453 N = mHosts.size();
1454 for (int i = 0; i < N; i++) {
1455 Host host = mHosts.get(i);
1456 out.startTag(null, "h");
1457 out.attribute(null, "pkg", host.packageName);
1458 out.attribute(null, "id", Integer.toHexString(host.hostId));
1459 out.endTag(null, "h");
1460 host.tag = i;
1461 }
1462
1463 N = mAppWidgetIds.size();
1464 for (int i = 0; i < N; i++) {
1465 AppWidgetId id = mAppWidgetIds.get(i);
1466 out.startTag(null, "g");
1467 out.attribute(null, "id", Integer.toHexString(id.appWidgetId));
1468 out.attribute(null, "h", Integer.toHexString(id.host.tag));
1469 if (id.provider != null) {
1470 out.attribute(null, "p", Integer.toHexString(id.provider.tag));
1471 }
1472 out.endTag(null, "g");
1473 }
1474
Michael Jurka61a5b012012-04-13 10:39:45 -07001475 Iterator<String> it = mPackagesWithBindWidgetPermission.iterator();
1476 while (it.hasNext()) {
1477 out.startTag(null, "b");
1478 out.attribute(null, "packageName", it.next());
1479 out.endTag(null, "b");
1480 }
1481
Amith Yamasani742a6712011-05-04 14:49:28 -07001482 out.endTag(null, "gs");
1483
1484 out.endDocument();
1485 return true;
1486 } catch (IOException e) {
1487 Slog.w(TAG, "Failed to write state: " + e);
1488 return false;
1489 }
1490 }
1491
1492 void readStateFromFileLocked(FileInputStream stream) {
1493 boolean success = false;
Amith Yamasani742a6712011-05-04 14:49:28 -07001494 try {
1495 XmlPullParser parser = Xml.newPullParser();
1496 parser.setInput(stream, null);
1497
1498 int type;
1499 int providerIndex = 0;
1500 HashMap<Integer, Provider> loadedProviders = new HashMap<Integer, Provider>();
1501 do {
1502 type = parser.next();
1503 if (type == XmlPullParser.START_TAG) {
1504 String tag = parser.getName();
1505 if ("p".equals(tag)) {
1506 // TODO: do we need to check that this package has the same signature
1507 // as before?
1508 String pkg = parser.getAttributeValue(null, "pkg");
1509 String cl = parser.getAttributeValue(null, "cl");
1510
1511 final PackageManager packageManager = mContext.getPackageManager();
1512 try {
1513 packageManager.getReceiverInfo(new ComponentName(pkg, cl), 0);
1514 } catch (PackageManager.NameNotFoundException e) {
1515 String[] pkgs = packageManager
1516 .currentToCanonicalPackageNames(new String[] { pkg });
1517 pkg = pkgs[0];
1518 }
1519
1520 Provider p = lookupProviderLocked(new ComponentName(pkg, cl));
1521 if (p == null && mSafeMode) {
1522 // if we're in safe mode, make a temporary one
1523 p = new Provider();
1524 p.info = new AppWidgetProviderInfo();
1525 p.info.provider = new ComponentName(pkg, cl);
1526 p.zombie = true;
1527 mInstalledProviders.add(p);
1528 }
1529 if (p != null) {
1530 // if it wasn't uninstalled or something
1531 loadedProviders.put(providerIndex, p);
1532 }
1533 providerIndex++;
1534 } else if ("h".equals(tag)) {
1535 Host host = new Host();
1536
1537 // TODO: do we need to check that this package has the same signature
1538 // as before?
1539 host.packageName = parser.getAttributeValue(null, "pkg");
1540 try {
1541 host.uid = getUidForPackage(host.packageName);
1542 } catch (PackageManager.NameNotFoundException ex) {
1543 host.zombie = true;
1544 }
1545 if (!host.zombie || mSafeMode) {
1546 // In safe mode, we don't discard the hosts we don't recognize
1547 // so that they're not pruned from our list. Otherwise, we do.
1548 host.hostId = Integer
1549 .parseInt(parser.getAttributeValue(null, "id"), 16);
1550 mHosts.add(host);
1551 }
Michael Jurka61a5b012012-04-13 10:39:45 -07001552 } else if ("b".equals(tag)) {
1553 String packageName = parser.getAttributeValue(null, "packageName");
1554 if (packageName != null) {
1555 mPackagesWithBindWidgetPermission.add(packageName);
1556 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001557 } else if ("g".equals(tag)) {
1558 AppWidgetId id = new AppWidgetId();
1559 id.appWidgetId = Integer.parseInt(parser.getAttributeValue(null, "id"), 16);
1560 if (id.appWidgetId >= mNextAppWidgetId) {
1561 mNextAppWidgetId = id.appWidgetId + 1;
1562 }
1563
1564 String providerString = parser.getAttributeValue(null, "p");
1565 if (providerString != null) {
1566 // there's no provider if it hasn't been bound yet.
1567 // maybe we don't have to save this, but it brings the system
1568 // to the state it was in.
1569 int pIndex = Integer.parseInt(providerString, 16);
1570 id.provider = loadedProviders.get(pIndex);
1571 if (false) {
1572 Slog.d(TAG, "bound appWidgetId=" + id.appWidgetId + " to provider "
1573 + pIndex + " which is " + id.provider);
1574 }
1575 if (id.provider == null) {
1576 // This provider is gone. We just let the host figure out
1577 // that this happened when it fails to load it.
1578 continue;
1579 }
1580 }
1581
1582 int hIndex = Integer.parseInt(parser.getAttributeValue(null, "h"), 16);
1583 id.host = mHosts.get(hIndex);
1584 if (id.host == null) {
1585 // This host is gone.
1586 continue;
1587 }
1588
1589 if (id.provider != null) {
1590 id.provider.instances.add(id);
1591 }
1592 id.host.instances.add(id);
1593 mAppWidgetIds.add(id);
1594 }
1595 }
1596 } while (type != XmlPullParser.END_DOCUMENT);
1597 success = true;
1598 } catch (NullPointerException e) {
1599 Slog.w(TAG, "failed parsing " + e);
1600 } catch (NumberFormatException e) {
1601 Slog.w(TAG, "failed parsing " + e);
1602 } catch (XmlPullParserException e) {
1603 Slog.w(TAG, "failed parsing " + e);
1604 } catch (IOException e) {
1605 Slog.w(TAG, "failed parsing " + e);
1606 } catch (IndexOutOfBoundsException e) {
1607 Slog.w(TAG, "failed parsing " + e);
1608 }
1609
1610 if (success) {
1611 // delete any hosts that didn't manage to get connected (should happen)
1612 // if it matters, they'll be reconnected.
1613 for (int i = mHosts.size() - 1; i >= 0; i--) {
1614 pruneHostLocked(mHosts.get(i));
1615 }
1616 } else {
1617 // failed reading, clean up
1618 Slog.w(TAG, "Failed to read state, clearing widgets and hosts.");
1619
1620 mAppWidgetIds.clear();
1621 mHosts.clear();
1622 final int N = mInstalledProviders.size();
1623 for (int i = 0; i < N; i++) {
1624 mInstalledProviders.get(i).instances.clear();
1625 }
1626 }
1627 }
1628
Amith Yamasani13593602012-03-22 16:16:17 -07001629 static File getSettingsFile(int userId) {
1630 return new File("/data/system/users/" + userId + "/" + SETTINGS_FILENAME);
1631 }
1632
Amith Yamasani742a6712011-05-04 14:49:28 -07001633 AtomicFile savedStateFile() {
Amith Yamasani67cf7d32012-02-16 14:31:23 -08001634 File dir = new File("/data/system/users/" + mUserId);
Amith Yamasani13593602012-03-22 16:16:17 -07001635 File settingsFile = getSettingsFile(mUserId);
Amith Yamasanie0eb39b2012-05-01 13:48:48 -07001636 if (!settingsFile.exists() && mUserId == 0) {
1637 if (!dir.exists()) {
1638 dir.mkdirs();
Amith Yamasani742a6712011-05-04 14:49:28 -07001639 }
Amith Yamasanie0eb39b2012-05-01 13:48:48 -07001640 // Migrate old data
1641 File oldFile = new File("/data/system/" + SETTINGS_FILENAME);
1642 // Method doesn't throw an exception on failure. Ignore any errors
1643 // in moving the file (like non-existence)
1644 oldFile.renameTo(settingsFile);
Amith Yamasani742a6712011-05-04 14:49:28 -07001645 }
1646 return new AtomicFile(settingsFile);
1647 }
1648
Amith Yamasani13593602012-03-22 16:16:17 -07001649 void onUserRemoved() {
1650 // prune the ones we don't want to keep
1651 int N = mInstalledProviders.size();
1652 for (int i = N - 1; i >= 0; i--) {
1653 Provider p = mInstalledProviders.get(i);
1654 cancelBroadcasts(p);
1655 }
1656 getSettingsFile(mUserId).delete();
1657 }
1658
Winson Chung7fbd2842012-06-13 10:35:51 -07001659 boolean addProvidersForPackageLocked(String pkgName) {
1660 boolean providersAdded = false;
Amith Yamasani742a6712011-05-04 14:49:28 -07001661 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
1662 intent.setPackage(pkgName);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001663 List<ResolveInfo> broadcastReceivers;
1664 try {
1665 broadcastReceivers = mPm.queryIntentReceivers(intent,
1666 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
1667 PackageManager.GET_META_DATA, mUserId);
1668 } catch (RemoteException re) {
1669 // Shouldn't happen, local call
Winson Chung7fbd2842012-06-13 10:35:51 -07001670 return false;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001671 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001672 final int N = broadcastReceivers == null ? 0 : broadcastReceivers.size();
1673 for (int i = 0; i < N; i++) {
1674 ResolveInfo ri = broadcastReceivers.get(i);
1675 ActivityInfo ai = ri.activityInfo;
1676 if ((ai.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
1677 continue;
1678 }
1679 if (pkgName.equals(ai.packageName)) {
1680 addProviderLocked(ri);
Winson Chung7fbd2842012-06-13 10:35:51 -07001681 providersAdded = true;
Amith Yamasani742a6712011-05-04 14:49:28 -07001682 }
1683 }
Winson Chung7fbd2842012-06-13 10:35:51 -07001684
1685 return providersAdded;
Amith Yamasani742a6712011-05-04 14:49:28 -07001686 }
1687
Winson Chunga3195052012-06-25 10:02:10 -07001688 /**
1689 * Updates all providers with the specified package names, and records any providers that were
1690 * pruned.
1691 *
1692 * @return whether any providers were updated
1693 */
1694 boolean updateProvidersForPackageLocked(String pkgName, Set<ComponentName> removedProviders) {
Winson Chung7fbd2842012-06-13 10:35:51 -07001695 boolean providersUpdated = false;
Amith Yamasani742a6712011-05-04 14:49:28 -07001696 HashSet<String> keep = new HashSet<String>();
1697 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
1698 intent.setPackage(pkgName);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001699 List<ResolveInfo> broadcastReceivers;
1700 try {
1701 broadcastReceivers = mPm.queryIntentReceivers(intent,
1702 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
1703 PackageManager.GET_META_DATA, mUserId);
1704 } catch (RemoteException re) {
1705 // Shouldn't happen, local call
Winson Chung7fbd2842012-06-13 10:35:51 -07001706 return false;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001707 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001708
1709 // add the missing ones and collect which ones to keep
1710 int N = broadcastReceivers == null ? 0 : broadcastReceivers.size();
1711 for (int i = 0; i < N; i++) {
1712 ResolveInfo ri = broadcastReceivers.get(i);
1713 ActivityInfo ai = ri.activityInfo;
1714 if ((ai.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
1715 continue;
1716 }
1717 if (pkgName.equals(ai.packageName)) {
1718 ComponentName component = new ComponentName(ai.packageName, ai.name);
1719 Provider p = lookupProviderLocked(component);
1720 if (p == null) {
1721 if (addProviderLocked(ri)) {
1722 keep.add(ai.name);
Winson Chung7fbd2842012-06-13 10:35:51 -07001723 providersUpdated = true;
Amith Yamasani742a6712011-05-04 14:49:28 -07001724 }
1725 } else {
1726 Provider parsed = parseProviderInfoXml(component, ri);
1727 if (parsed != null) {
1728 keep.add(ai.name);
1729 // Use the new AppWidgetProviderInfo.
1730 p.info = parsed.info;
1731 // If it's enabled
1732 final int M = p.instances.size();
1733 if (M > 0) {
1734 int[] appWidgetIds = getAppWidgetIds(p);
1735 // Reschedule for the new updatePeriodMillis (don't worry about handling
1736 // it specially if updatePeriodMillis didn't change because we just sent
1737 // an update, and the next one will be updatePeriodMillis from now).
1738 cancelBroadcasts(p);
1739 registerForBroadcastsLocked(p, appWidgetIds);
1740 // If it's currently showing, call back with the new
1741 // AppWidgetProviderInfo.
1742 for (int j = 0; j < M; j++) {
1743 AppWidgetId id = p.instances.get(j);
1744 id.views = null;
1745 if (id.host != null && id.host.callbacks != null) {
1746 try {
1747 id.host.callbacks.providerChanged(id.appWidgetId, p.info);
1748 } catch (RemoteException ex) {
1749 // It failed; remove the callback. No need to prune because
1750 // we know that this host is still referenced by this
1751 // instance.
1752 id.host.callbacks = null;
1753 }
1754 }
1755 }
1756 // Now that we've told the host, push out an update.
1757 sendUpdateIntentLocked(p, appWidgetIds);
Winson Chung7fbd2842012-06-13 10:35:51 -07001758 providersUpdated = true;
Amith Yamasani742a6712011-05-04 14:49:28 -07001759 }
1760 }
1761 }
1762 }
1763 }
1764
1765 // prune the ones we don't want to keep
1766 N = mInstalledProviders.size();
1767 for (int i = N - 1; i >= 0; i--) {
1768 Provider p = mInstalledProviders.get(i);
1769 if (pkgName.equals(p.info.provider.getPackageName())
1770 && !keep.contains(p.info.provider.getClassName())) {
Winson Chunga3195052012-06-25 10:02:10 -07001771 if (removedProviders != null) {
1772 removedProviders.add(p.info.provider);
1773 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001774 removeProviderLocked(i, p);
Winson Chung7fbd2842012-06-13 10:35:51 -07001775 providersUpdated = true;
Amith Yamasani742a6712011-05-04 14:49:28 -07001776 }
1777 }
Winson Chung7fbd2842012-06-13 10:35:51 -07001778
1779 return providersUpdated;
Amith Yamasani742a6712011-05-04 14:49:28 -07001780 }
1781
Winson Chung7fbd2842012-06-13 10:35:51 -07001782 boolean removeProvidersForPackageLocked(String pkgName) {
1783 boolean providersRemoved = false;
Amith Yamasani742a6712011-05-04 14:49:28 -07001784 int N = mInstalledProviders.size();
1785 for (int i = N - 1; i >= 0; i--) {
1786 Provider p = mInstalledProviders.get(i);
1787 if (pkgName.equals(p.info.provider.getPackageName())) {
1788 removeProviderLocked(i, p);
Winson Chung7fbd2842012-06-13 10:35:51 -07001789 providersRemoved = true;
Amith Yamasani742a6712011-05-04 14:49:28 -07001790 }
1791 }
1792
1793 // Delete the hosts for this package too
1794 //
1795 // By now, we have removed any AppWidgets that were in any hosts here,
1796 // so we don't need to worry about sending DISABLE broadcasts to them.
1797 N = mHosts.size();
1798 for (int i = N - 1; i >= 0; i--) {
1799 Host host = mHosts.get(i);
1800 if (pkgName.equals(host.packageName)) {
1801 deleteHostLocked(host);
1802 }
1803 }
Winson Chung7fbd2842012-06-13 10:35:51 -07001804
1805 return providersRemoved;
1806 }
1807
1808 void notifyHostsForProvidersChangedLocked() {
1809 final int N = mHosts.size();
1810 for (int i = N - 1; i >= 0; i--) {
1811 Host host = mHosts.get(i);
1812 try {
1813 if (host.callbacks != null) {
1814 host.callbacks.providersChanged();
1815 }
1816 } catch (RemoteException ex) {
1817 // It failed; remove the callback. No need to prune because
1818 // we know that this host is still referenced by this
1819 // instance.
1820 host.callbacks = null;
1821 }
1822 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001823 }
1824}