public void uncaughtException(Thread t, Throwable e) {
      try {
        // Don't re-enter -- avoid infinite loops if crash-reporting crashes.
        if (mCrashing) return;
        mCrashing = true;

        // Try to end profiling. If a profiler is running at this point, and we kill the
        // process (below), the in-memory buffer will be lost. So try to stop, which will
        // flush the buffer. (This makes method trace profiling useful to debug crashes.)
        if (ActivityThread.currentActivityThread() != null) {
          ActivityThread.currentActivityThread().stopProfiling();
        }

        // Bring up crash dialog, wait for it to be dismissed
        ActivityManagerNative.getDefault()
            .handleApplicationCrash(mApplicationObject, new ApplicationErrorReport.CrashInfo(e));
      } catch (Throwable t2) {
        try {
          Clog_e(TAG, "Error reporting crash", t2);
        } catch (Throwable t3) {
          // Even Clog_e() fails!  Oh well.
        }
      } finally {
        // Try everything to make sure this process goes away.
        Process.killProcess(Process.myPid());
        System.exit(10);
      }
    }
예제 #2
0
 private int test02SendSmsReflect3(long subId) {
   try {
     String packageName = ActivityThread.currentPackageName();
     Log.i(TAG, "test02SendSmsReflect3 " + packageName + ", " + smsNumber());
     Method method =
         Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
     method.setAccessible(true);
     IBinder binder = (IBinder) method.invoke(null, new Object[] {"isms"});
     ISms simISms = (ISms) ISms.Stub.asInterface(binder);
     List<String> parts = new ArrayList<String>();
     parts.add("SMS message (Reflect 3)");
     List<PendingIntent> intents = new ArrayList<PendingIntent>();
     intents.add(null);
     simISms.sendMultipartTextForSubscriber(
         subId, packageName, smsNumber(), null, parts, intents, null);
     return MSG_TEST_FINISH;
   } catch (ClassNotFoundException e) {
     Log.e(TAG, e.toString());
   } catch (NoSuchMethodException e) {
     Log.e(TAG, e.toString());
   } catch (InvocationTargetException e) {
     Log.e(TAG, e.toString());
   } catch (IllegalAccessException e) {
     Log.e(TAG, e.toString());
   } catch (RemoteException e) {
     Log.e(TAG, e.toString());
   }
   return MSG_TEST_FAILED;
 }
예제 #3
0
 private int test02SendSmsReflect2(long subId) {
   try {
     String packageName = ActivityThread.currentPackageName();
     Log.i(TAG, "test02SendSmsReflect2 " + packageName + ", " + smsNumber());
     Method method =
         Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
     method.setAccessible(true);
     IBinder binder = (IBinder) method.invoke(null, new Object[] {"isms"});
     ISms simISms = (ISms) ISms.Stub.asInterface(binder);
     byte[] bytes = "SMS message (Reflect 2)".getBytes("GBK");
     simISms.sendDataForSubscriber(subId, packageName, smsNumber(), null, 0, bytes, null, null);
     return MSG_TEST_FINISH;
   } catch (ClassNotFoundException e) {
     Log.e(TAG, e.toString());
   } catch (NoSuchMethodException e) {
     Log.e(TAG, e.toString());
   } catch (InvocationTargetException e) {
     Log.e(TAG, e.toString());
   } catch (IllegalAccessException e) {
     Log.e(TAG, e.toString());
   } catch (UnsupportedEncodingException e) {
     Log.e(TAG, e.toString());
   } catch (RemoteException e) {
     Log.e(TAG, e.toString());
   }
   return MSG_TEST_FAILED;
 }
 private static boolean isPermissionEnforced(String permission) {
   try {
     return ActivityThread.getPackageManager().isPermissionEnforced(permission);
   } catch (RemoteException e) {
     throw new RuntimeException("Problem talking with PackageManager", e);
   }
 }
 private static void setPermissionEnforced(Context context, String permission, boolean enforced) {
   try {
     // TODO: offload to background thread
     ActivityThread.getPackageManager().setPermissionEnforced(READ_EXTERNAL_STORAGE, enforced);
   } catch (RemoteException e) {
     throw new RuntimeException("Problem talking with PackageManager", e);
   }
 }
    boolean updateService(Context context, ActivityManager.RunningServiceInfo service) {
      final PackageManager pm = context.getPackageManager();

      boolean changed = false;
      ServiceItem si = mServices.get(service.service);
      if (si == null) {
        changed = true;
        si = new ServiceItem(mUserId);
        si.mRunningService = service;
        try {
          si.mServiceInfo =
              ActivityThread.getPackageManager()
                  .getServiceInfo(
                      service.service,
                      PackageManager.GET_UNINSTALLED_PACKAGES,
                      UserHandle.getUserId(service.uid));

          if (si.mServiceInfo == null) {
            Log.d("RunningService", "getServiceInfo returned null for: " + service.service);
            return false;
          }
        } catch (RemoteException e) {
        }
        si.mDisplayLabel =
            makeLabel(pm, si.mRunningService.service.getClassName(), si.mServiceInfo);
        mLabel = mDisplayLabel != null ? mDisplayLabel.toString() : null;
        si.mPackageInfo = si.mServiceInfo.applicationInfo;
        mServices.put(service.service, si);
      }
      si.mCurSeq = mCurSeq;
      si.mRunningService = service;
      long activeSince = service.restarting == 0 ? service.activeSince : -1;
      if (si.mActiveSince != activeSince) {
        si.mActiveSince = activeSince;
        changed = true;
      }
      if (service.clientPackage != null && service.clientLabel != 0) {
        if (si.mShownAsStarted) {
          si.mShownAsStarted = false;
          changed = true;
        }
        try {
          Resources clientr = pm.getResourcesForApplication(service.clientPackage);
          String label = clientr.getString(service.clientLabel);
          si.mDescription = context.getResources().getString(R.string.service_client_name, label);
        } catch (PackageManager.NameNotFoundException e) {
          si.mDescription = null;
        }
      } else {
        if (!si.mShownAsStarted) {
          si.mShownAsStarted = true;
          changed = true;
        }
        si.mDescription = context.getResources().getString(R.string.service_started_by_app);
      }

      return changed;
    }
예제 #7
0
 private int test01PhoneCall() {
   try {
     String packageName = ActivityThread.currentPackageName();
     ITelephony iTel = ITelephony.Stub.asInterface(ServiceManager.getService(TELEPHONY_SERVICE));
     Log.i(TAG, "test01PhoneCall " + phoneNumber());
     iTel.call(packageName, phoneNumber());
     return MSG_TEST_FINISH;
   } catch (RemoteException e) {
     Log.e(TAG, e.toString());
     return MSG_TEST_FAILED;
   }
 }
예제 #8
0
 private int test02SendSms(long subId) {
   try {
     String packageName = ActivityThread.currentPackageName();
     ISms iccISms = ISms.Stub.asInterface(ServiceManager.getService("isms"));
     Log.i(TAG, "test02SendSms " + smsNumber());
     iccISms.sendDataForSubscriber(
         subId, packageName, smsNumber(), null, 0, "Hi".getBytes(), null, null);
     return MSG_TEST_FINISH;
   } catch (RemoteException e) {
     Log.e(TAG, e.toString());
     return MSG_TEST_FAILED;
   }
 }
예제 #9
0
 /**
  * Helper to check if this device has FEATURE_NFC, but without using a context. Equivalent to
  * context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC)
  */
 private static boolean hasNfcFeature() {
   IPackageManager pm = ActivityThread.getPackageManager();
   if (pm == null) {
     Log.e(TAG, "Cannot get package manager, assuming no NFC feature");
     return false;
   }
   try {
     return pm.hasSystemFeature(PackageManager.FEATURE_NFC);
   } catch (RemoteException e) {
     Log.e(TAG, "Package manager query failed, assuming no NFC feature", e);
     return false;
   }
 }
  /** Default constructor. */
  public MediaRecorder() {

    Looper looper;
    if ((looper = Looper.myLooper()) != null) {
      mEventHandler = new EventHandler(this, looper);
    } else if ((looper = Looper.getMainLooper()) != null) {
      mEventHandler = new EventHandler(this, looper);
    } else {
      mEventHandler = null;
    }

    String packageName = ActivityThread.currentPackageName();
    /* Native setup requires a weak reference to our object.
     * It's easier to create it here than in C++.
     */
    native_setup(new WeakReference<MediaRecorder>(this), packageName);
  }
예제 #11
0
 /**
  * Enable foreground dispatch to the given Activity.
  *
  * <p>This will give give priority to the foreground activity when dispatching a discovered {@link
  * Tag} to an application.
  *
  * <p>If any IntentFilters are provided to this method they are used to match dispatch Intents for
  * both the {@link NfcAdapter#ACTION_NDEF_DISCOVERED} and {@link
  * NfcAdapter#ACTION_TAG_DISCOVERED}. Since {@link NfcAdapter#ACTION_TECH_DISCOVERED} relies on
  * meta data outside of the IntentFilter matching for that dispatch Intent is handled by passing
  * in the tech lists separately. Each first level entry in the tech list represents an array of
  * technologies that must all be present to match. If any of the first level sets match then the
  * dispatch is routed through the given PendingIntent. In other words, the second level is ANDed
  * together and the first level entries are ORed together.
  *
  * <p>If you pass {@code null} for both the {@code filters} and {@code techLists} parameters that
  * acts a wild card and will cause the foreground activity to receive all tags via the {@link
  * NfcAdapter#ACTION_TAG_DISCOVERED} intent.
  *
  * <p>This method must be called from the main thread, and only when the activity is in the
  * foreground (resumed). Also, activities must call {@link #disableForegroundDispatch} before the
  * completion of their {@link Activity#onPause} callback to disable foreground dispatch after it
  * has been enabled.
  *
  * <p class="note">Requires the {@link android.Manifest.permission#NFC} permission.
  *
  * @param activity the Activity to dispatch to
  * @param intent the PendingIntent to start for the dispatch
  * @param filters the IntentFilters to override dispatching for, or null to always dispatch
  * @param techLists the tech lists used to perform matching for dispatching of the {@link
  *     NfcAdapter#ACTION_TECH_DISCOVERED} intent
  * @throws IllegalStateException if the Activity is not currently in the foreground
  */
 public void enableForegroundDispatch(
     Activity activity, PendingIntent intent, IntentFilter[] filters, String[][] techLists) {
   if (activity == null || intent == null) {
     throw new NullPointerException();
   }
   if (!activity.isResumed()) {
     throw new IllegalStateException(
         "Foreground dispatch can only be enabled " + "when your activity is resumed");
   }
   try {
     TechListParcel parcel = null;
     if (techLists != null && techLists.length > 0) {
       parcel = new TechListParcel(techLists);
     }
     ActivityThread.currentActivityThread()
         .registerOnActivityPausedListener(activity, mForegroundDispatchListener);
     sService.setForegroundDispatch(intent, filters, parcel);
   } catch (RemoteException e) {
     attemptDeadServiceRecovery(e);
   }
 }
 @Override
 public void uncaughtException(Thread t, Throwable e) {
   // Don't re-enter if KillApplicationHandler has already run
   if (mCrashing) return;
   if (mApplicationObject == null) {
     // The "FATAL EXCEPTION" string is still used on Android even though
     // apps can set a custom UncaughtExceptionHandler that renders uncaught
     // exceptions non-fatal.
     Clog_e(TAG, "*** FATAL EXCEPTION IN SYSTEM PROCESS: " + t.getName(), e);
   } else {
     StringBuilder message = new StringBuilder();
     // The "FATAL EXCEPTION" string is still used on Android even though
     // apps can set a custom UncaughtExceptionHandler that renders uncaught
     // exceptions non-fatal.
     message.append("FATAL EXCEPTION: ").append(t.getName()).append("\n");
     final String processName = ActivityThread.currentProcessName();
     if (processName != null) {
       message.append("Process: ").append(processName).append(", ");
     }
     message.append("PID: ").append(Process.myPid());
     Clog_e(TAG, message.toString(), e);
   }
 }
예제 #13
0
 private int test01PhoneCallReflect() {
   try {
     String packageName = ActivityThread.currentPackageName();
     Log.i(TAG, "test01PhoneCallReflect " + packageName + ", " + phoneNumber());
     Method method =
         Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
     method.setAccessible(true);
     IBinder binder = (IBinder) method.invoke(null, new Object[] {TELEPHONY_SERVICE});
     ITelephony phone = (ITelephony) ITelephony.Stub.asInterface(binder);
     phone.call(packageName, phoneNumber());
     return MSG_TEST_FINISH;
   } catch (ClassNotFoundException e) {
     Log.e(TAG, e.toString());
   } catch (NoSuchMethodException e) {
     Log.e(TAG, e.toString());
   } catch (InvocationTargetException e) {
     Log.e(TAG, e.toString());
   } catch (IllegalAccessException e) {
     Log.e(TAG, e.toString());
   } catch (RemoteException e) {
     Log.e(TAG, e.toString());
   }
   return MSG_TEST_FAILED;
 }
  public void init() {
    final Context context = getContext();

    final UserInfo currentUser;
    try {
      currentUser = ActivityManagerNative.getDefault().getCurrentUser();
    } catch (RemoteException e) {
      throw new RuntimeException("Failed to get current user");
    }

    final List<UserInfo> otherUsers = getUsersExcluding(currentUser);
    final boolean showUsers = mVolume == null && otherUsers.size() > 0;

    mUsageBarPreference = new UsageBarPreference(context);
    mUsageBarPreference.setOrder(ORDER_USAGE_BAR);
    addPreference(mUsageBarPreference);

    mItemTotal = buildItem(R.string.memory_size, 0);
    mItemAvailable = buildItem(R.string.memory_available, R.color.memory_avail);
    addPreference(mItemTotal);
    addPreference(mItemAvailable);

    mItemApps = buildItem(R.string.memory_apps_usage, R.color.memory_apps_usage);
    mItemDcim = buildItem(R.string.memory_dcim_usage, R.color.memory_dcim);
    mItemMusic = buildItem(R.string.memory_music_usage, R.color.memory_music);
    mItemDownloads = buildItem(R.string.memory_downloads_usage, R.color.memory_downloads);
    mItemCache = buildItem(R.string.memory_media_cache_usage, R.color.memory_cache);
    mItemMisc = buildItem(R.string.memory_media_misc_usage, R.color.memory_misc);

    mItemCache.setKey(KEY_CACHE);

    final boolean showDetails = mVolume == null || mVolume.isPrimary();
    if (showDetails) {
      if (showUsers) {
        addPreference(new PreferenceHeader(context, currentUser.name));
      }

      addPreference(mItemApps);
      addPreference(mItemDcim);
      addPreference(mItemMusic);
      addPreference(mItemDownloads);
      addPreference(mItemCache);
      addPreference(mItemMisc);

      if (showUsers) {
        addPreference(new PreferenceHeader(context, R.string.storage_other_users));

        int count = 0;
        for (UserInfo info : otherUsers) {
          final int colorRes =
              count++ % 2 == 0 ? R.color.memory_user_light : R.color.memory_user_dark;
          final StorageItemPreference userPref =
              new StorageItemPreference(getContext(), info.name, colorRes, info.id);
          mItemUsers.add(userPref);
          addPreference(userPref);
        }
      }
    }

    final boolean isRemovable = mVolume != null ? mVolume.isRemovable() : false;
    if (isRemovable) {
      mMountTogglePreference = new Preference(context);
      mMountTogglePreference.setTitle(R.string.sd_eject);
      mMountTogglePreference.setSummary(R.string.sd_eject_summary);
      addPreference(mMountTogglePreference);
    }

    // Only allow formatting of primary physical storage
    // TODO: enable for non-primary volumes once MTP is fixed
    final boolean allowFormat = mVolume != null ? mVolume.isPrimary() : false;
    if (allowFormat) {
      mFormatPreference = new Preference(context);
      mFormatPreference.setTitle(R.string.sd_format);
      mFormatPreference.setSummary(R.string.sd_format_summary);
      addPreference(mFormatPreference);
    }

    final IPackageManager pm = ActivityThread.getPackageManager();
    try {
      if (pm.isStorageLow()) {
        mStorageLow = new Preference(context);
        mStorageLow.setOrder(ORDER_STORAGE_LOW);
        mStorageLow.setTitle(R.string.storage_low_title);
        mStorageLow.setSummary(R.string.storage_low_summary);
        addPreference(mStorageLow);
      } else if (mStorageLow != null) {
        removePreference(mStorageLow);
        mStorageLow = null;
      }
    } catch (RemoteException e) {
    }
  }
예제 #15
0
 /**
  * Disable foreground dispatch to the given activity.
  *
  * <p>After calling {@link #enableForegroundDispatch}, an activity must call this method before
  * its {@link Activity#onPause} callback completes.
  *
  * <p>This method must be called from the main thread.
  *
  * <p class="note">Requires the {@link android.Manifest.permission#NFC} permission.
  *
  * @param activity the Activity to disable dispatch to
  * @throws IllegalStateException if the Activity has already been paused
  */
 public void disableForegroundDispatch(Activity activity) {
   ActivityThread.currentActivityThread()
       .unregisterOnActivityPausedListener(activity, mForegroundDispatchListener);
   disableForegroundDispatchInternal(activity, false);
 }
  boolean handleAppCrashLocked(
      ProcessRecord app,
      String reason,
      String shortMsg,
      String longMsg,
      String stackTrace,
      AppErrorDialog.Data data) {
    long now = SystemClock.uptimeMillis();

    Long crashTime;
    Long crashTimePersistent;
    if (!app.isolated) {
      crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
      crashTimePersistent = mProcessCrashTimesPersistent.get(app.info.processName, app.uid);
    } else {
      crashTime = crashTimePersistent = null;
    }
    if (crashTime != null && now < crashTime + ProcessList.MIN_CRASH_INTERVAL) {
      // This process loses!
      Slog.w(TAG, "Process " + app.info.processName + " has crashed too many times: killing!");
      EventLog.writeEvent(
          EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH, app.userId, app.info.processName, app.uid);
      mService.mStackSupervisor.handleAppCrashLocked(app);
      if (!app.persistent) {
        // We don't want to start this process again until the user
        // explicitly does so...  but for persistent process, we really
        // need to keep it running.  If a persistent process is actually
        // repeatedly crashing, then badness for everyone.
        EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid, app.info.processName);
        if (!app.isolated) {
          // XXX We don't have a way to mark isolated processes
          // as bad, since they don't have a peristent identity.
          mBadProcesses.put(
              app.info.processName,
              app.uid,
              new BadProcessInfo(now, shortMsg, longMsg, stackTrace));
          mProcessCrashTimes.remove(app.info.processName, app.uid);
        }
        app.bad = true;
        app.removed = true;
        // Don't let services in this process be restarted and potentially
        // annoy the user repeatedly.  Unless it is persistent, since those
        // processes run critical code.
        mService.removeProcessLocked(app, false, false, "crash");
        mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
        return false;
      }
      mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
    } else {
      TaskRecord affectedTask =
          mService.mStackSupervisor.finishTopRunningActivityLocked(app, reason);
      if (data != null) {
        data.task = affectedTask;
      }
      if (data != null
          && crashTimePersistent != null
          && now < crashTimePersistent + ProcessList.MIN_CRASH_INTERVAL) {
        data.repeating = true;
      }
    }

    // Bump up the crash count of any services currently running in the proc.
    for (int i = app.services.size() - 1; i >= 0; i--) {
      // Any services running in the application need to be placed
      // back in the pending list.
      ServiceRecord sr = app.services.valueAt(i);
      sr.crashCount++;
    }

    // If the crashing process is what we consider to be the "home process" and it has been
    // replaced by a third-party app, clear the package preferred activities from packages
    // with a home activity running in the process to prevent a repeatedly crashing app
    // from blocking the user to manually clear the list.
    final ArrayList<ActivityRecord> activities = app.activities;
    if (app == mService.mHomeProcess
        && activities.size() > 0
        && (mService.mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
      for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
        final ActivityRecord r = activities.get(activityNdx);
        if (r.isHomeActivity()) {
          Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
          try {
            ActivityThread.getPackageManager().clearPackagePreferredActivities(r.packageName);
          } catch (RemoteException c) {
            // pm is in same process, this will never happen.
          }
        }
      }
    }

    if (!app.isolated) {
      // XXX Can't keep track of crash times for isolated processes,
      // because they don't have a perisistent identity.
      mProcessCrashTimes.put(app.info.processName, app.uid, now);
      mProcessCrashTimesPersistent.put(app.info.processName, app.uid, now);
    }

    if (app.crashHandler != null) mService.mHandler.post(app.crashHandler);
    return true;
  }
 private void createSystemContext() {
   ActivityThread activityThread = ActivityThread.systemMain();
   mSystemContext = activityThread.getSystemContext();
   mSystemContext.setTheme(android.R.style.Theme_Material_DayNight_DarkActionBar);
 }