1 /*
2  * Copyright (C) 2015 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 
17 package com.android.commands.monkey;
18 
19 import android.app.ActivityManager;
20 import android.app.IActivityManager;
21 import android.content.pm.IPackageManager;
22 import android.content.pm.PackageManager;
23 import android.content.pm.PermissionInfo;
24 import android.os.RemoteException;
25 import android.os.ServiceManager;
26 import android.view.IWindowManager;
27 
28 public class MonkeyPermissionEvent extends MonkeyEvent {
29     private String mPkg;
30     private PermissionInfo mPermissionInfo;
31 
MonkeyPermissionEvent(String pkg, PermissionInfo permissionInfo)32     public MonkeyPermissionEvent(String pkg, PermissionInfo permissionInfo) {
33         super(EVENT_TYPE_PERMISSION);
34         mPkg = pkg;
35         mPermissionInfo = permissionInfo;
36     }
37 
38     @Override
injectEvent(IWindowManager iwm, IActivityManager iam, int verbose)39     public int injectEvent(IWindowManager iwm, IActivityManager iam, int verbose) {
40         IPackageManager pm = IPackageManager.Stub.asInterface(ServiceManager.getService("package"));
41         int currentUser = ActivityManager.getCurrentUser();
42         try {
43             // determine if we should grant or revoke permission
44             int perm = pm.checkPermission(mPermissionInfo.name, mPkg, currentUser);
45             boolean grant = perm == PackageManager.PERMISSION_DENIED;
46             // log before calling pm in case we hit an error
47             Logger.out.println(String.format(":Permission %s %s to package %s",
48                     grant ? "grant" : "revoke", mPermissionInfo.name, mPkg));
49             if (grant) {
50                 pm.grantRuntimePermission(mPkg, mPermissionInfo.name, currentUser);
51             } else {
52                 pm.revokeRuntimePermission(mPkg, mPermissionInfo.name, currentUser);
53             }
54             return MonkeyEvent.INJECT_SUCCESS;
55         } catch (RemoteException re) {
56             return MonkeyEvent.INJECT_ERROR_REMOTE_EXCEPTION;
57         }
58     }
59 }
60