ServiceRecord.java revision d0a2f86f357f346639a6648b4004266865c979b4
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.os.BatteryStatsImpl;
20import com.android.server.NotificationManagerService;
21
22import android.app.INotificationManager;
23import android.app.Notification;
24import android.app.NotificationManager;
25import android.content.ComponentName;
26import android.content.Intent;
27import android.content.pm.ApplicationInfo;
28import android.content.pm.ServiceInfo;
29import android.os.Binder;
30import android.os.IBinder;
31import android.os.RemoteException;
32import android.os.SystemClock;
33import android.util.Slog;
34
35import java.io.PrintWriter;
36import java.util.ArrayList;
37import java.util.HashMap;
38import java.util.Iterator;
39import java.util.List;
40
41/**
42 * A running application service.
43 */
44class ServiceRecord extends Binder {
45    final ActivityManagerService ams;
46    final BatteryStatsImpl.Uid.Pkg.Serv stats;
47    final ComponentName name; // service component.
48    final String shortName; // name.flattenToShortString().
49    final Intent.FilterComparison intent;
50                            // original intent used to find service.
51    final ServiceInfo serviceInfo;
52                            // all information about the service.
53    final ApplicationInfo appInfo;
54                            // information about service's app.
55    final String packageName; // the package implementing intent's component
56    final String processName; // process where this component wants to run
57    final String permission;// permission needed to access service
58    final String baseDir;   // where activity source (resources etc) located
59    final String resDir;   // where public activity source (public resources etc) located
60    final String dataDir;   // where activity data should go
61    final boolean exported; // from ServiceInfo.exported
62    final Runnable restarter; // used to schedule retries of starting the service
63    final long createTime;  // when this service was created
64    final HashMap<Intent.FilterComparison, IntentBindRecord> bindings
65            = new HashMap<Intent.FilterComparison, IntentBindRecord>();
66                            // All active bindings to the service.
67    final HashMap<IBinder, ConnectionRecord> connections
68            = new HashMap<IBinder, ConnectionRecord>();
69                            // IBinder -> ConnectionRecord of all bound clients
70
71    // Maximum number of delivery attempts before giving up.
72    static final int MAX_DELIVERY_COUNT = 3;
73
74    // Maximum number of times it can fail during execution before giving up.
75    static final int MAX_DONE_EXECUTING_COUNT = 6;
76
77    static class StartItem {
78        final int id;
79        final Intent intent;
80        long deliveredTime;
81        int deliveryCount;
82        int doneExecutingCount;
83
84        StartItem(int _id, Intent _intent) {
85            id = _id;
86            intent = _intent;
87        }
88    }
89    final ArrayList<StartItem> deliveredStarts = new ArrayList<StartItem>();
90                            // start() arguments which been delivered.
91    final ArrayList<StartItem> pendingStarts = new ArrayList<StartItem>();
92                            // start() arguments that haven't yet been delivered.
93
94    ProcessRecord app;      // where this service is running or null.
95    boolean isForeground;   // is service currently in foreground mode?
96    int foregroundId;       // Notification ID of last foreground req.
97    Notification foregroundNoti; // Notification record of foreground state.
98    long lastActivity;      // last time there was some activity on the service.
99    boolean startRequested; // someone explicitly called start?
100    boolean stopIfKilled;   // last onStart() said to stop if service killed?
101    boolean callStart;      // last onStart() has asked to alway be called on restart.
102    int lastStartId;        // identifier of most recent start request.
103    int executeNesting;     // number of outstanding operations keeping foreground.
104    long executingStart;    // start time of last execute request.
105    int crashCount;         // number of times proc has crashed with service running
106    int totalRestartCount;  // number of times we have had to restart.
107    int restartCount;       // number of restarts performed in a row.
108    long restartDelay;      // delay until next restart attempt.
109    long restartTime;       // time of last restart.
110    long nextRestartTime;   // time when restartDelay will expire.
111
112    String stringName;      // caching of toString
113
114    void dumpStartList(PrintWriter pw, String prefix, List<StartItem> list, long now) {
115        final int N = list.size();
116        for (int i=0; i<N; i++) {
117            StartItem si = list.get(i);
118            pw.print(prefix); pw.print("#"); pw.print(i);
119                    pw.print(" id="); pw.print(si.id);
120                    if (now != 0) pw.print(" dur="); pw.print(now-si.deliveredTime);
121                    if (si.deliveryCount != 0) {
122                        pw.print(" dc="); pw.print(si.deliveryCount);
123                    }
124                    if (si.doneExecutingCount != 0) {
125                        pw.print(" dxc="); pw.print(si.doneExecutingCount);
126                    }
127                    pw.print(" ");
128                    if (si.intent != null) pw.println(si.intent.toString());
129                    else pw.println("null");
130        }
131    }
132
133    void dump(PrintWriter pw, String prefix) {
134        pw.print(prefix); pw.print("intent={");
135                pw.print(intent.getIntent().toShortString(true, false));
136                pw.println('}');
137        pw.print(prefix); pw.print("packageName="); pw.println(packageName);
138        pw.print(prefix); pw.print("processName="); pw.println(processName);
139        if (permission != null) {
140            pw.print(prefix); pw.print("permission="); pw.println(permission);
141        }
142        long now = SystemClock.uptimeMillis();
143        pw.print(prefix); pw.print("baseDir="); pw.print(baseDir);
144                if (!resDir.equals(baseDir)) pw.print(" resDir="); pw.print(resDir);
145                pw.print(" dataDir="); pw.println(dataDir);
146        pw.print(prefix); pw.print("app="); pw.println(app);
147        if (isForeground || foregroundId != 0) {
148            pw.print(prefix); pw.print("isForeground="); pw.print(isForeground);
149                    pw.print(" foregroundId="); pw.print(foregroundId);
150                    pw.print(" foregroundNoti="); pw.println(foregroundNoti);
151        }
152        pw.print(prefix); pw.print("lastActivity="); pw.print(lastActivity-now);
153                pw.print(" executingStart="); pw.print(executingStart-now);
154                pw.print(" restartTime="); pw.println(restartTime);
155        if (startRequested || lastStartId != 0) {
156            pw.print(prefix); pw.print("startRequested="); pw.print(startRequested);
157                    pw.print(" stopIfKilled="); pw.print(stopIfKilled);
158                    pw.print(" callStart="); pw.print(callStart);
159                    pw.print(" lastStartId="); pw.println(lastStartId);
160        }
161        if (executeNesting != 0 || crashCount != 0 || restartCount != 0
162                || restartDelay != 0 || nextRestartTime != 0) {
163            pw.print(prefix); pw.print("executeNesting="); pw.print(executeNesting);
164                    pw.print(" restartCount="); pw.print(restartCount);
165                    pw.print(" restartDelay="); pw.print(restartDelay-now);
166                    pw.print(" nextRestartTime="); pw.print(nextRestartTime-now);
167                    pw.print(" crashCount="); pw.println(crashCount);
168        }
169        if (deliveredStarts.size() > 0) {
170            pw.print(prefix); pw.println("Delivered Starts:");
171            dumpStartList(pw, prefix, deliveredStarts, SystemClock.uptimeMillis());
172        }
173        if (pendingStarts.size() > 0) {
174            pw.print(prefix); pw.println("Pending Starts:");
175            dumpStartList(pw, prefix, pendingStarts, 0);
176        }
177        if (bindings.size() > 0) {
178            Iterator<IntentBindRecord> it = bindings.values().iterator();
179            pw.print(prefix); pw.println("Bindings:");
180            while (it.hasNext()) {
181                IntentBindRecord b = it.next();
182                pw.print(prefix); pw.print("* IntentBindRecord{");
183                        pw.print(Integer.toHexString(System.identityHashCode(b)));
184                        pw.println("}:");
185                b.dumpInService(pw, prefix + "  ");
186            }
187        }
188        if (connections.size() > 0) {
189            pw.print(prefix); pw.println("All Connections:");
190            Iterator<ConnectionRecord> it = connections.values().iterator();
191            while (it.hasNext()) {
192                ConnectionRecord c = it.next();
193                pw.print(prefix); pw.print("  "); pw.println(c);
194            }
195        }
196    }
197
198    ServiceRecord(ActivityManagerService ams,
199            BatteryStatsImpl.Uid.Pkg.Serv servStats, ComponentName name,
200            Intent.FilterComparison intent, ServiceInfo sInfo, Runnable restarter) {
201        this.ams = ams;
202        this.stats = servStats;
203        this.name = name;
204        shortName = name.flattenToShortString();
205        this.intent = intent;
206        serviceInfo = sInfo;
207        appInfo = sInfo.applicationInfo;
208        packageName = sInfo.applicationInfo.packageName;
209        processName = sInfo.processName;
210        permission = sInfo.permission;
211        baseDir = sInfo.applicationInfo.sourceDir;
212        resDir = sInfo.applicationInfo.publicSourceDir;
213        dataDir = sInfo.applicationInfo.dataDir;
214        exported = sInfo.exported;
215        this.restarter = restarter;
216        createTime = lastActivity = SystemClock.uptimeMillis();
217    }
218
219    public AppBindRecord retrieveAppBindingLocked(Intent intent,
220            ProcessRecord app) {
221        Intent.FilterComparison filter = new Intent.FilterComparison(intent);
222        IntentBindRecord i = bindings.get(filter);
223        if (i == null) {
224            i = new IntentBindRecord(this, filter);
225            bindings.put(filter, i);
226        }
227        AppBindRecord a = i.apps.get(app);
228        if (a != null) {
229            return a;
230        }
231        a = new AppBindRecord(this, i, app);
232        i.apps.put(app, a);
233        return a;
234    }
235
236    public void resetRestartCounter() {
237        restartCount = 0;
238        restartDelay = 0;
239        restartTime = 0;
240    }
241
242    public StartItem findDeliveredStart(int id, boolean remove) {
243        final int N = deliveredStarts.size();
244        for (int i=0; i<N; i++) {
245            StartItem si = deliveredStarts.get(i);
246            if (si.id == id) {
247                if (remove) deliveredStarts.remove(i);
248                return si;
249            }
250        }
251
252        return null;
253    }
254
255    public void postNotification() {
256        final int appUid = appInfo.uid;
257        final int appPid = app.pid;
258        if (foregroundId != 0 && foregroundNoti != null) {
259            // Do asynchronous communication with notification manager to
260            // avoid deadlocks.
261            final String localPackageName = packageName;
262            final int localForegroundId = foregroundId;
263            final Notification localForegroundNoti = foregroundNoti;
264            ams.mHandler.post(new Runnable() {
265                public void run() {
266                    NotificationManagerService nm =
267                            (NotificationManagerService) NotificationManager.getService();
268                    if (nm == null) {
269                        return;
270                    }
271                    try {
272                        int[] outId = new int[1];
273                        nm.enqueueNotificationInternal(localPackageName, appUid, appPid,
274                                null, localForegroundId, localForegroundNoti, outId);
275                    } catch (RuntimeException e) {
276                        Slog.w(ActivityManagerService.TAG,
277                                "Error showing notification for service", e);
278                        // If it gave us a garbage notification, it doesn't
279                        // get to be foreground.
280                        ams.setServiceForeground(name, ServiceRecord.this,
281                                localForegroundId, null, true);
282                    }
283                }
284            });
285        }
286    }
287
288    public void cancelNotification() {
289        if (foregroundId != 0) {
290            // Do asynchronous communication with notification manager to
291            // avoid deadlocks.
292            final String localPackageName = packageName;
293            final int localForegroundId = foregroundId;
294            ams.mHandler.post(new Runnable() {
295                public void run() {
296                    INotificationManager inm = NotificationManager.getService();
297                    if (inm == null) {
298                        return;
299                    }
300                    try {
301                        inm.cancelNotification(localPackageName, localForegroundId);
302                    } catch (RuntimeException e) {
303                        Slog.w(ActivityManagerService.TAG,
304                                "Error canceling notification for service", e);
305                    } catch (RemoteException e) {
306                    }
307                }
308            });
309        }
310    }
311
312    public String toString() {
313        if (stringName != null) {
314            return stringName;
315        }
316        StringBuilder sb = new StringBuilder(128);
317        sb.append("ServiceRecord{")
318            .append(Integer.toHexString(System.identityHashCode(this)))
319            .append(' ').append(shortName).append('}');
320        return stringName = sb.toString();
321    }
322}
323