下面列出了怎么用android.os.Binder的API类实例代码及写法,或者点击链接到github查看源代码。
@TargetApi(Build.VERSION_CODES.KITKAT)
private static boolean checkOp(Context context, int op) {
final int version = Build.VERSION.SDK_INT;
if (version >= 19) {
AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
try {
Class clazz = AppOpsManager.class;
Method method = clazz.getDeclaredMethod("checkOp", int.class, int.class, String.class);
return AppOpsManager.MODE_ALLOWED == (int)method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName());
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
}
} else {
Log.e(TAG, "Below API 19 cannot invoke!");
}
return false;
}
/**
* Find the most relevant {@link SubscriptionPlan} for the given
* {@link NetworkTemplate} and flags. This is typically used to augment
* local measurement results to match a known anchor from the carrier.
*/
private SubscriptionPlan resolveSubscriptionPlan(NetworkTemplate template, int flags) {
SubscriptionPlan plan = null;
if ((flags & NetworkStatsManager.FLAG_AUGMENT_WITH_SUBSCRIPTION_PLAN) != 0
&& mSettings.getAugmentEnabled()) {
if (LOGD) Slog.d(TAG, "Resolving plan for " + template);
final long token = Binder.clearCallingIdentity();
try {
plan = LocalServices.getService(NetworkPolicyManagerInternal.class)
.getSubscriptionPlan(template);
} finally {
Binder.restoreCallingIdentity(token);
}
if (LOGD) Slog.d(TAG, "Resolved to plan " + plan);
}
return plan;
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private static boolean checkOp(Context context, int op) {
final int version = Build.VERSION.SDK_INT;
if (version >= 19) {
AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
try {
Class clazz = AppOpsManager.class;
Method method = clazz.getDeclaredMethod("checkOp", int.class, int.class, String.class);
return AppOpsManager.MODE_ALLOWED == (int)method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName());
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
}
} else {
Log.e("", "Below API 19 cannot invoke!");
}
return false;
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private static boolean checkOp(Context context, int op) {
final int version = Build.VERSION.SDK_INT;
if (version >= 19) {
AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
try {
Class clazz = AppOpsManager.class;
Method method = clazz.getDeclaredMethod("checkOp", int.class, int.class, String.class);
return AppOpsManager.MODE_ALLOWED == (int)method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName());
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
}
} else {
Log.e("", "Below API 19 cannot invoke!");
}
return false;
}
/**
* Runs some checks for GNSS (FINE) level permissions, used by several methods which directly
* (try to) access GNSS information at this layer.
*/
private boolean hasGnssPermissions(String packageName) {
int allowedResolutionLevel = getCallerAllowedResolutionLevel();
checkResolutionLevelIsSufficientForProviderUse(
allowedResolutionLevel,
LocationManager.GPS_PROVIDER);
int pid = Binder.getCallingPid();
int uid = Binder.getCallingUid();
long identity = Binder.clearCallingIdentity();
boolean hasLocationAccess;
try {
hasLocationAccess = checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
} finally {
Binder.restoreCallingIdentity(identity);
}
return hasLocationAccess;
}
private int setWifiTethering(final boolean enable) {
int rval = TETHER_ERROR_MASTER_ERROR;
final long ident = Binder.clearCallingIdentity();
try {
synchronized (mPublicSync) {
mWifiTetherRequested = enable;
final WifiManager mgr = getWifiManager();
if ((enable && mgr.startSoftAp(null /* use existing wifi config */)) ||
(!enable && mgr.stopSoftAp())) {
rval = TETHER_ERROR_NO_ERROR;
}
}
} finally {
Binder.restoreCallingIdentity(ident);
}
return rval;
}
@Override
public void deleteDocument(String docId) throws FileNotFoundException {
final String packageName = getPackageForDocId(docId);
final long token = Binder.clearCallingIdentity();
try {
if (docId.startsWith(ROOT_ID_USER_APP)) {
PackageManagerUtils.uninstallApp(getContext(), packageName);
}
else if(docId.startsWith(ROOT_ID_PROCESS)) {
activityManager.killBackgroundProcesses(getPackageForDocId(docId));
}
notifyDocumentsChanged(docId);
} finally {
Binder.restoreCallingIdentity(token);
}
}
public List<PackageInfo> getInstalledPackages(int flags) throws RemoteException {
waitForReadyInner();
try {
enforcePluginFileExists();
List<PackageInfo> infos = new ArrayList(this.mPluginCache.size());
if (shouldNotBlockOtherInfo()) {
for (PluginPackageParser pluginPackageParser : this.mPluginCache.values()) {
infos.add(pluginPackageParser.getPackageInfo(flags));
}
return infos;
}
List<String> pkgs = this.mActivityManagerService.getPackageNamesByPid(Binder.getCallingPid());
for (PluginPackageParser pluginPackageParser2 : this.mPluginCache.values()) {
if (pkgs.contains(pluginPackageParser2.getPackageName())) {
infos.add(pluginPackageParser2.getPackageInfo(flags));
}
}
return infos;
} catch (Exception e) {
handleException(e);
return null;
}
}
@Override
public ParcelFileDescriptor openDocument(String docId, String mode, CancellationSignal signal)
throws FileNotFoundException {
if (!"r".equals(mode)) {
throw new IllegalArgumentException("Media is read-only");
}
final Uri target = getUriForDocumentId(docId);
// Delegate to real provider
final long token = Binder.clearCallingIdentity();
try {
return getContext().getContentResolver().openFileDescriptor(target, mode);
} finally {
Binder.restoreCallingIdentity(token);
}
}
@Override
public Bundle getCache(String packageName, Uri key, int userId) {
enforceCrossUserPermission(userId, TAG);
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CACHE_CONTENT, TAG);
mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
packageName);
final String providerPackageName = getProviderPackageName(key);
final Pair<String, Uri> fullKey = Pair.create(packageName, key);
synchronized (mCache) {
final ArrayMap<Pair<String, Uri>, Bundle> cache = findOrCreateCacheLocked(userId,
providerPackageName);
return cache.get(fullKey);
}
}
@Override
public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
int[] ops) {
mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
Binder.getCallingPid(), Binder.getCallingUid(), null);
String resolvedPackageName = resolvePackageName(uid, packageName);
if (resolvedPackageName == null) {
return Collections.emptyList();
}
synchronized (this) {
Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, false /* edit */,
false /* uidMismatchExpected */);
if (pkgOps == null) {
return null;
}
ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
if (resOps == null) {
return null;
}
ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
pkgOps.packageName, pkgOps.uidState.uid, resOps);
res.add(resPackage);
return res;
}
}
@Override
public void requestSync(Account account, String authority, Bundle extras,
String callingPackage) {
Bundle.setDefusable(extras, true);
ContentResolver.validateSyncExtrasBundle(extras);
int userId = UserHandle.getCallingUserId();
final int callingUid = Binder.getCallingUid();
final int callingPid = Binder.getCallingPid();
validateExtras(callingUid, extras);
final int syncExemption = getSyncExemptionAndCleanUpExtrasForCaller(callingUid, extras);
// This makes it so that future permission checks will be in the context of this
// process rather than the caller's process. We will restore this before returning.
long identityToken = clearCallingIdentity();
try {
SyncManager syncManager = getSyncManager();
if (syncManager != null) {
syncManager.scheduleSync(account, userId, callingUid, authority, extras,
SyncStorageEngine.AuthorityInfo.UNDEFINED,
syncExemption, callingUid, callingPid, callingPackage);
}
} finally {
restoreCallingIdentity(identityToken);
}
}
@Override
public boolean isPlaybackActive(IMediaRouterClient client) {
if (client == null) {
throw new IllegalArgumentException("client must not be null");
}
final long token = Binder.clearCallingIdentity();
try {
ClientRecord clientRecord;
synchronized (mLock) {
clientRecord = mAllClientRecords.get(client.asBinder());
}
if (clientRecord != null) {
return mAudioPlayerStateMonitor.isPlaybackActive(clientRecord.mUid);
}
return false;
} finally {
Binder.restoreCallingIdentity(token);
}
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private static boolean checkOp(Context context, int op) {
final int version = Build.VERSION.SDK_INT;
if (version >= 19) {
AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
try {
Class clazz = AppOpsManager.class;
Method method = clazz.getDeclaredMethod("checkOp", int.class, int.class, String.class);
return AppOpsManager.MODE_ALLOWED == (int) method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName());
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
}
} else {
Log.e(TAG, "Below API 19 cannot invoke!");
}
return false;
}
@Override
public ParcelFileDescriptor openDocument(String docId, String mode, CancellationSignal signal)
throws FileNotFoundException {
if (!"r".equals(mode)) {
throw new IllegalArgumentException("Media is read-only");
}
final Uri target = getUriForDocumentId(docId);
// Delegate to real provider
final long token = Binder.clearCallingIdentity();
try {
return getContext().getContentResolver().openFileDescriptor(target, mode);
} finally {
Binder.restoreCallingIdentity(token);
}
}
public List<ResolveInfo> queryIntentActivities(Intent intent, String resolvedType, int flags) throws RemoteException {
waitForReadyInner();
try {
enforcePluginFileExists();
if (shouldNotBlockOtherInfo()) {
return IntentMatcher.resolveActivityIntent(this.mContext, this.mPluginCache, intent, resolvedType, flags);
}
List<String> pkgs = this.mActivityManagerService.getPackageNamesByPid(Binder.getCallingPid());
List<ResolveInfo> infos = new ArrayList();
for (String pkg : pkgs) {
intent.setPackage(pkg);
infos.addAll(IntentMatcher.resolveActivityIntent(this.mContext, this.mPluginCache, intent, resolvedType, flags));
}
if (infos != null) {
if (infos.size() > 0) {
return infos;
}
}
return null;
} catch (Exception e) {
handleException(e);
}
}
@Override
public List<ResolveInfo> queryIntentActivities(Intent intent, String resolvedType, int flags) throws RemoteException {
waitForReadyInner();
try {
enforcePluginFileExists();
if (shouldNotBlockOtherInfo()) {
return IntentMatcher.resolveActivityIntent(mContext, mPluginCache, intent, resolvedType, flags);
} else {
List<String> pkgs = mActivityManagerService.getPackageNamesByPid(Binder.getCallingPid());
List<ResolveInfo> infos = new ArrayList<ResolveInfo>();
for (String pkg : pkgs) {
intent.setPackage(pkg);
List<ResolveInfo> list = IntentMatcher.resolveActivityIntent(mContext, mPluginCache, intent, resolvedType, flags);
infos.addAll(list);
}
if (infos != null && infos.size() > 0) {
return infos;
}
}
} catch (Exception e) {
handleException(e);
}
return null;
}
@Override
public boolean setEnabledExclusiveInCategory(@Nullable String packageName, int userId)
throws RemoteException {
enforceChangeOverlayPackagesPermission("setEnabled");
userId = handleIncomingUser(userId, "setEnabled");
if (packageName == null) {
return false;
}
final long ident = Binder.clearCallingIdentity();
try {
synchronized (mLock) {
return mImpl.setEnabledExclusive(packageName, true /* withinCategory */,
userId);
}
} finally {
Binder.restoreCallingIdentity(ident);
}
}
@SuppressLint("NewApi")
private void notifyChange(final Uri uri) {
// If the calling user is different than current one, we need to post a
// task to notify change, otherwise, a system level hidden permission
// INTERACT_ACROSS_USERS_FULL is needed.
// The related APIs were added in API 17, it should be safe to fallback to
// normal way for notifying change, because caller can't be other users in
// devices whose API level is less than API 17.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
UserHandle callingUserHandle = Binder.getCallingUserHandle();
if (callingUserHandle != null
&& !callingUserHandle.equals(android.os.Process.myUserHandle())) {
ThreadUtils.postOnUiThread(new Runnable() {
@Override
public void run() {
getContext().getContentResolver().notifyChange(uri, null);
}
});
return;
}
}
getContext().getContentResolver().notifyChange(uri, null);
}
public String getStringUnchecked(String key, String defaultValue, int userId) {
if (Settings.Secure.LOCK_PATTERN_ENABLED.equals(key)) {
long ident = Binder.clearCallingIdentity();
try {
return mLockPatternUtils.isLockPatternEnabled(userId) ? "1" : "0";
} finally {
Binder.restoreCallingIdentity(ident);
}
}
if (userId == USER_FRP) {
return getFrpStringUnchecked(key);
}
if (LockPatternUtils.LEGACY_LOCK_PATTERN_ENABLED.equals(key)) {
key = Settings.Secure.LOCK_PATTERN_ENABLED;
}
return mStorage.readKeyValue(key, defaultValue, userId);
}
private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
final int parentId;
// Resolves dependency if setting has a dependency and the calling user has a parent
if (sSystemCloneFromParentOnDependency.containsKey(setting)
&& (parentId = getGroupParentLocked(userId)) != userId) {
// The setting has a dependency and the profile has a parent
String dependency = sSystemCloneFromParentOnDependency.get(setting);
// Lookup the dependency setting as ourselves, some callers may not have access to it.
final long token = Binder.clearCallingIdentity();
try {
Setting settingObj = getSecureSetting(dependency, userId);
if (settingObj != null && settingObj.getValue().equals("1")) {
return parentId;
}
} finally {
Binder.restoreCallingIdentity(token);
}
}
return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private static boolean checkOp(Context context, int op) {
final int version = Build.VERSION.SDK_INT;
if (version >= 19) {
AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
try {
Class clazz = AppOpsManager.class;
Method method = clazz.getDeclaredMethod("checkOp", int.class, int.class, String.class);
return AppOpsManager.MODE_ALLOWED == (int)method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName());
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
}
} else {
Log.e(TAG, "Below API 19 cannot invoke!");
}
return false;
}
private boolean post(Runnable runnable) {
int callingUid = Binder.getCallingUid();
if (callingUid != knownGoodUid) {
// TODO: Verify Gms is calling
String[] packagesForUid = getPackageManager().getPackagesForUid(callingUid);
if (packagesForUid != null) {
if (Arrays.asList(packagesForUid).contains(GMS_PACKAGE_NAME)) {
knownGoodUid = callingUid;
} else {
throw new SecurityException("Caller is not Services Core");
}
}
}
synchronized (lock) {
if (disconnected) {
return false;
}
serviceHandler.post(runnable);
return true;
}
}
private DatabaseHelper getOrEstablishDatabase(int callingUser) {
if (callingUser >= Process.SYSTEM_UID) {
if (USER_CHECK_THROWS) {
throw new IllegalArgumentException("Uid rather than user handle: " + callingUser);
} else {
Slog.wtf(TAG, "establish db for uid rather than user: " + callingUser);
}
}
long oldId = Binder.clearCallingIdentity();
try {
DatabaseHelper dbHelper;
synchronized (this) {
dbHelper = mOpenHelpers.get(callingUser);
}
if (null == dbHelper) {
establishDbTracking(callingUser);
synchronized (this) {
dbHelper = mOpenHelpers.get(callingUser);
}
}
return dbHelper;
} finally {
Binder.restoreCallingIdentity(oldId);
}
}
@Override
public void putCache(String packageName, Uri key, Bundle value, int userId) {
Bundle.setDefusable(value, true);
enforceCrossUserPermission(userId, TAG);
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CACHE_CONTENT, TAG);
mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
packageName);
final String providerPackageName = getProviderPackageName(key);
final Pair<String, Uri> fullKey = Pair.create(packageName, key);
synchronized (mCache) {
final ArrayMap<Pair<String, Uri>, Bundle> cache = findOrCreateCacheLocked(userId,
providerPackageName);
if (value != null) {
cache.put(fullKey, value);
} else {
cache.remove(fullKey);
}
}
}
@Override // Binder call
public ParceledListSlice<AmbientBrightnessDayStats> getAmbientBrightnessStats() {
mContext.enforceCallingOrSelfPermission(
Manifest.permission.ACCESS_AMBIENT_LIGHT_STATS,
"Permission required to to access ambient light stats.");
final int callingUid = Binder.getCallingUid();
final int userId = UserHandle.getUserId(callingUid);
final long token = Binder.clearCallingIdentity();
try {
synchronized (mSyncRoot) {
return mDisplayPowerController.getAmbientBrightnessStats(userId);
}
} finally {
Binder.restoreCallingIdentity(token);
}
}
@Override
public ParcelFileDescriptor openDocument(String docId, String mode, CancellationSignal signal)
throws FileNotFoundException {
if (!"r".equals(mode)) {
throw new IllegalArgumentException("Media is read-only");
}
final Uri target = getUriForDocumentId(docId);
// Delegate to real provider
final long token = Binder.clearCallingIdentity();
try {
return getContext().getContentResolver().openFileDescriptor(target, mode);
} finally {
Binder.restoreCallingIdentity(token);
}
}
@Override
public void createOverlayView(IBinder sessionToken, IBinder windowToken, Rect frame,
int userId) {
final int callingUid = Binder.getCallingUid();
final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
userId, "createOverlayView");
final long identity = Binder.clearCallingIdentity();
try {
synchronized (mLock) {
try {
getSessionLocked(sessionToken, callingUid, resolvedUserId)
.createOverlayView(windowToken, frame);
} catch (RemoteException | SessionNotFoundException e) {
Slog.e(TAG, "error in createOverlayView", e);
}
}
} finally {
Binder.restoreCallingIdentity(identity);
}
}
@Override // Binder call
public boolean isDreaming() {
checkPermission(android.Manifest.permission.READ_DREAM_STATE);
final long ident = Binder.clearCallingIdentity();
try {
return isDreamingInternal();
} finally {
Binder.restoreCallingIdentity(ident);
}
}
@Override
public Uri importTextMessage(String callingPkg, String address, int type, String text,
long timestampMillis, boolean seen, boolean read) throws RemoteException {
if (getAppOpsManager().noteOp(AppOpsManager.OP_WRITE_SMS, Binder.getCallingUid(),
callingPkg) != AppOpsManager.MODE_ALLOWED) {
// Silently fail AppOps failure due to not being the default SMS app
// while writing the TelephonyProvider
return FAKE_SMS_SENT_URI;
}
return getServiceGuarded().importTextMessage(
callingPkg, address, type, text, timestampMillis, seen, read);
}