下面列出了怎么用android.os.Process的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Fetch and return shortcuts for a specific app.
*
* @param launcherApps LauncherApps service from an activity.
* @param componentName The component name to flatten to package name.
*
* @return A list of shortcut. Null if nonexistent.
*/
@TargetApi(Build.VERSION_CODES.N_MR1)
public static List<ShortcutInfo> getShortcuts(LauncherApps launcherApps, String componentName) {
// Return nothing if we don't have permission to retrieve shortcuts.
if (launcherApps == null || !launcherApps.hasShortcutHostPermission()) {
return new ArrayList<>(0);
}
LauncherApps.ShortcutQuery shortcutQuery = new LauncherApps.ShortcutQuery();
shortcutQuery.setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_DYNAMIC
| LauncherApps.ShortcutQuery.FLAG_MATCH_MANIFEST
| LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED);
shortcutQuery.setPackage(getPackageName(componentName));
return launcherApps.getShortcuts(shortcutQuery, Process.myUserHandle());
}
@Override
protected void after(XParam param) throws Throwable {
switch (mMethod) {
case onCreate:
// Install receiver for package management
if (PrivacyManager.isApplication(Process.myUid()) && !mReceiverInstalled)
try {
Application app = (Application) param.thisObject;
if (app != null) {
mReceiverInstalled = true;
Util.log(this, Log.INFO, "Installing receiver uid=" + Process.myUid());
app.registerReceiver(new Receiver(app), new IntentFilter(ACTION_MANAGE_PACKAGE),
PERMISSION_MANAGE_PACKAGES, null);
}
} catch (SecurityException ignored) {
} catch (Throwable ex) {
Util.bug(this, ex);
}
break;
}
}
/**
* Get an AccessibilityManager instance (create one if necessary).
*
* @param context Context in which this manager operates.
*
* @hide
*/
public static AccessibilityManager getInstance(Context context) {
synchronized (sInstanceSync) {
if (sInstance == null) {
final int userId;
if (Binder.getCallingUid() == Process.SYSTEM_UID
|| context.checkCallingOrSelfPermission(
Manifest.permission.INTERACT_ACROSS_USERS)
== PackageManager.PERMISSION_GRANTED
|| context.checkCallingOrSelfPermission(
Manifest.permission.INTERACT_ACROSS_USERS_FULL)
== PackageManager.PERMISSION_GRANTED) {
userId = UserHandle.USER_CURRENT;
} else {
userId = context.getUserId();
}
sInstance = new AccessibilityManager(context, null, userId);
}
}
return sInstance;
}
/**
* [HIDE] 外界请不要调用此方法
*/
public static void init(Context context) {
sCurrentProcess = SysUtils.getCurrentProcessName();
sCurrentPid = Process.myPid();
sPackageName = context.getApplicationInfo().packageName;
// 设置最终的常驻进程名
String cppn = RePlugin.getConfig().getPersistentName();
if (!TextUtils.isEmpty(cppn)) {
if (cppn.startsWith(":")) {
sPersistentProcessName = sPackageName + cppn;
} else {
sPersistentProcessName = cppn;
}
}
sIsUIProcess = sCurrentProcess.equals(sPackageName);
sIsPersistentProcess = sCurrentProcess.equals(sPersistentProcessName);
}
private static void MergeWirteAheads(File storageLocation) {
try {
File wal = new File(STORAGE_LOCATION, "wal");
String curProcessName = OpenAtlasUtils.getProcessNameByPID(Process.myPid());
log.debug("restoreProfile in process " + curProcessName);
String packageName = RuntimeVariables.androidApplication.getPackageName();
if (curProcessName != null && packageName != null && curProcessName.equals(packageName)) {
mergeWalsDir(wal, storageLocation);
}
} catch (Throwable th) {
if (Build.MODEL == null || !Build.MODEL.equals("HTC 802w")) {
log.error(th.getMessage(), th.getCause());
return;
}
}
}
/**
* Generates a device- and invocation-specific seed to be mixed into the
* Linux PRNG.
*/
private static byte[] generateSeed() {
try {
ByteArrayOutputStream seedBuffer = new ByteArrayOutputStream();
DataOutputStream seedBufferOut =
new DataOutputStream(seedBuffer);
seedBufferOut.writeLong(System.currentTimeMillis());
seedBufferOut.writeLong(System.nanoTime());
seedBufferOut.writeInt(Process.myPid());
seedBufferOut.writeInt(Process.myUid());
seedBufferOut.write(BUILD_FINGERPRINT_AND_DEVICE_SERIAL);
seedBufferOut.close();
return seedBuffer.toByteArray();
} catch (IOException e) {
throw new SecurityException("Failed to generate seed", e);
}
}
/**
* Generates a device- and invocation-specific seed to be mixed into the
* Linux PRNG.
*/
private static byte[] generateSeed() {
try {
final ByteArrayOutputStream seedBuffer = new ByteArrayOutputStream();
final DataOutputStream seedBufferOut =
new DataOutputStream(seedBuffer);
seedBufferOut.writeLong(System.currentTimeMillis());
seedBufferOut.writeLong(System.nanoTime());
seedBufferOut.writeInt(Process.myPid());
seedBufferOut.writeInt(Process.myUid());
seedBufferOut.write(BUILD_FINGERPRINT_AND_DEVICE_SERIAL);
seedBufferOut.close();
return seedBuffer.toByteArray();
} catch (final IOException e) {
throw new SecurityException("Failed to generate seed", e);
}
}
private ActivityStateListener createActivityStateListener() {
return new ActivityStateListener() {
@Override
public void onActivityStateChange(Activity activity, int newState) {
if (newState == ActivityState.CREATED || newState == ActivityState.DESTROYED) {
// Android destroys Activities at some point after a locale change, but doesn't
// kill the process. This can lead to a bug where Chrome is halfway RTL, where
// stale natively-loaded resources are not reloaded (http://crbug.com/552618).
if (!mInitialLocale.equals(Locale.getDefault())) {
Log.e(TAG, "Killing process because of locale change.");
Process.killProcess(Process.myPid());
}
DeviceFormFactor.resetValuesIfNeeded(mApplication);
}
}
};
}
public RestrictionAdapter(Context context, int resource, ApplicationInfoEx appInfo,
String selectedRestrictionName, String selectedMethodName) {
mContext = context;
mAppInfo = appInfo;
mSelectedRestrictionName = selectedRestrictionName;
mSelectedMethodName = selectedMethodName;
mListRestriction = new ArrayList<String>();
mHook = new LinkedHashMap<Integer, List<Hook>>();
mVersion = new Version(Util.getSelfVersionName(context));
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int userId = Util.getUserId(Process.myUid());
boolean fUsed = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFUsed, false);
boolean fPermission = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFPermission, false);
for (String rRestrictionName : PrivacyManager.getRestrictions(mContext).values()) {
boolean isUsed = (PrivacyManager.getUsage(mAppInfo.getUid(), rRestrictionName, null) > 0);
boolean hasPermission = PrivacyManager.hasPermission(mContext, mAppInfo, rRestrictionName, mVersion);
if (mSelectedRestrictionName != null
|| ((fUsed ? isUsed : true) && (fPermission ? isUsed || hasPermission : true)))
mListRestriction.add(rRestrictionName);
}
}
public PortSweeper(int port, String file, int threadCount, Callback callback, Looper looper) {
mPort = port;
mPath = file;
mWorkerCount = threadCount;
mCallback = callback;
mAddressQueue = new ConcurrentLinkedQueue<byte[]>();
mWorkerManager = new MyWorkerManager();
mWorkerCallback = new MyWorkerCallback();
mScanThread = new HandlerThread("Scanner", Process.THREAD_PRIORITY_BACKGROUND);
mScanThread.start();
Handler.Callback callbackHandlerCallback = new MyCallbackHandlerCallback();
mCallbackHandler = new Handler(looper, callbackHandlerCallback);
Handler.Callback scanHandlerCallback = new MyScanHandlerCallback();
mScanHandler = new Handler(mScanThread.getLooper(), scanHandlerCallback);
}
void enforceManageAppOpsModes(int callingPid, int callingUid, int targetUid) {
if (callingPid == Process.myPid()) {
return;
}
final int callingUser = UserHandle.getUserId(callingUid);
synchronized (this) {
if (mProfileOwners != null && mProfileOwners.get(callingUser, -1) == callingUid) {
if (targetUid >= 0 && callingUser == UserHandle.getUserId(targetUid)) {
// Profile owners are allowed to change modes but only for apps
// within their user.
return;
}
}
}
mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
Binder.getCallingPid(), Binder.getCallingUid(), null);
}
/**
* Generates a device- and invocation-specific seed to be mixed into the
* Linux PRNG.
*/
private static byte[] generateSeed() {
try {
ByteArrayOutputStream seedBuffer = new ByteArrayOutputStream();
DataOutputStream seedBufferOut =
new DataOutputStream(seedBuffer);
seedBufferOut.writeLong(System.currentTimeMillis());
seedBufferOut.writeLong(System.nanoTime());
seedBufferOut.writeInt(Process.myPid());
seedBufferOut.writeInt(Process.myUid());
seedBufferOut.write(BUILD_FINGERPRINT_AND_DEVICE_SERIAL);
seedBufferOut.close();
return seedBuffer.toByteArray();
} catch (IOException e) {
throw new SecurityException("Failed to generate seed", e);
}
}
private static boolean checkOpsPermission(Context context, String permission) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
String opsName = AppOpsManager.permissionToOp(permission);
if (opsName == null) {
return true;
}
int opsMode = appOpsManager.checkOpNoThrow(opsName, Process.myUid(), context.getPackageName());
return opsMode == AppOpsManager.MODE_ALLOWED;
} catch (Exception ex) {
return true;
}
}
return true;
}
private void setApplicationInfo(ApplicationInfo aInfo) {
final int myUid = Process.myUid();
aInfo = adjustNativeLibraryPaths(aInfo);
mApplicationInfo = aInfo;
mAppDir = aInfo.sourceDir;
mResDir = aInfo.uid == myUid ? aInfo.sourceDir : aInfo.publicSourceDir;
mOverlayDirs = aInfo.resourceDirs;
mDataDir = aInfo.dataDir;
mLibDir = aInfo.nativeLibraryDir;
mDataDirFile = FileUtils.newFileOrNull(aInfo.dataDir);
mDeviceProtectedDataDirFile = FileUtils.newFileOrNull(aInfo.deviceProtectedDataDir);
mCredentialProtectedDataDirFile = FileUtils.newFileOrNull(aInfo.credentialProtectedDataDir);
mSplitNames = aInfo.splitNames;
mSplitAppDirs = aInfo.splitSourceDirs;
mSplitResDirs = aInfo.uid == myUid ? aInfo.splitSourceDirs : aInfo.splitPublicSourceDirs;
mSplitClassLoaderNames = aInfo.splitClassLoaderNames;
if (aInfo.requestsIsolatedSplitLoading() && !ArrayUtils.isEmpty(mSplitNames)) {
mSplitLoader = new SplitDependencyLoaderImpl(aInfo.splitDependencies);
}
}
final void handleLowMemory() {
ArrayList<ComponentCallbacks2> callbacks;
synchronized (mPackages) {
callbacks = collectComponentCallbacksLocked(true, null);
}
final int N = callbacks.size();
for (int i=0; i<N; i++) {
callbacks.get(i).onLowMemory();
}
// Ask SQLite to free up as much memory as it can, mostly from its page caches.
if (Process.myUid() != Process.SYSTEM_UID) {
int sqliteReleased = SQLiteDatabase.releaseMemory();
EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
}
// Ask graphics to free up as much as possible (font/image caches)
Canvas.freeCaches();
// Ask text layout engine to free also as much as possible
Canvas.freeTextLayoutCaches();
BinderInternal.forceGc("mem");
}
/**
* Lazily create a handler on a separate thread.
*
* @return the handler
*/
private static Handler getHandler() {
synchronized (sLock) {
if (sHandler == null) {
HandlerThread handlerThread = new HandlerThread("queued-work-looper",
Process.THREAD_PRIORITY_FOREGROUND);
handlerThread.start();
sHandler = new QueuedWorkHandler(handlerThread.getLooper());
}
return sHandler;
}
}
@Override
public void onProximityNegative() {
synchronized (mLock) {
mProximityPositive = false;
mDirty |= DIRTY_PROXIMITY_POSITIVE;
userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
updatePowerStateLocked();
}
}
public static String md5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
// MD5
int userId = Util.getUserId(Process.myUid());
String salt = PrivacyManager.getSalt(userId);
byte[] bytes = MessageDigest.getInstance("MD5").digest((text + salt).getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte b : bytes)
sb.append(String.format("%02X", b));
return sb.toString();
}
@Override
public void onCreate() {
super.onCreate();
Utils.debugLog(TAG, "Creating downloader service.");
HandlerThread thread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
serviceLooper = thread.getLooper();
if (BuildConfig.DEBUG) {
serviceLooper.setMessageLogging(new LogPrinter(Log.DEBUG, ServiceHandler.TAG));
}
serviceHandler = new ServiceHandler(serviceLooper);
localBroadcastManager = LocalBroadcastManager.getInstance(this);
}
void exitForceIdleLocked() {
if (mForceIdle) {
mForceIdle = false;
if (mScreenOn || mCharging) {
becomeActiveLocked("exit-force", Process.myUid());
}
}
}
@Override
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_AUDIO);
while (isConnecting && !socketHandler.isInterrupted()) {
synchronized (socketHandler.readLocker) {
handleSocketRead();
}
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("ServiceStartArguments",
"Starting #" + startId + ": " + intent.getExtras());
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.arg2 = flags;
msg.obj = intent.getExtras();
mServiceHandler.sendMessage(msg);
Log.i("ServiceStartArguments", "Sending: " + msg);
// For the start fail button, we will simulate the process dying
// for some reason in onStartCommand().
if (intent.getBooleanExtra("fail", false)) {
// Don't do this if we are in a retry... the system will
// eventually give up if we keep crashing.
if ((flags&START_FLAG_RETRY) == 0) {
// Since the process hasn't finished handling the command,
// it will be restarted with the command again, regardless of
// whether we return START_REDELIVER_INTENT.
Process.killProcess(Process.myPid());
}
}
// Normally we would consistently return one kind of result...
// however, here we will select between these two, so you can see
// how they impact the behavior. Try killing the process while it
// is in the middle of executing the different commands.
return intent.getBooleanExtra("redeliver", false)
? START_REDELIVER_INTENT : START_NOT_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate()");
HandlerThread thread = new HandlerThread("dispatcher",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mHandler = new Handler(mServiceLooper, getHandlerCallback());
if (!initialized)
initialized = checkInit();
mNotificationFactory = NotificationFactory.getInstance(this);
mNotificationFactory.setContentTitle(R.string.network_alert);
}
private static boolean shouldInit(Context context) {
ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));
List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
String mainProcessName = context.getPackageName();
int myPid = Process.myPid();
for (ActivityManager.RunningAppProcessInfo info : processInfos) {
if (info.pid == myPid && mainProcessName.equals(info.processName)) {
return true;
}
}
return false;
}
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*/
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
return postResult(doInBackground(mParams));
}
};
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
try {
postResultIfNotInvoked(get());
} catch (InterruptedException e) {
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
public static @NonNull
Handler createIfNotExistHandler(String tag) {
synchronized (sLockForHandlerManager) {
Handler tmp = sHandlerMap.get(tag);
if (tmp != null) {
return tmp;
}
HandlerThread handlerThread = new HandlerThread(tag, Process.THREAD_PRIORITY_BACKGROUND);
handlerThread.start();
Handler handler = new Handler(handlerThread.getLooper());
sHandlerMap.put(tag, handler);
return handler;
}
}
@Override
public int checkCallingPermission(String permission) {
if (permission == null) {
throw new IllegalArgumentException("permission is null");
}
int pid = Binder.getCallingPid();
if (pid != Process.myPid()) {
return checkPermission(permission, pid, Binder.getCallingUid());
}
return PackageManager.PERMISSION_DENIED;
}
/**
* Returns "true" if the UID belongs to a bound location provider.
*
* @param uid the uid
* @return true if uid belongs to a bound location provider
*/
private boolean isUidALocationProvider(int uid) {
if (uid == Process.SYSTEM_UID) {
return true;
}
if (mGeocodeProvider != null) {
if (doesUidHavePackage(uid, mGeocodeProvider.getConnectedPackageName())) return true;
}
for (LocationProviderProxy proxy : mProxyProviders) {
if (doesUidHavePackage(uid, proxy.getConnectedPackageName())) return true;
}
return false;
}
@Override
public void notifyCameraState(String cameraId, int newCameraState, int facing,
String clientName, int apiLevel) {
if (Binder.getCallingUid() != Process.CAMERASERVER_UID) {
Slog.e(TAG, "Calling UID: " + Binder.getCallingUid() + " doesn't match expected " +
" camera service UID!");
return;
}
String state = cameraStateToString(newCameraState);
String facingStr = cameraFacingToString(facing);
if (DEBUG) Slog.v(TAG, "Camera " + cameraId + " facing " + facingStr + " state now " +
state + " for client " + clientName + " API Level " + apiLevel);
updateActivityCount(cameraId, newCameraState, facing, clientName, apiLevel);
}
private int getAppUid(String app, int userHandle) {
if (VpnConfig.LEGACY_VPN.equals(app)) {
return Process.myUid();
}
PackageManager pm = mContext.getPackageManager();
int result;
try {
result = pm.getPackageUidAsUser(app, userHandle);
} catch (NameNotFoundException e) {
result = -1;
}
return result;
}