下面列出了怎么用android.os.ServiceManager的API类实例代码及写法,或者点击链接到github查看源代码。
public static boolean open() {
IInputMethodManager mImm;
mImm = IInputMethodManager.Stub.asInterface(ServiceManager
.getService("input_method"));
try {
List<String> inputList = list();
for (int i = 0; i < inputList.size(); i++) {
String _id = inputList.get(i);
if (_id.contains("CmdInputService")) {
id = _id;
break;
}
}
mImm.setInputMethodEnabled(id, true);
mImm.setInputMethod(null, id);
return true;
} catch (RemoteException e) {
}
return false;
}
private void tryConnectToServiceLocked(IAccessibilityManager service) {
if (service == null) {
IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
if (iBinder == null) {
return;
}
service = IAccessibilityManager.Stub.asInterface(iBinder);
}
try {
final long userStateAndRelevantEvents = service.addClient(mClient, mUserId);
setStateLocked(IntPair.first(userStateAndRelevantEvents));
mRelevantEventTypes = IntPair.second(userStateAndRelevantEvents);
mService = service;
} catch (RemoteException re) {
Log.e(LOG_TAG, "AccessibilityManagerService is dead", re);
}
}
int runGetInactive(PrintWriter pw) throws RemoteException {
int userId = UserHandle.USER_CURRENT;
String opt;
while ((opt=getNextOption()) != null) {
if (opt.equals("--user")) {
userId = UserHandle.parseUserArg(getNextArgRequired());
} else {
getErrPrintWriter().println("Error: Unknown option: " + opt);
return -1;
}
}
String packageName = getNextArgRequired();
IUsageStatsManager usm = IUsageStatsManager.Stub.asInterface(ServiceManager.getService(
Context.USAGE_STATS_SERVICE));
boolean isIdle = usm.isAppInactive(packageName, userId);
pw.println("Idle=" + isIdle);
return 0;
}
static boolean setWifiAP(boolean enable, boolean doNotChangeWifi) {
//PPApplication.logE("CmdWifiAP.setWifiAP", "START enable="+enable);
//PPApplication.logE("CmdWifiAP.setWifiAP", "START doNotChangeWifi="+doNotChangeWifi);
final String packageName = PPApplication.PACKAGE_NAME;
try {
IConnectivityManager connectivityAdapter = IConnectivityManager.Stub.asInterface(ServiceManager.getService("connectivity")); // service list | grep IConnectivityManager
//PPApplication.logE("CmdWifiAP.setWifiAP", "connectivityAdapter="+connectivityAdapter);
if (enable) {
if (!doNotChangeWifi) {
IWifiManager wifiAdapter = IWifiManager.Stub.asInterface(ServiceManager.getService("wifi")); // service list | grep IWifiManager
//PPApplication.logE("CmdWifiAP.setWifiAP", "wifiAdapter="+wifiAdapter);
int wifiState = wifiAdapter.getWifiEnabledState();
boolean isWifiEnabled = ((wifiState == WifiManager.WIFI_STATE_ENABLED) || (wifiState == WifiManager.WIFI_STATE_ENABLING));
//PPApplication.logE("CmdWifiAP.setWifiAP", "isWifiEnabled="+isWifiEnabled);
if (isWifiEnabled)
wifiAdapter.setWifiEnabled(packageName, false);
}
ResultReceiver dummyResultReceiver = new ResultReceiver(null);
connectivityAdapter.startTethering(0, dummyResultReceiver, false, packageName);
} else {
connectivityAdapter.stopTethering(0, packageName);
}
//PPApplication.logE("CmdWifiAP.setWifiAP", "END=");
return true;
} catch (java.lang.SecurityException ee) {
//Log.e("CmdWifiAP.setWifiAP", Log.getStackTraceString(ee));
//PPApplication.logToCrashlytics("E/CmdWifiAP.setWifiAP: " + Log.getStackTraceString(ee));
//PPApplication.recordException(e);
//PPApplication.logE("CmdWifiAP.setWifiAP", Log.getStackTraceString(e));
return false;
} catch (Throwable e) {
//Log.e("CmdWifiAP.setWifiAP", Log.getStackTraceString(e));
PPApplication.recordException(e);
//PPApplication.logE("CmdWifiAP.setWifiAP", Log.getStackTraceString(e));
return false;
}
}
void systemReady() {
IVrManager vrManager = IVrManager.Stub.asInterface(
ServiceManager.getService(Context.VR_SERVICE));
if (vrManager != null) {
try {
vrManager.registerListener(mVrStateCallbacks);
mVrModeEnabled = vrManager.getVrModeState();
} catch (RemoteException re) {
}
}
}
/**
* Ensure that given directories exist, trying to create them if missing. If
* unable to create, they are filtered by replacing with {@code null}.
*/
private File[] ensureExternalDirsExistOrFilter(File[] dirs) {
File[] result = new File[dirs.length];
for (int i = 0; i < dirs.length; i++) {
File dir = dirs[i];
if (!dir.exists()) {
if (!dir.mkdirs()) {
// recheck existence in case of cross-process race
if (!dir.exists()) {
// Failing to mkdir() may be okay, since we might not have
// enough permissions; ask vold to create on our behalf.
final IStorageManager storageManager = IStorageManager.Stub.asInterface(
ServiceManager.getService("mount"));
try {
final int res = storageManager.mkdirs(
getPackageName(), dir.getAbsolutePath());
if (res != 0) {
Log.w(TAG, "Failed to ensure " + dir + ": " + res);
dir = null;
}
} catch (Exception e) {
Log.w(TAG, "Failed to ensure " + dir + ": " + e);
dir = null;
}
}
}
}
result[i] = dir;
}
return result;
}
private static void startDream(Context context, boolean docked) {
try {
IDreamManager dreamManagerService = IDreamManager.Stub.asInterface(
ServiceManager.getService(DreamService.DREAM_SERVICE));
if (dreamManagerService != null && !dreamManagerService.isDreaming()) {
if (docked) {
Slog.i(TAG, "Activating dream while docked.");
// Wake up.
// The power manager will wake up the system automatically when it starts
// receiving power from a dock but there is a race between that happening
// and the UI mode manager starting a dream. We want the system to already
// be awake by the time this happens. Otherwise the dream may not start.
PowerManager powerManager =
(PowerManager)context.getSystemService(Context.POWER_SERVICE);
powerManager.wakeUp(SystemClock.uptimeMillis(),
"android.service.dreams:DREAM");
} else {
Slog.i(TAG, "Activating dream by user request.");
}
// Dream.
dreamManagerService.dream();
}
} catch (RemoteException ex) {
Slog.e(TAG, "Could not start dream when docked.", ex);
}
}
@Override
public RttManager createService(ContextImpl ctx) throws ServiceNotFoundException {
IBinder b = ServiceManager.getServiceOrThrow(Context.WIFI_RTT_RANGING_SERVICE);
IWifiRttManager service = IWifiRttManager.Stub.asInterface(b);
return new RttManager(ctx.getOuterContext(),
new WifiRttManager(ctx.getOuterContext(), service));
}
public static List<String> list() {
List<String> ret = new ArrayList<String>();
IInputMethodManager mImm;
mImm = IInputMethodManager.Stub.asInterface(ServiceManager
.getService("input_method"));
try {
for (InputMethodInfo info : mImm.getInputMethodList()) {
ret.add(info.getId());
}
} catch (RemoteException e) {
}
return ret;
}
@Override
public DeviceIdleManager createService(ContextImpl ctx)
throws ServiceNotFoundException {
IDeviceIdleController service = IDeviceIdleController.Stub.asInterface(
ServiceManager.getServiceOrThrow(
Context.DEVICE_IDLE_CONTROLLER));
return new DeviceIdleManager(ctx.getOuterContext(), service);
}
private void runSet(OpsCommands.Builder builder) throws Throwable {
final int uid = Helper.getPackageUid(builder.getPackageName(), builder.getUserHandleId());
if (OtherOp.isOtherOp(builder.getOpInt())) {
setOther(builder, uid);
} else {
final IAppOpsService appOpsService = IAppOpsService.Stub.asInterface(
ServiceManager.getService(Context.APP_OPS_SERVICE));
appOpsService
.setMode(builder.getOpInt(), uid, builder.getPackageName(), builder.getModeInt());
}
}
public Object createService(ContextImpl ctx) {
IBinder b = ServiceManager.getService(POWER_SERVICE);
IPowerManager service = IPowerManager.Stub.asInterface(b);
if (service == null) {
Log.wtf(TAG, "Failed to get power manager service.");
}
return new PowerManager(ctx.getOuterContext(),
service, ctx.mMainThread.getHandler());
}
@Override
public WallpaperManager createService(ContextImpl ctx)
throws ServiceNotFoundException {
final IBinder b;
if (ctx.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.P) {
b = ServiceManager.getServiceOrThrow(Context.WALLPAPER_SERVICE);
} else {
b = ServiceManager.getService(Context.WALLPAPER_SERVICE);
}
IWallpaperManager service = IWallpaperManager.Stub.asInterface(b);
return new WallpaperManager(service, ctx.getOuterContext(),
ctx.mMainThread.getHandler());
}
private void connect() {
IBinder binder = ServiceManager.getService("installd");
if (binder != null) {
try {
binder.linkToDeath(new DeathRecipient() {
@Override
public void binderDied() {
Slog.w(TAG, "installd died; reconnecting");
connect();
}
}, 0);
} catch (RemoteException e) {
binder = null;
}
}
if (binder != null) {
mInstalld = IInstalld.Stub.asInterface(binder);
try {
invalidateMounts();
} catch (InstallerException ignored) {
}
} else {
Slog.w(TAG, "installd not found; trying again");
BackgroundThread.getHandler().postDelayed(() -> {
connect();
}, DateUtils.SECOND_IN_MILLIS);
}
}
static private INotificationManager getService() {
if (sService != null) {
return sService;
}
sService = INotificationManager.Stub.asInterface(ServiceManager
.getService("notification"));
return sService;
}
@Override
public WifiScanner createService(ContextImpl ctx) throws ServiceNotFoundException {
IBinder b = ServiceManager.getServiceOrThrow(Context.WIFI_SCANNING_SERVICE);
IWifiScanner service = IWifiScanner.Stub.asInterface(b);
return new WifiScanner(ctx.getOuterContext(), service,
ConnectivityThread.getInstanceLooper());
}
static DropBoxManager createDropBoxManager() {
IBinder b = ServiceManager.getService(DROPBOX_SERVICE);
IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b);
if (service == null) {
// Don't return a DropBoxManager that will NPE upon use.
// This also avoids caching a broken DropBoxManager in
// getDropBoxManager during early boot, before the
// DROPBOX_SERVICE is registered.
return null;
}
return new DropBoxManager(service);
}
public static IPackageManager getPackageManager() {
if (sPackageManager != null) {
//Slog.v("PackageManager", "returning cur default = " + sPackageManager);
return sPackageManager;
}
IBinder b = ServiceManager.getService("package");
//Slog.v("PackageManager", "default service binder = " + b);
sPackageManager = IPackageManager.Stub.asInterface(b);
//Slog.v("PackageManager", "default service = " + sPackageManager);
return sPackageManager;
}
/**
* Force the global system in or out of touch mode. This can be used if
* your instrumentation relies on the UI being in one more or the other
* when it starts.
*
* @param inTouch Set to true to be in touch mode, false to be in
* focus mode.
*/
public void setInTouchMode(boolean inTouch) {
try {
IWindowManager.Stub.asInterface(
ServiceManager.getService("window")).setInTouchMode(inTouch);
} catch (RemoteException e) {
// Shouldn't happen!
}
}
public SystemTextClassifier(Context context, TextClassificationConstants settings)
throws ServiceManager.ServiceNotFoundException {
mManagerService = ITextClassifierService.Stub.asInterface(
ServiceManager.getServiceOrThrow(Context.TEXT_CLASSIFICATION_SERVICE));
mSettings = Preconditions.checkNotNull(settings);
mFallback = context.getSystemService(TextClassificationManager.class)
.getTextClassifier(TextClassifier.LOCAL);
mPackageName = Preconditions.checkNotNull(context.getPackageName());
}
private static void bindService(Context context) {
synchronized (sServiceLock) {
if (sServiceInitialized) {
return;
}
sServiceInitialized = true;
PackageManager packageManager = context.getPackageManager();
if (!packageManager.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS)
&& !context.getResources().getBoolean(R.bool.config_enableAppWidgetService)) {
return;
}
IBinder b = ServiceManager.getService(Context.APPWIDGET_SERVICE);
sService = IAppWidgetService.Stub.asInterface(b);
}
}
private void setAutoRestore(boolean enabled) {
try {
IBackupManager bm = IBackupManager.Stub.asInterface(
ServiceManager.getService(Context.BACKUP_SERVICE));
if (bm != null) {
bm.setAutoRestore(enabled);
}
} catch (RemoteException e) {}
}
@Override
public AutofillManager createService(ContextImpl ctx) throws ServiceNotFoundException {
// Get the services without throwing as this is an optional feature
IBinder b = ServiceManager.getService(Context.AUTOFILL_MANAGER_SERVICE);
IAutoFillManager service = IAutoFillManager.Stub.asInterface(b);
return new AutofillManager(ctx.getOuterContext(), service);
}
public KeyguardStateMonitor(Context context, IKeyguardService service, StateCallback callback) {
mLockPatternUtils = new LockPatternUtils(context);
mCurrentUserId = ActivityManager.getCurrentUser();
mCallback = callback;
mKeystoreService = IKeystoreService.Stub.asInterface(ServiceManager
.getService("android.security.keystore"));
try {
service.addStateMonitorCallback(this);
} catch (RemoteException e) {
Slog.w(TAG, "Remote Exception", e);
}
}
/**
* Gets an instance of the input manager.
*
* @return The input manager instance.
*
* @hide
*/
public static InputManager getInstance() {
synchronized (InputManager.class) {
if (sInstance == null) {
try {
sInstance = new InputManager(IInputManager.Stub
.asInterface(ServiceManager.getServiceOrThrow(Context.INPUT_SERVICE)));
} catch (ServiceNotFoundException e) {
throw new IllegalStateException(e);
}
}
return sInstance;
}
}
public Object createService(ContextImpl ctx) {
IBinder b = ServiceManager.getService(POWER_SERVICE);
IPowerManager service = IPowerManager.Stub.asInterface(b);
if (service == null) {
Log.wtf(TAG, "Failed to get power manager service.");
}
return new PowerManager(ctx.getOuterContext(),
service, ctx.mMainThread.getHandler());
}
public static OtaDexoptService main(Context context,
PackageManagerService packageManagerService) {
OtaDexoptService ota = new OtaDexoptService(context, packageManagerService);
ServiceManager.addService("otadexopt", ota);
// Now it's time to check whether we need to move any A/B artifacts.
ota.moveAbArtifacts(packageManagerService.mInstaller);
return ota;
}
@Override
public CompanionDeviceManager createService(ContextImpl ctx)
throws ServiceNotFoundException {
ICompanionDeviceManager service = null;
// If the feature not present, don't try to look up every time
if (ctx.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_COMPANION_DEVICE_SETUP)) {
service = ICompanionDeviceManager.Stub.asInterface(
ServiceManager.getServiceOrThrow(Context.COMPANION_DEVICE_SERVICE));
}
return new CompanionDeviceManager(service, ctx.getOuterContext());
}
static DropBoxManager createDropBoxManager() {
IBinder b = ServiceManager.getService(DROPBOX_SERVICE);
IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b);
if (service == null) {
// Don't return a DropBoxManager that will NPE upon use.
// This also avoids caching a broken DropBoxManager in
// getDropBoxManager during early boot, before the
// DROPBOX_SERVICE is registered.
return null;
}
return new DropBoxManager(service);
}
public Object createService(ContextImpl ctx) {
IBinder b = ServiceManager.getService(PERSISTENT_DATA_BLOCK_SERVICE);
IPersistentDataBlockService persistentDataBlockService =
IPersistentDataBlockService.Stub.asInterface(b);
if (persistentDataBlockService != null) {
return new PersistentDataBlockManager(persistentDataBlockService);
} else {
// not supported
return null;
}
}