ServiceRecord.java revision 846318a3250fa95f47a9decfbffb05a31dbd0006
1/*
2 * Copyright (C) 2006 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.am;
18
19import com.android.internal.app.ProcessStats;
20import com.android.internal.os.BatteryStatsImpl;
21import com.android.server.LocalServices;
22import com.android.server.notification.NotificationManagerInternal;
23
24import android.app.INotificationManager;
25import android.app.Notification;
26import android.app.NotificationManager;
27import android.app.PendingIntent;
28import android.content.ComponentName;
29import android.content.Context;
30import android.content.Intent;
31import android.content.pm.ApplicationInfo;
32import android.content.pm.PackageManager;
33import android.content.pm.ServiceInfo;
34import android.net.Uri;
35import android.os.Binder;
36import android.os.IBinder;
37import android.os.RemoteException;
38import android.os.SystemClock;
39import android.os.UserHandle;
40import android.provider.Settings;
41import android.util.ArrayMap;
42import android.util.Slog;
43import android.util.TimeUtils;
44
45import java.io.PrintWriter;
46import java.util.ArrayList;
47import java.util.List;
48
49/**
50 * A running application service.
51 */
52final class ServiceRecord extends Binder {
53    // Maximum number of delivery attempts before giving up.
54    static final int MAX_DELIVERY_COUNT = 3;
55
56    // Maximum number of times it can fail during execution before giving up.
57    static final int MAX_DONE_EXECUTING_COUNT = 6;
58
59    final ActivityManagerService ams;
60    final BatteryStatsImpl.Uid.Pkg.Serv stats;
61    final ComponentName name; // service component.
62    final String shortName; // name.flattenToShortString().
63    final Intent.FilterComparison intent;
64                            // original intent used to find service.
65    final ServiceInfo serviceInfo;
66                            // all information about the service.
67    final ApplicationInfo appInfo;
68                            // information about service's app.
69    final int userId;       // user that this service is running as
70    final String packageName; // the package implementing intent's component
71    final String processName; // process where this component wants to run
72    final String permission;// permission needed to access service
73    final String baseDir;   // where activity source (resources etc) located
74    final String resDir;   // where public activity source (public resources etc) located
75    final String dataDir;   // where activity data should go
76    final boolean exported; // from ServiceInfo.exported
77    final Runnable restarter; // used to schedule retries of starting the service
78    final long createTime;  // when this service was created
79    final ArrayMap<Intent.FilterComparison, IntentBindRecord> bindings
80            = new ArrayMap<Intent.FilterComparison, IntentBindRecord>();
81                            // All active bindings to the service.
82    final ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections
83            = new ArrayMap<IBinder, ArrayList<ConnectionRecord>>();
84                            // IBinder -> ConnectionRecord of all bound clients
85
86    ProcessRecord app;      // where this service is running or null.
87    ProcessRecord isolatedProc; // keep track of isolated process, if requested
88    ProcessStats.ServiceState tracker; // tracking service execution, may be null
89    ProcessStats.ServiceState restartTracker; // tracking service restart
90    boolean delayed;        // are we waiting to start this service in the background?
91    boolean isForeground;   // is service currently in foreground mode?
92    int foregroundId;       // Notification ID of last foreground req.
93    Notification foregroundNoti; // Notification record of foreground state.
94    long lastActivity;      // last time there was some activity on the service.
95    long startingBgTimeout;  // time at which we scheduled this for a delayed start.
96    boolean startRequested; // someone explicitly called start?
97    boolean delayedStop;    // service has been stopped but is in a delayed start?
98    boolean stopIfKilled;   // last onStart() said to stop if service killed?
99    boolean callStart;      // last onStart() has asked to alway be called on restart.
100    int executeNesting;     // number of outstanding operations keeping foreground.
101    boolean executeFg;      // should we be executing in the foreground?
102    long executingStart;    // start time of last execute request.
103    boolean createdFromFg;  // was this service last created due to a foreground process call?
104    int crashCount;         // number of times proc has crashed with service running
105    int totalRestartCount;  // number of times we have had to restart.
106    int restartCount;       // number of restarts performed in a row.
107    long restartDelay;      // delay until next restart attempt.
108    long restartTime;       // time of last restart.
109    long nextRestartTime;   // time when restartDelay will expire.
110
111    String stringName;      // caching of toString
112
113    private int lastStartId;    // identifier of most recent start request.
114
115    static class StartItem {
116        final ServiceRecord sr;
117        final boolean taskRemoved;
118        final int id;
119        final Intent intent;
120        final ActivityManagerService.NeededUriGrants neededGrants;
121        long deliveredTime;
122        int deliveryCount;
123        int doneExecutingCount;
124        UriPermissionOwner uriPermissions;
125
126        String stringName;      // caching of toString
127
128        StartItem(ServiceRecord _sr, boolean _taskRemoved, int _id, Intent _intent,
129                ActivityManagerService.NeededUriGrants _neededGrants) {
130            sr = _sr;
131            taskRemoved = _taskRemoved;
132            id = _id;
133            intent = _intent;
134            neededGrants = _neededGrants;
135        }
136
137        UriPermissionOwner getUriPermissionsLocked() {
138            if (uriPermissions == null) {
139                uriPermissions = new UriPermissionOwner(sr.ams, this);
140            }
141            return uriPermissions;
142        }
143
144        void removeUriPermissionsLocked() {
145            if (uriPermissions != null) {
146                uriPermissions.removeUriPermissionsLocked();
147                uriPermissions = null;
148            }
149        }
150
151        public String toString() {
152            if (stringName != null) {
153                return stringName;
154            }
155            StringBuilder sb = new StringBuilder(128);
156            sb.append("ServiceRecord{")
157                .append(Integer.toHexString(System.identityHashCode(sr)))
158                .append(' ').append(sr.shortName)
159                .append(" StartItem ")
160                .append(Integer.toHexString(System.identityHashCode(this)))
161                .append(" id=").append(id).append('}');
162            return stringName = sb.toString();
163        }
164    }
165
166    final ArrayList<StartItem> deliveredStarts = new ArrayList<StartItem>();
167                            // start() arguments which been delivered.
168    final ArrayList<StartItem> pendingStarts = new ArrayList<StartItem>();
169                            // start() arguments that haven't yet been delivered.
170
171    void dumpStartList(PrintWriter pw, String prefix, List<StartItem> list, long now) {
172        final int N = list.size();
173        for (int i=0; i<N; i++) {
174            StartItem si = list.get(i);
175            pw.print(prefix); pw.print("#"); pw.print(i);
176                    pw.print(" id="); pw.print(si.id);
177                    if (now != 0) {
178                        pw.print(" dur=");
179                        TimeUtils.formatDuration(si.deliveredTime, now, pw);
180                    }
181                    if (si.deliveryCount != 0) {
182                        pw.print(" dc="); pw.print(si.deliveryCount);
183                    }
184                    if (si.doneExecutingCount != 0) {
185                        pw.print(" dxc="); pw.print(si.doneExecutingCount);
186                    }
187                    pw.println("");
188            pw.print(prefix); pw.print("  intent=");
189                    if (si.intent != null) pw.println(si.intent.toString());
190                    else pw.println("null");
191            if (si.neededGrants != null) {
192                pw.print(prefix); pw.print("  neededGrants=");
193                        pw.println(si.neededGrants);
194            }
195            if (si.uriPermissions != null) {
196                si.uriPermissions.dump(pw, prefix);
197            }
198        }
199    }
200
201    void dump(PrintWriter pw, String prefix) {
202        pw.print(prefix); pw.print("intent={");
203                pw.print(intent.getIntent().toShortString(false, true, false, true));
204                pw.println('}');
205        pw.print(prefix); pw.print("packageName="); pw.println(packageName);
206        pw.print(prefix); pw.print("processName="); pw.println(processName);
207        if (permission != null) {
208            pw.print(prefix); pw.print("permission="); pw.println(permission);
209        }
210        long now = SystemClock.uptimeMillis();
211        long nowReal = SystemClock.elapsedRealtime();
212        pw.print(prefix); pw.print("baseDir="); pw.println(baseDir);
213        if (!resDir.equals(baseDir)) {
214            pw.print(prefix); pw.print("resDir="); pw.println(resDir);
215        }
216        pw.print(prefix); pw.print("dataDir="); pw.println(dataDir);
217        pw.print(prefix); pw.print("app="); pw.println(app);
218        if (isolatedProc != null) {
219            pw.print(prefix); pw.print("isolatedProc="); pw.println(isolatedProc);
220        }
221        if (delayed) {
222            pw.print(prefix); pw.print("delayed="); pw.println(delayed);
223        }
224        if (isForeground || foregroundId != 0) {
225            pw.print(prefix); pw.print("isForeground="); pw.print(isForeground);
226                    pw.print(" foregroundId="); pw.print(foregroundId);
227                    pw.print(" foregroundNoti="); pw.println(foregroundNoti);
228        }
229        pw.print(prefix); pw.print("createTime=");
230                TimeUtils.formatDuration(createTime, nowReal, pw);
231                pw.print(" startingBgTimeout=");
232                TimeUtils.formatDuration(startingBgTimeout, now, pw);
233                pw.println();
234        pw.print(prefix); pw.print("lastActivity=");
235                TimeUtils.formatDuration(lastActivity, now, pw);
236                pw.print(" restartTime=");
237                TimeUtils.formatDuration(restartTime, now, pw);
238                pw.print(" createdFromFg="); pw.println(createdFromFg);
239        if (startRequested || delayedStop || lastStartId != 0) {
240            pw.print(prefix); pw.print("startRequested="); pw.print(startRequested);
241                    pw.print(" delayedStop="); pw.print(delayedStop);
242                    pw.print(" stopIfKilled="); pw.print(stopIfKilled);
243                    pw.print(" callStart="); pw.print(callStart);
244                    pw.print(" lastStartId="); pw.println(lastStartId);
245        }
246        if (executeNesting != 0) {
247            pw.print(prefix); pw.print("executeNesting="); pw.print(executeNesting);
248                    pw.print(" executeFg="); pw.print(executeFg);
249                    pw.print(" executingStart=");
250                    TimeUtils.formatDuration(executingStart, now, pw);
251                    pw.println();
252        }
253        if (crashCount != 0 || restartCount != 0
254                || restartDelay != 0 || nextRestartTime != 0) {
255            pw.print(prefix); pw.print("restartCount="); pw.print(restartCount);
256                    pw.print(" restartDelay=");
257                    TimeUtils.formatDuration(restartDelay, now, pw);
258                    pw.print(" nextRestartTime=");
259                    TimeUtils.formatDuration(nextRestartTime, now, pw);
260                    pw.print(" crashCount="); pw.println(crashCount);
261        }
262        if (deliveredStarts.size() > 0) {
263            pw.print(prefix); pw.println("Delivered Starts:");
264            dumpStartList(pw, prefix, deliveredStarts, now);
265        }
266        if (pendingStarts.size() > 0) {
267            pw.print(prefix); pw.println("Pending Starts:");
268            dumpStartList(pw, prefix, pendingStarts, 0);
269        }
270        if (bindings.size() > 0) {
271            pw.print(prefix); pw.println("Bindings:");
272            for (int i=0; i<bindings.size(); i++) {
273                IntentBindRecord b = bindings.valueAt(i);
274                pw.print(prefix); pw.print("* IntentBindRecord{");
275                        pw.print(Integer.toHexString(System.identityHashCode(b)));
276                        if ((b.collectFlags()&Context.BIND_AUTO_CREATE) != 0) {
277                            pw.append(" CREATE");
278                        }
279                        pw.println("}:");
280                b.dumpInService(pw, prefix + "  ");
281            }
282        }
283        if (connections.size() > 0) {
284            pw.print(prefix); pw.println("All Connections:");
285            for (int conni=0; conni<connections.size(); conni++) {
286                ArrayList<ConnectionRecord> c = connections.valueAt(conni);
287                for (int i=0; i<c.size(); i++) {
288                    pw.print(prefix); pw.print("  "); pw.println(c.get(i));
289                }
290            }
291        }
292    }
293
294    ServiceRecord(ActivityManagerService ams,
295            BatteryStatsImpl.Uid.Pkg.Serv servStats, ComponentName name,
296            Intent.FilterComparison intent, ServiceInfo sInfo, boolean callerIsFg,
297            Runnable restarter) {
298        this.ams = ams;
299        this.stats = servStats;
300        this.name = name;
301        shortName = name.flattenToShortString();
302        this.intent = intent;
303        serviceInfo = sInfo;
304        appInfo = sInfo.applicationInfo;
305        packageName = sInfo.applicationInfo.packageName;
306        processName = sInfo.processName;
307        permission = sInfo.permission;
308        baseDir = sInfo.applicationInfo.sourceDir;
309        resDir = sInfo.applicationInfo.publicSourceDir;
310        dataDir = sInfo.applicationInfo.dataDir;
311        exported = sInfo.exported;
312        this.restarter = restarter;
313        createTime = SystemClock.elapsedRealtime();
314        lastActivity = SystemClock.uptimeMillis();
315        userId = UserHandle.getUserId(appInfo.uid);
316        createdFromFg = callerIsFg;
317    }
318
319    public ProcessStats.ServiceState getTracker() {
320        if (tracker != null) {
321            return tracker;
322        }
323        if ((serviceInfo.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) == 0) {
324            tracker = ams.mProcessStats.getServiceStateLocked(serviceInfo.packageName,
325                    serviceInfo.applicationInfo.uid, serviceInfo.applicationInfo.versionCode,
326                    serviceInfo.processName, serviceInfo.name);
327            tracker.applyNewOwner(this);
328        }
329        return tracker;
330    }
331
332    public void forceClearTracker() {
333        if (tracker != null) {
334            tracker.clearCurrentOwner(this, true);
335            tracker = null;
336        }
337    }
338
339    public void makeRestarting(int memFactor, long now) {
340        if (restartTracker == null) {
341            if ((serviceInfo.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) == 0) {
342                restartTracker = ams.mProcessStats.getServiceStateLocked(serviceInfo.packageName,
343                        serviceInfo.applicationInfo.uid, serviceInfo.applicationInfo.versionCode,
344                        serviceInfo.processName, serviceInfo.name);
345            }
346            if (restartTracker == null) {
347                return;
348            }
349        }
350        restartTracker.setRestarting(true, memFactor, now);
351    }
352
353    public AppBindRecord retrieveAppBindingLocked(Intent intent,
354            ProcessRecord app) {
355        Intent.FilterComparison filter = new Intent.FilterComparison(intent);
356        IntentBindRecord i = bindings.get(filter);
357        if (i == null) {
358            i = new IntentBindRecord(this, filter);
359            bindings.put(filter, i);
360        }
361        AppBindRecord a = i.apps.get(app);
362        if (a != null) {
363            return a;
364        }
365        a = new AppBindRecord(this, i, app);
366        i.apps.put(app, a);
367        return a;
368    }
369
370    public boolean hasAutoCreateConnections() {
371        // XXX should probably keep a count of the number of auto-create
372        // connections directly in the service.
373        for (int conni=connections.size()-1; conni>=0; conni--) {
374            ArrayList<ConnectionRecord> cr = connections.valueAt(conni);
375            for (int i=0; i<cr.size(); i++) {
376                if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
377                    return true;
378                }
379            }
380        }
381        return false;
382    }
383
384    public void resetRestartCounter() {
385        restartCount = 0;
386        restartDelay = 0;
387        restartTime = 0;
388    }
389
390    public StartItem findDeliveredStart(int id, boolean remove) {
391        final int N = deliveredStarts.size();
392        for (int i=0; i<N; i++) {
393            StartItem si = deliveredStarts.get(i);
394            if (si.id == id) {
395                if (remove) deliveredStarts.remove(i);
396                return si;
397            }
398        }
399
400        return null;
401    }
402
403    public int getLastStartId() {
404        return lastStartId;
405    }
406
407    public int makeNextStartId() {
408        lastStartId++;
409        if (lastStartId < 1) {
410            lastStartId = 1;
411        }
412        return lastStartId;
413    }
414
415    public void postNotification() {
416        final int appUid = appInfo.uid;
417        final int appPid = app.pid;
418        if (foregroundId != 0 && foregroundNoti != null) {
419            // Do asynchronous communication with notification manager to
420            // avoid deadlocks.
421            final String localPackageName = packageName;
422            final int localForegroundId = foregroundId;
423            final Notification localForegroundNoti = foregroundNoti;
424            ams.mHandler.post(new Runnable() {
425                public void run() {
426                    NotificationManagerInternal nm = LocalServices.getService(
427                            NotificationManagerInternal.class);
428                    if (nm == null) {
429                        return;
430                    }
431                    try {
432                        if (localForegroundNoti.icon == 0) {
433                            // It is not correct for the caller to supply a notification
434                            // icon, but this used to be able to slip through, so for
435                            // those dirty apps give it the app's icon.
436                            localForegroundNoti.icon = appInfo.icon;
437
438                            // Do not allow apps to present a sneaky invisible content view either.
439                            localForegroundNoti.contentView = null;
440                            localForegroundNoti.bigContentView = null;
441                            CharSequence appName = appInfo.loadLabel(
442                                    ams.mContext.getPackageManager());
443                            if (appName == null) {
444                                appName = appInfo.packageName;
445                            }
446                            Context ctx = null;
447                            try {
448                                ctx = ams.mContext.createPackageContext(
449                                        appInfo.packageName, 0);
450                                Intent runningIntent = new Intent(
451                                        Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
452                                runningIntent.setData(Uri.fromParts("package",
453                                        appInfo.packageName, null));
454                                PendingIntent pi = PendingIntent.getActivity(ams.mContext, 0,
455                                        runningIntent, PendingIntent.FLAG_UPDATE_CURRENT);
456                                localForegroundNoti.setLatestEventInfo(ctx,
457                                        ams.mContext.getString(
458                                                com.android.internal.R.string
459                                                        .app_running_notification_title,
460                                                appName),
461                                        ams.mContext.getString(
462                                                com.android.internal.R.string
463                                                        .app_running_notification_text,
464                                                appName),
465                                        pi);
466                            } catch (PackageManager.NameNotFoundException e) {
467                                localForegroundNoti.icon = 0;
468                            }
469                        }
470                        if (localForegroundNoti.icon == 0) {
471                            // Notifications whose icon is 0 are defined to not show
472                            // a notification, silently ignoring it.  We don't want to
473                            // just ignore it, we want to prevent the service from
474                            // being foreground.
475                            throw new RuntimeException("icon must be non-zero");
476                        }
477                        int[] outId = new int[1];
478                        nm.enqueueNotification(localPackageName, localPackageName,
479                                appUid, appPid, null, localForegroundId, localForegroundNoti,
480                                outId, userId);
481                    } catch (RuntimeException e) {
482                        Slog.w(ActivityManagerService.TAG,
483                                "Error showing notification for service", e);
484                        // If it gave us a garbage notification, it doesn't
485                        // get to be foreground.
486                        ams.setServiceForeground(name, ServiceRecord.this,
487                                0, null, true);
488                        ams.crashApplication(appUid, appPid, localPackageName,
489                                "Bad notification for startForeground: " + e);
490                    }
491                }
492            });
493        }
494    }
495
496    public void cancelNotification() {
497        if (foregroundId != 0) {
498            // Do asynchronous communication with notification manager to
499            // avoid deadlocks.
500            final String localPackageName = packageName;
501            final int localForegroundId = foregroundId;
502            ams.mHandler.post(new Runnable() {
503                public void run() {
504                    INotificationManager inm = NotificationManager.getService();
505                    if (inm == null) {
506                        return;
507                    }
508                    try {
509                        inm.cancelNotificationWithTag(localPackageName, null,
510                                localForegroundId, userId);
511                    } catch (RuntimeException e) {
512                        Slog.w(ActivityManagerService.TAG,
513                                "Error canceling notification for service", e);
514                    } catch (RemoteException e) {
515                    }
516                }
517            });
518        }
519    }
520
521    public void clearDeliveredStartsLocked() {
522        for (int i=deliveredStarts.size()-1; i>=0; i--) {
523            deliveredStarts.get(i).removeUriPermissionsLocked();
524        }
525        deliveredStarts.clear();
526    }
527
528    public String toString() {
529        if (stringName != null) {
530            return stringName;
531        }
532        StringBuilder sb = new StringBuilder(128);
533        sb.append("ServiceRecord{")
534            .append(Integer.toHexString(System.identityHashCode(this)))
535            .append(" u").append(userId)
536            .append(' ').append(shortName).append('}');
537        return stringName = sb.toString();
538    }
539}
540