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