ServiceRecord.java revision 9adb9c3b10991ef315c270993f4155709c8a232d
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("createTime=");
153                pw.print(createTime-SystemClock.elapsedRealtime());
154                pw.print(" lastActivity="); pw.print(lastActivity-now);
155                pw.print(" executingStart="); pw.print(executingStart-now);
156                pw.print(" restartTime="); pw.println(restartTime);
157        if (startRequested || lastStartId != 0) {
158            pw.print(prefix); pw.print("startRequested="); pw.print(startRequested);
159                    pw.print(" stopIfKilled="); pw.print(stopIfKilled);
160                    pw.print(" callStart="); pw.print(callStart);
161                    pw.print(" lastStartId="); pw.println(lastStartId);
162        }
163        if (executeNesting != 0 || crashCount != 0 || restartCount != 0
164                || restartDelay != 0 || nextRestartTime != 0) {
165            pw.print(prefix); pw.print("executeNesting="); pw.print(executeNesting);
166                    pw.print(" restartCount="); pw.print(restartCount);
167                    pw.print(" restartDelay="); pw.print(restartDelay-now);
168                    pw.print(" nextRestartTime="); pw.print(nextRestartTime-now);
169                    pw.print(" crashCount="); pw.println(crashCount);
170        }
171        if (deliveredStarts.size() > 0) {
172            pw.print(prefix); pw.println("Delivered Starts:");
173            dumpStartList(pw, prefix, deliveredStarts, SystemClock.uptimeMillis());
174        }
175        if (pendingStarts.size() > 0) {
176            pw.print(prefix); pw.println("Pending Starts:");
177            dumpStartList(pw, prefix, pendingStarts, 0);
178        }
179        if (bindings.size() > 0) {
180            Iterator<IntentBindRecord> it = bindings.values().iterator();
181            pw.print(prefix); pw.println("Bindings:");
182            while (it.hasNext()) {
183                IntentBindRecord b = it.next();
184                pw.print(prefix); pw.print("* IntentBindRecord{");
185                        pw.print(Integer.toHexString(System.identityHashCode(b)));
186                        pw.println("}:");
187                b.dumpInService(pw, prefix + "  ");
188            }
189        }
190        if (connections.size() > 0) {
191            pw.print(prefix); pw.println("All Connections:");
192            Iterator<ConnectionRecord> it = connections.values().iterator();
193            while (it.hasNext()) {
194                ConnectionRecord c = it.next();
195                pw.print(prefix); pw.print("  "); pw.println(c);
196            }
197        }
198    }
199
200    ServiceRecord(ActivityManagerService ams,
201            BatteryStatsImpl.Uid.Pkg.Serv servStats, ComponentName name,
202            Intent.FilterComparison intent, ServiceInfo sInfo, Runnable restarter) {
203        this.ams = ams;
204        this.stats = servStats;
205        this.name = name;
206        shortName = name.flattenToShortString();
207        this.intent = intent;
208        serviceInfo = sInfo;
209        appInfo = sInfo.applicationInfo;
210        packageName = sInfo.applicationInfo.packageName;
211        processName = sInfo.processName;
212        permission = sInfo.permission;
213        baseDir = sInfo.applicationInfo.sourceDir;
214        resDir = sInfo.applicationInfo.publicSourceDir;
215        dataDir = sInfo.applicationInfo.dataDir;
216        exported = sInfo.exported;
217        this.restarter = restarter;
218        createTime = SystemClock.elapsedRealtime();
219        lastActivity = SystemClock.uptimeMillis();
220    }
221
222    public AppBindRecord retrieveAppBindingLocked(Intent intent,
223            ProcessRecord app) {
224        Intent.FilterComparison filter = new Intent.FilterComparison(intent);
225        IntentBindRecord i = bindings.get(filter);
226        if (i == null) {
227            i = new IntentBindRecord(this, filter);
228            bindings.put(filter, i);
229        }
230        AppBindRecord a = i.apps.get(app);
231        if (a != null) {
232            return a;
233        }
234        a = new AppBindRecord(this, i, app);
235        i.apps.put(app, a);
236        return a;
237    }
238
239    public void resetRestartCounter() {
240        restartCount = 0;
241        restartDelay = 0;
242        restartTime = 0;
243    }
244
245    public StartItem findDeliveredStart(int id, boolean remove) {
246        final int N = deliveredStarts.size();
247        for (int i=0; i<N; i++) {
248            StartItem si = deliveredStarts.get(i);
249            if (si.id == id) {
250                if (remove) deliveredStarts.remove(i);
251                return si;
252            }
253        }
254
255        return null;
256    }
257
258    public void postNotification() {
259        final int appUid = appInfo.uid;
260        final int appPid = app.pid;
261        if (foregroundId != 0 && foregroundNoti != null) {
262            // Do asynchronous communication with notification manager to
263            // avoid deadlocks.
264            final String localPackageName = packageName;
265            final int localForegroundId = foregroundId;
266            final Notification localForegroundNoti = foregroundNoti;
267            ams.mHandler.post(new Runnable() {
268                public void run() {
269                    NotificationManagerService nm =
270                            (NotificationManagerService) NotificationManager.getService();
271                    if (nm == null) {
272                        return;
273                    }
274                    try {
275                        int[] outId = new int[1];
276                        nm.enqueueNotificationInternal(localPackageName, appUid, appPid,
277                                null, localForegroundId, localForegroundNoti, outId);
278                    } catch (RuntimeException e) {
279                        Slog.w(ActivityManagerService.TAG,
280                                "Error showing notification for service", e);
281                        // If it gave us a garbage notification, it doesn't
282                        // get to be foreground.
283                        ams.setServiceForeground(name, ServiceRecord.this,
284                                localForegroundId, null, true);
285                    }
286                }
287            });
288        }
289    }
290
291    public void cancelNotification() {
292        if (foregroundId != 0) {
293            // Do asynchronous communication with notification manager to
294            // avoid deadlocks.
295            final String localPackageName = packageName;
296            final int localForegroundId = foregroundId;
297            ams.mHandler.post(new Runnable() {
298                public void run() {
299                    INotificationManager inm = NotificationManager.getService();
300                    if (inm == null) {
301                        return;
302                    }
303                    try {
304                        inm.cancelNotification(localPackageName, localForegroundId);
305                    } catch (RuntimeException e) {
306                        Slog.w(ActivityManagerService.TAG,
307                                "Error canceling notification for service", e);
308                    } catch (RemoteException e) {
309                    }
310                }
311            });
312        }
313    }
314
315    public String toString() {
316        if (stringName != null) {
317            return stringName;
318        }
319        StringBuilder sb = new StringBuilder(128);
320        sb.append("ServiceRecord{")
321            .append(Integer.toHexString(System.identityHashCode(this)))
322            .append(' ').append(shortName).append('}');
323        return stringName = sb.toString();
324    }
325}
326