下面列出了怎么用android.os.IBinder的API类实例代码及写法,或者点击链接到github查看源代码。
public void onServiceConnected(ComponentName className, IBinder service) {
mService = new Messenger(service);
try {
//Register client with service
Message msg = Message.obtain(null, NTRIPService.MSG_REGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
//Request a status update.
msg = Message.obtain(null, NTRIPService.MSG_UPDATE_STATUS, 0, 0);
mService.send(msg);
//Request full log from service.
msg = Message.obtain(null, NTRIPService.MSG_UPDATE_LOG_FULL, 0, 0);
mService.send(msg);
SetSettings();
NTrip.this.onServiceConnected();
} catch (RemoteException e) {
// In this case the service has crashed before we could even do anything with it
}
}
@Override
public void unblockContent(
IBinder sessionToken, String unblockedRating, int userId) {
ensureParentalControlsPermission();
final int callingUid = Binder.getCallingUid();
final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
userId, "unblockContent");
final long identity = Binder.clearCallingIdentity();
try {
synchronized (mLock) {
try {
getSessionLocked(sessionToken, callingUid, resolvedUserId)
.unblockContent(unblockedRating);
} catch (RemoteException | SessionNotFoundException e) {
Slog.e(TAG, "error in unblockContent", e);
}
}
} finally {
Binder.restoreCallingIdentity(identity);
}
}
private void setSystemAnimationsScale(float animationScale) {
try {
Class<?> windowManagerStubClazz = Class.forName("android.view.IWindowManager$Stub");
Method asInterface = windowManagerStubClazz.getDeclaredMethod("asInterface", IBinder.class);
Class<?> serviceManagerClazz = Class.forName("android.os.ServiceManager");
Method getService = serviceManagerClazz.getDeclaredMethod("getService", String.class);
Class<?> windowManagerClazz = Class.forName("android.view.IWindowManager");
Method setAnimationScales = windowManagerClazz.getDeclaredMethod("setAnimationScales", float[].class);
Method getAnimationScales = windowManagerClazz.getDeclaredMethod("getAnimationScales");
IBinder windowManagerBinder = (IBinder) getService.invoke(null, "window");
Object windowManagerObj = asInterface.invoke(null, windowManagerBinder);
float[] currentScales = (float[]) getAnimationScales.invoke(windowManagerObj);
for (int i = 0; i < currentScales.length; i++) {
currentScales[i] = animationScale;
}
setAnimationScales.invoke(windowManagerObj, new Object[]{currentScales});
} catch (Exception e) {
Log.e("SystemAnimations", "Could not change animation scale to " + animationScale + " :'(");
}
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
hasConnected = true;
mControl = IPlayControl.Stub.asInterface(service);
try {
mControl.registerOnPlayStatusChangedListener(mPlayStatusChangedListener);
mControl.registerOnSongChangedListener(mSongChangedListener);
mControl.registerOnPlayListChangedListener(mPlayListChangedListener);
mControl.registerOnDataIsReadyListener(mDataIsReadyListener);
} catch (RemoteException e) {
e.printStackTrace();
}
serviceConnect.onConnected(name, service);
}
private void switchIME() {
//final String LATIN = "com.android.inputmethod.latin/.LatinIME";
// 'this' is an InputMethodService
try {
InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
final IBinder token = Objects.requireNonNull(this.getWindow().getWindow()).getAttributes().token;
//imm.setInputMethod(token, LATIN);
imm.switchToNextInputMethod(token, false);
} catch (Throwable t) { // java.lang.NoSuchMethodError if API_level<11
mInputMethodManager.showInputMethodPicker();
Log.e(TAG, "cannot set the previous input method:");
t.printStackTrace();
}
}
public LuaValue hideKeyboard(U target, Varargs varargs) {
View view = target.getView();
if (view == null) {
return this;
}
Context context = view.getContext();
if (context instanceof Activity) {
View v = ((Activity) context).getCurrentFocus();
if (v != null) {
IBinder token = v.getWindowToken();
if (token != null) {
InputMethodManager im = (InputMethodManager) context.getSystemService
(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
return this;
}
@Override
public void stopRecording(IBinder sessionToken, int userId) {
final int callingUid = Binder.getCallingUid();
final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
userId, "stopRecording");
final long identity = Binder.clearCallingIdentity();
try {
synchronized (mLock) {
try {
getSessionLocked(sessionToken, callingUid, resolvedUserId).stopRecording();
} catch (RemoteException | SessionNotFoundException e) {
Slog.e(TAG, "error in stopRecording", e);
}
}
} finally {
Binder.restoreCallingIdentity(identity);
}
}
/**
* @param context
* @return
* @throws RemoteException
*/
public static final IPref getPref(Context context) throws RemoteException {
if (sPref == null) {
if (IPC.isPersistentProcess()) {
// 需要枷锁否?
initPref();
} else {
IBinder b = PluginProviderStub.proxyFetchHostPref(context);
b.linkToDeath(new DeathRecipient() {
@Override
public void binderDied() {
sPref = null;
}
}, 0);
sPref = IPref.Stub.asInterface(b);
}
}
return sPref;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
super.onServiceConnected(name, service);
backend = LocationBackend.Stub.asInterface(service);
if (backend != null) {
try {
backend.open(callback);
if (updateWaiting) {
update();
}
} catch (Exception e) {
Log.w(TAG, e);
unbind();
}
}
}
@Override
public IBinder onBind(Intent intent) {
// We call stopSelf() to request that this service be stopped as soon as the client
// unbinds. Otherwise the system may keep it around and available for a reconnect. The
// child processes do not currently support reconnect; they must be initialized from
// scratch every time.
stopSelf();
synchronized (mMainThread) {
mCommandLineParams = intent.getStringArrayExtra(
ChildProcessConnection.EXTRA_COMMAND_LINE);
mLinkerParams = null;
if (Linker.isUsed())
mLinkerParams = new LinkerParams(intent);
mIsBound = true;
mMainThread.notifyAll();
}
return mBinder;
}
void onActivityResumed(int userId, IBinder token) {
synchronized (mHistory) {
optimizeTasksLocked();
ActivityRecord r = findActivityByToken(userId, token);
if (r != null) {
synchronized (r.task.activities) {
r.task.activities.remove(r);
r.task.activities.add(r);
}
}
}
}
public static void scheduleCreateService(IInterface appThread, IBinder token, ServiceInfo info,
int processState) throws RemoteException {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
IApplicationThreadKitkat.scheduleCreateService.call(appThread, token, info, CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO.get(),
processState);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
IApplicationThreadICSMR1.scheduleCreateService.call(appThread, token, info, CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO.get());
} else {
IApplicationThread.scheduleCreateService.call(appThread, token, info);
}
}
/**
* Request to hide the soft input window from the context of the window that is currently accepting input.
* This should be called as a result of the user doing some actually than fairly explicitly requests to have the input window hidden.
*
* @param view the current focused view
*/
public static boolean hideSoftInputFromWindow(View view) {
boolean result = false;
if (view != null) {
Context context = view.getContext();
IBinder windowToken = view.getWindowToken();
InputMethodManager inputMethodManager = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
result = inputMethodManager.hideSoftInputFromWindow(windowToken, 0);
}
return result;
}
public void onServiceConnected(ComponentName className, IBinder binderService) {
weatherByVoiceService = new Messenger(binderService);
weatherByVoiceServiceLock.lock();
try {
while (!weatherByvOiceUnsentMessages.isEmpty()) {
weatherByVoiceService.send(weatherByvOiceUnsentMessages.poll());
}
} catch (RemoteException e) {
appendLog(getBaseContext(), TAG, e.getMessage(), e);
} finally {
weatherByVoiceServiceLock.unlock();
}
}
@Test
public void testBoundService() throws TimeoutException {
IBinder binder = myServiceRule.bindService(
new Intent(InstrumentationRegistry.getTargetContext(), SampleService.class));
SampleService service = ((SampleService.LocalBinder) binder).getService();
// Do work with the service
assertNotNull("Bound service is null", service);
}
/**
* This method is used to hide a keyboard after a user has
* finished typing the url.
*/
public static void hideKeyboard(Activity activity,
IBinder windowToken) {
InputMethodManager mgr =
(InputMethodManager) activity.getSystemService
(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(windowToken, 0);
}
public void onServiceConnected(ComponentName className, IBinder service) {
Log.d(TAG, "DLNA-----DlnaAndRemoteSearch---onServiceConnected");
mUpnpService = (AndroidUpnpService) service;
mUpnpService.getControlPoint().getRegistry().removeAllRemoteDevices();// 先清除掉之前的,再搜索
mUpnpService.getRegistry().addListener(mDefaultRegistryListener);
mUpnpService.getControlPoint().search();
}
public void connected(ComponentName name, IBinder service, boolean dead)
throws RemoteException {
LoadedApk.ServiceDispatcher sd = mDispatcher.get();
if (sd != null) {
sd.connected(name, service, dead);
}
}
@Override
public void sendTimestamp(IBinder token, long timestamp) throws RemoteException {
Connection connection = mConnectionRef.get();
if (connection != null) {
connection.sendTimestamp(token, timestamp);
}
}
@Override
public IModule query(Class<? extends IModule> c) {
IBinder b = null;
try {
b = mPlugin.query(c.getName());
} catch (Throwable e) {
if (LOGR) {
LogRelease.e(PLUGIN_TAG, "query(" + c + ") exception: " + e.getMessage(), e);
}
}
// TODO: return IModule
return null;
}
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
grblUsbSerialService = ((GrblUsbSerialService.UsbSerialBinder) service).getService();
mBound = true;
grblUsbSerialService.setMessageHandler(grblServiceMessageHandler);
grblUsbSerialService.setStatusUpdatePoolInterval(Long.valueOf(sharedPref.getString(getString(R.string.preference_update_pool_interval), String.valueOf(Constants.GRBL_STATUS_UPDATE_INTERVAL))));
}
public void showSubtypeSwitchDialog() {
// prepare dialog
final Dialog dialog = new Dialog(
DialogUtils.getPlatformDialogThemeContext(this),
R.style.CustomDialogTheme
);
SubtypeSwitchDialogView dialogView = (SubtypeSwitchDialogView) getLayoutInflater().inflate(R.layout.subtype_switch, null);
dialogView.setListener(this);
dialog.setContentView(dialogView);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
// show dialog
final IBinder windowToken = KeyboardSwitcher.getInstance().getMainKeyboardView().getWindowToken();
if (windowToken == null) {
return;
}
final Window window = dialog.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
window.setNavigationBarColor(Color.TRANSPARENT);
}
WindowManager.LayoutParams lp = window.getAttributes();
lp.token = windowToken;
lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
mSubtypeSwitchDialog = dialog;
dialog.show();
}
/**
* Cast an IBinder object into an ILicenseResultListener interface,
* generating a proxy if needed.
*/
public static com.google.android.vending.licensing.ILicenseResultListener asInterface(android.os.IBinder obj) {
if ((obj == null)) {
return null;
}
android.os.IInterface iin = (android.os.IInterface) obj.queryLocalInterface(DESCRIPTOR);
if (((iin != null) && (iin instanceof com.google.android.vending.licensing.ILicenseResultListener))) {
return ((com.google.android.vending.licensing.ILicenseResultListener) iin);
}
return new com.google.android.vending.licensing.ILicenseResultListener.Stub.Proxy(obj);
}
@Override
public void write(IBinder clientToken, WriteData writeData) {
if (clientToken == null) {
LogUtils.log(SelfBrailleService.this, Log.ERROR,
"null client token to write");
return;
}
ServiceUtil serviceUtil = new ServiceUtil(mPackageManager);
if (!serviceUtil.verifyCaller(Binder.getCallingUid())) {
LogUtils.log(SelfBrailleService.this, Log.ERROR,
"non-google signed package try to invoke service, rejected.");
return;
}
if (writeData == null) {
LogUtils.log(SelfBrailleService.this, Log.ERROR,
"null writeData to write");
return;
}
LogUtils.log(SelfBrailleService.this, Log.VERBOSE,
"write %s, %s", writeData.getText(),
writeData.getAccessibilityNodeInfo());
try {
writeData.validate();
} catch (IllegalStateException ex) {
LogUtils.log(SelfBrailleService.this, Log.ERROR,
"Invalid write data: %s", ex);
return;
}
NodeState state = new NodeState();
state.mClientToken = clientToken;
state.mWriteData = writeData;
mHandler.setNodeState(state);
}
public ActivityResult execStartActivityAsCaller(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options, int userId) {
PluginIntentResolver.resolveActivity(intent);
return hackInstrumentation.execStartActivityAsCaller(who, contextThread, token, target, intent, requestCode, options, userId);
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//实例化Service的内部类myBinder
// 通过向下转型得到了MyBinder的实例
socketBinder = (SocketService.SocketBinder) service;
//在Activity调用Service类的方法
socketBinder.service_connect_Activity();
socketBinder.addNewOrderInterface(MainActivity.this);
}
public int bindService(IApplicationThread caller, IBinder token,
Intent service, String resolvedType,
IServiceConnection connection, int flags, int userId) {
token = getActivityToken(token);
RemapingUtil.remapServiceIntent(mHostContext, service);
if (userId == INVALID_USER_ID) {
return mTarget.bindService(caller, token, service, resolvedType, connection, flags);
} else {
return mTarget.bindService(caller, token, service, resolvedType, connection, flags, userId);
}
}
@Override
protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
if (code == IBinder.LAST_CALL_TRANSACTION) {
onRevoke();
return true;
}
return false;
}
public boolean unpin(String pkg, IBinder token) {
synchronized (mLock) {
token.unlinkToDeath(mDeathRecipient, 0);
mListeners.remove(token);
}
return !hasPinOrListener();
}
public static void onDestroyActivity(IBinder token) {
mPreventRunning.onDestroyActivity(forToken(token));
}