下面列出了怎么用android.app.ActivityManagerNative的API类实例代码及写法,或者点击链接到github查看源代码。
public void setRunAsMonkey(boolean isSet) {
IActivityManager am = ActivityManagerNative.getDefault();
if (am == null) {
throw new RuntimeException(
"Can't manage monkey status; is the system running?");
}
try {
if (isSet) {
am.setActivityController(new DummyActivityController());
} else {
am.setActivityController(null);
}
} catch (RemoteException e) {
throw new RuntimeException(e);
}
}
public void initialize(ShellUiAutomatorBridge uiAutomatorBridge) {
mUiAutomationBridge = uiAutomatorBridge;
// 监听activity变化,用于getAct
try {
IActivityManager am = ActivityManagerNative.getDefault();
am.setActivityController(new DummyActivityController());
} catch (RemoteException e) {
}
UiAutomation uiAutomation = uiAutomatorBridge.getUiAutomation();
uiAutomation
.setOnAccessibilityEventListener(new OnAccessibilityEventListener() {
public void onAccessibilityEvent(AccessibilityEvent event) {
synchronized (onAccessibilityEventListeners) {
for (OnAccessibilityEventListener listener : onAccessibilityEventListeners) {
listener.onAccessibilityEvent(event);
}
}
}
});
}
/**
* hookSystemServices, but need to compatible with Android O in future.
*/
protected void hookSystemServices() {
try {
Singleton<IActivityManager> defaultSingleton;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
defaultSingleton = Reflector.on(ActivityManager.class).field("IActivityManagerSingleton").get();
} else {
defaultSingleton = Reflector.on(ActivityManagerNative.class).field("gDefault").get();
}
IActivityManager origin = defaultSingleton.get();
IActivityManager activityManagerProxy = (IActivityManager) Proxy.newProxyInstance(mContext.getClassLoader(), new Class[] { IActivityManager.class },
createActivityManagerProxy(origin));
// Hook IActivityManager from ActivityManagerNative
Reflector.with(defaultSingleton).field("mInstance").set(activityManagerProxy);
if (defaultSingleton.get() == activityManagerProxy) {
this.mActivityManager = activityManagerProxy;
Log.d(TAG, "hookSystemServices succeed : " + mActivityManager);
}
} catch (Exception e) {
Log.w(TAG, e);
}
}
/**
* Evicts a user's CE key by stopping and restarting the user.
*
* The key is evicted automatically by the user controller when the user has stopped.
*/
@Override
public void evictCredentialEncryptionKey(@UserIdInt int userId) {
checkManageUsersPermission("evict CE key");
final IActivityManager am = ActivityManagerNative.getDefault();
final long identity = Binder.clearCallingIdentity();
try {
am.restartUserInBackground(userId);
} catch (RemoteException re) {
throw re.rethrowAsRuntimeException();
} finally {
Binder.restoreCallingIdentity(identity);
}
}
public long getSystemLongPressTime() {
long longPressTimeout = 2000;
try {
IContentProvider provider = null;
Cursor cursor = null;
IActivityManager activityManager = ActivityManagerNative
.getDefault();
String providerName = Settings.Secure.CONTENT_URI.getAuthority();
IBinder token = new Binder();
try {
ContentProviderHolder holder = activityManager
.getContentProviderExternal(providerName,
UserHandle.USER_OWNER, token);
if (holder == null) {
throw new IllegalStateException("Could not find provider: "
+ providerName);
}
provider = holder.provider;
cursor = provider.query(null, Settings.Secure.CONTENT_URI,
new String[] { Settings.Secure.VALUE }, "name=?",
new String[] { Settings.Secure.LONG_PRESS_TIMEOUT },
null, null);
if (cursor.moveToFirst()) {
longPressTimeout = cursor.getInt(0);
}
} finally {
if (cursor != null) {
cursor.close();
}
if (provider != null) {
activityManager.removeContentProviderExternal(providerName,
token);
}
}
} catch (Throwable e) {
}
return longPressTimeout;
}
/**
* Sets the locale specified. Input data is the byte representation of a
* BCP-47 language tag. For backwards compatibility, strings of the form
* {@code ll_CC} are also accepted, where {@code ll} is a two letter language
* code and {@code CC} is a two letter country code.
*
* @param data the locale string in bytes.
*/
void setLocaleData(byte[] data, int size) {
// Check if locale was set by the user:
Configuration conf = mContext.getResources().getConfiguration();
// TODO: The following is not working as intended because the network is forcing a locale
// change after registering. Need to find some other way to detect if the user manually
// changed the locale
if (conf.userSetLocale) return; // Don't change if user set it in the SetupWizard
final String[] availableLocales = mContext.getAssets().getLocales();
// Replace "_" with "-" to deal with older backups.
String localeCode = new String(data, 0, size).replace('_', '-');
Locale loc = null;
for (int i = 0; i < availableLocales.length; i++) {
if (availableLocales[i].equals(localeCode)) {
loc = Locale.forLanguageTag(localeCode);
break;
}
}
if (loc == null) return; // Couldn't find the saved locale in this version of the software
try {
IActivityManager am = ActivityManagerNative.getDefault();
Configuration config = am.getConfiguration();
config.locale = loc;
// indicate this isn't some passing default - the user wants this remembered
config.userSetLocale = true;
am.updateConfiguration(config);
} catch (RemoteException e) {
// Intentionally left blank
}
}
@Override
public void inject() throws Throwable {
Field f_gDefault = ActivityManagerNative.class.getDeclaredField("gDefault");
if (!f_gDefault.isAccessible()) {
f_gDefault.setAccessible(true);
}
if (f_gDefault.getType() == IActivityManager.class) {
f_gDefault.set(null, getHookObject().getProxyObject());
} else if (f_gDefault.getType() == Singleton.class) {
Singleton gDefault = (Singleton) f_gDefault.get(null);
Field f_mInstance = Singleton.class.getDeclaredField("mInstance");
if (!f_mInstance.isAccessible()) {
f_mInstance.setAccessible(true);
}
f_mInstance.set(gDefault, getHookObject().getProxyObject());
} else {
// 不会经过这里
throw new UnsupportedOperationException("Singleton is not visible in AMN.");
}
HookBinder<IActivityManager> hookAMBinder = new HookBinder<IActivityManager>() {
@Override
protected IBinder queryBaseBinder() {
return ServiceManager.getService(Context.ACTIVITY_SERVICE);
}
@Override
protected IActivityManager createInterface(IBinder baseBinder) {
return getHookObject().getProxyObject();
}
};
hookAMBinder.injectService(Context.ACTIVITY_SERVICE);
}
@Override
protected final void doCall(Bundle b) throws RemoteException {
Intent intent = new Intent();
intent.setClassName(packageName, SERVICE);
intent.putExtras(b);
Log.i(TAG, "Invoking ActivityManagerNative.getDefault().startService(...)");
ActivityManagerNative.getDefault().startService(null, intent, null);
Log.i(TAG, "Intent sent!");
}
void setInputMethodLocked(String id, int subtypeId) {
InputMethodInfo info = mMethodMap.get(id);
if (info == null) {
throw new IllegalArgumentException("Unknown id: " + id);
}
// See if we need to notify a subtype change within the same IME.
if (id.equals(mCurMethodId)) {
final int subtypeCount = info.getSubtypeCount();
if (subtypeCount <= 0) {
return;
}
final InputMethodSubtype oldSubtype = mCurrentSubtype;
final InputMethodSubtype newSubtype;
if (subtypeId >= 0 && subtypeId < subtypeCount) {
newSubtype = info.getSubtypeAt(subtypeId);
} else {
// If subtype is null, try to find the most applicable one from
// getCurrentInputMethodSubtype.
newSubtype = getCurrentInputMethodSubtypeLocked();
}
if (newSubtype == null || oldSubtype == null) {
Slog.w(TAG, "Illegal subtype state: old subtype = " + oldSubtype
+ ", new subtype = " + newSubtype);
return;
}
if (newSubtype != oldSubtype) {
setSelectedInputMethodAndSubtypeLocked(info, subtypeId, true);
if (mCurMethod != null) {
try {
refreshImeWindowVisibilityLocked();
mCurMethod.changeInputMethodSubtype(newSubtype);
} catch (RemoteException e) {
Slog.w(TAG, "Failed to call changeInputMethodSubtype");
}
}
}
return;
}
// Changing to a different IME.
final long ident = Binder.clearCallingIdentity();
try {
// Set a subtype to this input method.
// subtypeId the name of a subtype which will be set.
setSelectedInputMethodAndSubtypeLocked(info, subtypeId, false);
// mCurMethodId should be updated after setSelectedInputMethodAndSubtypeLocked()
// because mCurMethodId is stored as a history in
// setSelectedInputMethodAndSubtypeLocked().
mCurMethodId = id;
if (ActivityManagerNative.isSystemReady()) {
Intent intent = new Intent(Intent.ACTION_INPUT_METHOD_CHANGED);
intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
intent.putExtra("input_method_id", id);
mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT);
}
unbindCurrentClientLocked();
} finally {
Binder.restoreCallingIdentity(ident);
}
}
public static IActivityManager getAMN() {
return ActivityManagerNative.getDefault();
}
@Override
protected Object getActivityManager() {
Log.i(TAG, "Invoking ActivityManagerNative.getDefault");
return ActivityManagerNative.getDefault();
}