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