下面列出了怎么用android.os.ResultReceiver的API类实例代码及写法,或者点击链接到github查看源代码。
public static void startVoiceCall(@NonNull FragmentActivity activity, @NonNull Recipient recipient) {
if (TelephonyUtil.isAnyPstnLineBusy(activity)) {
Toast.makeText(activity,
R.string.CommunicationActions_a_cellular_call_is_already_in_progress,
Toast.LENGTH_SHORT)
.show();
return;
}
WebRtcCallService.isCallActive(activity, new ResultReceiver(new Handler(Looper.getMainLooper())) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (resultCode == 1) {
startCallInternal(activity, recipient, false);
} else {
new AlertDialog.Builder(activity)
.setMessage(R.string.CommunicationActions_start_voice_call)
.setPositiveButton(R.string.CommunicationActions_call, (d, w) -> startCallInternal(activity, recipient, false))
.setNegativeButton(R.string.CommunicationActions_cancel, (d, w) -> d.dismiss())
.setCancelable(true)
.show();
}
}
});
}
private void maybeProcessStartIntent() {
if (mStartIntent == null || mTorchStatus == TORCH_STATUS_UNKNOWN) return;
if (ACTION_TOGGLE_TORCH.equals(mStartIntent.getAction())) {
if (DEBUG) Log.d(TAG, "maybeProcessStartIntent: ACTION_TOGGLE_TORCH");
toggleTorch();
} else if (ACTION_TORCH_GET_STATUS.equals(mStartIntent.getAction())) {
if (DEBUG) Log.d(TAG, "maybeProcessStartIntent: " +
"ACTION_TORCH_GET_STATUS: mTorchStatus=" + mTorchStatus);
ResultReceiver receiver = mStartIntent.getParcelableExtra("receiver");
Bundle data = new Bundle();
data.putInt(EXTRA_TORCH_STATUS, mTorchStatus);
receiver.send(0, data);
}
mStartIntent = null;
}
@Override
protected void onHandleIntent(final Intent intent) {
int phase = intent.getIntExtra(INTENT_REQUESTED_PHASE, 0) & 0x03;
resultReceiver = (ResultReceiver) intent.getParcelableExtra(INTENT_RESULT_RECEIVER);
delayForInitDeviceFirmware = intent.getLongExtra(EXTRA_WAIT_FOR_INIT_DEVICE_FIRMWARE, 0);
int rc = 0;
logi("DFUBaseService onHandleIntent phase = " + phase);
mServicePhase = 0;
if ((phase & FLASHING_WITH_PAIR_CODE) != 0) {
mServicePhase = FLASHING_WITH_PAIR_CODE;
rc = flashingWithPairCode(intent);
}
if (resultReceiver != null) {
rc <<= 8;
resultReceiver.send(rc | phase, null);
}
}
public boolean sendMediaButton(String packageName, int pid, int uid,
boolean asSystemService, KeyEvent keyEvent, int sequenceId, ResultReceiver cb) {
try {
if (asSystemService) {
mCb.onMediaButton(mContext.getPackageName(), Process.myPid(),
Process.SYSTEM_UID, createMediaButtonIntent(keyEvent), sequenceId, cb);
} else {
mCb.onMediaButton(packageName, pid, uid,
createMediaButtonIntent(keyEvent), sequenceId, cb);
}
return true;
} catch (RemoteException e) {
Slog.e(TAG, "Remote failure in sendMediaRequest.", e);
}
return false;
}
/**
* Creates a proxy {@link ResultReceiver} which enables tethering if the provisioning result
* is successful before firing back up to the wrapped receiver.
*
* @param type The type of tethering being enabled.
* @param receiver A ResultReceiver which will be called back with an int resultCode.
* @return The proxy receiver.
*/
private ResultReceiver getProxyReceiver(final int type, final ResultReceiver receiver) {
ResultReceiver rr = new ResultReceiver(null) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
// If provisioning is successful, enable tethering, otherwise just send the error.
if (resultCode == TETHER_ERROR_NO_ERROR) {
enableTetheringInternal(type, true, receiver);
} else {
sendTetherResult(receiver, resultCode);
}
}
};
// The following is necessary to avoid unmarshalling issues when sending the receiver
// across processes.
Parcel parcel = Parcel.obtain();
rr.writeToParcel(parcel,0);
parcel.setDataPosition(0);
ResultReceiver receiverForSending = ResultReceiver.CREATOR.createFromParcel(parcel);
parcel.recycle();
return receiverForSending;
}
/**
* Request the record of {@link BluetoothActivityEnergyInfo} object that
* has the activity and energy info. This can be used to ascertain what
* the controller has been up to, since the last sample.
*
* A null value for the activity info object may be sent if the bluetooth service is
* unreachable or the device does not support reporting such information.
*
* @param result The callback to which to send the activity info.
* @hide
*/
public void requestControllerActivityEnergyInfo(ResultReceiver result) {
try {
mServiceLock.readLock().lock();
if (mService != null) {
mService.requestActivityInfo(result);
result = null;
}
} catch (RemoteException e) {
Log.e(TAG, "getControllerActivityEnergyInfoCallback: " + e);
} finally {
mServiceLock.readLock().unlock();
if (result != null) {
// Only send an immediate result if we failed.
result.send(0, null);
}
}
}
/**
* {@inheritDoc}
*/
@MainThread
@Override
public void hideSoftInput(int flags, ResultReceiver resultReceiver) {
if (DEBUG) Log.v(TAG, "hideSoftInput()");
boolean wasVis = isInputViewShown();
mShowInputFlags = 0;
mShowInputRequested = false;
doHideWindow();
clearInsetOfPreviousIme();
if (resultReceiver != null) {
resultReceiver.send(wasVis != isInputViewShown()
? InputMethodManager.RESULT_HIDDEN
: (wasVis ? InputMethodManager.RESULT_UNCHANGED_SHOWN
: InputMethodManager.RESULT_UNCHANGED_HIDDEN), null);
}
}
/** Returns Observable that will receive true if the keyboard is closed */
public static Single<Boolean> closeKeyboard(Activity activity) {
View view = activity.getCurrentFocus();
if (view != null) {
InputMethodManager imm =
(InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
return Single.create(
s -> {
imm.hideSoftInputFromWindow(
view.getWindowToken(),
0,
new ResultReceiver(null) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
s.onSuccess(resultCode == InputMethodManager.RESULT_HIDDEN);
super.onReceiveResult(resultCode, resultData);
}
});
});
} else {
return Single.just(false);
}
}
public void enterReady(Activity activity) {
if (mEnterActivityOptions == null || mIsEnterTriggered) {
return;
}
mIsEnterTriggered = true;
mHasExited = false;
ArrayList<String> sharedElementNames = mEnterActivityOptions.getSharedElementNames();
ResultReceiver resultReceiver = mEnterActivityOptions.getResultReceiver();
if (mEnterActivityOptions.isReturning()) {
restoreExitedViews();
activity.getWindow().getDecorView().setVisibility(View.VISIBLE);
}
mEnterTransitionCoordinator = new EnterTransitionCoordinator(activity,
resultReceiver, sharedElementNames, mEnterActivityOptions.isReturning(),
mEnterActivityOptions.isCrossTask());
if (mEnterActivityOptions.isCrossTask()) {
mExitingFrom = new ArrayList<>(mEnterActivityOptions.getSharedElementNames());
mExitingTo = new ArrayList<>(mEnterActivityOptions.getSharedElementNames());
}
if (!mIsEnterPostponed) {
startEnter();
}
}
UsbTransfer(ResultReceiver resultReceiver, Context context, UsbDevice usbDevice, UsbManager usbManager) throws Exception{
super(resultReceiver, context);
if (usbManager == null) {
finish();
return;
}
usbInterface = usbDevice.getInterface(0);
epIn = usbInterface.getEndpoint(0); // For bulk read
epOut = usbInterface.getEndpoint(1); // For bulk write
deviceConnection = usbManager.openDevice(usbDevice);
if ( ! deviceConnection.claimInterface(usbInterface, false)) {
issueDescription = "USB: failed to claim interface";
throw new Exception("USB: failed to claim interface");
}
}
GoldLeaf(ResultReceiver resultReceiver,
Context context,
UsbDevice usbDevice,
UsbManager usbManager,
ArrayList<NSPElement> nspElements) throws Exception {
super(resultReceiver, context, usbDevice, usbManager);
this.nspElements = nspElements;
String fileName;
InputStream fileInputStream;
fileInputStream = context.getContentResolver().openInputStream(nspElements.get(0).getUri());
fileName = nspElements.get(0).getFilename();
pfsElement = new PFSProvider(fileInputStream, fileName);
if (! pfsElement.init())
throw new Exception("GL File provided have incorrect structure and won't be uploaded.");
}
public static void requestPermissions(
final FlutterIncallManagerPlugin plugin,
final String[] permissions,
final Callback callback) {
requestPermissions(
plugin,
permissions,
new ResultReceiver(new Handler(Looper.getMainLooper())) {
@Override
protected void onReceiveResult(
int resultCode,
Bundle resultData) {
callback.invoke(
resultData.getStringArray(PERMISSIONS),
resultData.getIntArray(GRANT_RESULTS));
}
});
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_UNLOCK)) {
if (intent.getParcelableExtra("receiver") instanceof ResultReceiver) {
((ResultReceiver)intent.getParcelableExtra("receiver")).send(0, null);
}
Intent i = new Intent(context, UnlockActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
private void handleIsInCallQuery(Intent intent) {
ResultReceiver resultReceiver = intent.getParcelableExtra(EXTRA_RESULT_RECEIVER);
if (resultReceiver != null) {
resultReceiver.send(callState.get() != CallState.STATE_IDLE ? 1 : 0, null);
}
}
@Override // Binder call
public void onShellCommand(FileDescriptor in, FileDescriptor out,
FileDescriptor err, String[] args, ShellCallback callback,
ResultReceiver resultReceiver) {
final long token = Binder.clearCallingIdentity();
try {
DisplayManagerShellCommand command = new DisplayManagerShellCommand(this);
command.exec(this, in, out, err, args, callback, resultReceiver);
} finally {
Binder.restoreCallingIdentity(token);
}
}
private static void updateWifiConfig(ArrayList<WifiConfiguration> configList, ResultReceiver receiver) {
try {
WifiManager wm = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
for (WifiConfiguration c : configList) {
wm.updateNetwork(c);
}
wm.saveConfiguration();
if (receiver != null) {
receiver.send(0, null);
}
} catch (Throwable t) {
XposedBridge.log(t);
}
}
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) log("Broadcast received: " + intent.toString());
if (intent.getAction().equals(ACTION_SET_MOBILE_DATA_ENABLED)) {
final boolean enabled = intent.getBooleanExtra(EXTRA_ENABLED, false);
setMobileDataEnabled(enabled);
} else if (intent.getAction().equals(ACTION_TOGGLE_MOBILE_DATA)) {
changeMobileDataState(intent);
} else if (intent.getAction().equals(ACTION_TOGGLE_WIFI)) {
changeWifiState(intent);
} else if (intent.getAction().equals(ACTION_TOGGLE_BLUETOOTH)) {
changeBluetoothState(intent);
} else if (intent.getAction().equals(ACTION_TOGGLE_WIFI_AP)) {
changeWiFiApState(intent);
} else if (intent.getAction().equals(ACTION_SET_LOCATION_MODE)) {
setLocationMode(intent);
} else if (intent.getAction().equals(ACTION_TOGGLE_NFC)) {
changeNfcState(intent);
} else if (intent.getAction().equals(ACTION_GET_NFC_STATE)) {
if (intent.hasExtra("receiver")) {
sendNfcState((ResultReceiver)intent.getParcelableExtra("receiver"));
}
} else if (intent.getAction().equals(ACTION_TOGGLE_AIRPLANE_MODE)) {
changeAirplaneModeState(intent);
}
}
@Override
public void onShellCommand(FileDescriptor in, FileDescriptor out,
FileDescriptor err, String[] args, ShellCallback callback,
ResultReceiver resultReceiver) {
(new PowerManagerShellCommand(this)).exec(
this, in, out, err, args, callback, resultReceiver);
}
@Override
public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
String[] args, ShellCallback callback, ResultReceiver resultReceiver)
throws RemoteException {
enforceShell();
final long origId = Binder.clearCallingIdentity();
try {
(new LockSettingsShellCommand(mContext, new LockPatternUtils(mContext))).exec(
this, in, out, err, args, callback, resultReceiver);
} finally {
Binder.restoreCallingIdentity(origId);
}
}
public static void showIme(@NonNull View view) {
InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService
(Context.INPUT_METHOD_SERVICE);
// the public methods don't seem to work for me, so… reflection.
try {
Method showSoftInputUnchecked = InputMethodManager.class.getMethod(
"showSoftInputUnchecked", int.class, ResultReceiver.class);
showSoftInputUnchecked.setAccessible(true);
showSoftInputUnchecked.invoke(imm, 0, null);
} catch (Exception e) {
// ho hum
}
}
@Override
public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
enforceShell();
final long token = injectClearCallingIdentity();
try {
final int status = (new MyShellCommand()).exec(this, in, out, err, args, callback,
resultReceiver);
resultReceiver.send(status, null);
} finally {
injectRestoreCallingIdentity(token);
}
}
@Override
public void onShellCommand(@NonNull final FileDescriptor in,
@NonNull final FileDescriptor out, @NonNull final FileDescriptor err,
@NonNull final String[] args, @NonNull final ShellCallback callback,
@NonNull final ResultReceiver resultReceiver) {
(new OverlayManagerShellCommand(this)).exec(
this, in, out, err, args, callback, resultReceiver);
}
public void sendCommand(String packageName, int pid, int uid,
ISessionControllerCallback caller, String command, Bundle args, ResultReceiver cb) {
try {
mCb.onCommand(packageName, pid, uid, caller, command, args, cb);
} catch (RemoteException e) {
Slog.e(TAG, "Remote failure in sendCommand.", e);
}
}
public static Intent createPlayServiceIntent(Context context, String url, ChannelInfo channel,
boolean isVod, int vodLength, String vodId, int currentProgress,
Intent activityIntent, ResultReceiver audioOnlyReceiverDelegate) {
Intent playerService = new Intent(context, PlayerService.class);
playerService.putExtra(PlayerService.URL, url);
playerService.putExtra(PlayerService.STREAMER_INFO, channel);
playerService.putExtra(PlayerService.IS_VOD, isVod);
playerService.putExtra(PlayerService.VOD_LENGTH, vodLength);
playerService.putExtra(PlayerService.VOD_ID, vodId);
playerService.putExtra(PlayerService.VOD_PROGRESS, currentProgress);
playerService.putExtra(PlayerService.INTENT, activityIntent);
playerService.putExtra(PlayerService.RECEIVER_DELEGATE, audioOnlyReceiverDelegate);
return playerService;
}
/**
* Enables or disables tethering for the given type. This should only be called once
* provisioning has succeeded or is not necessary. It will also schedule provisioning rechecks
* for the specified interface.
*/
private void enableTetheringInternal(int type, boolean enable, ResultReceiver receiver) {
boolean isProvisioningRequired = enable && isTetherProvisioningRequired();
int result;
switch (type) {
case TETHERING_WIFI:
result = setWifiTethering(enable);
if (isProvisioningRequired && result == TETHER_ERROR_NO_ERROR) {
scheduleProvisioningRechecks(type);
}
sendTetherResult(receiver, result);
break;
case TETHERING_USB:
result = setUsbTethering(enable);
if (isProvisioningRequired && result == TETHER_ERROR_NO_ERROR) {
scheduleProvisioningRechecks(type);
}
sendTetherResult(receiver, result);
break;
case TETHERING_BLUETOOTH:
setBluetoothTethering(enable, receiver);
break;
default:
Log.w(TAG, "Invalid tether type.");
sendTetherResult(receiver, TETHER_ERROR_UNKNOWN_IFACE);
}
}
private void sendUiTetherProvisionIntent(int type, ResultReceiver receiver) {
Intent intent = new Intent(Settings.ACTION_TETHER_PROVISIONING);
intent.putExtra(EXTRA_ADD_TETHER_TYPE, type);
intent.putExtra(EXTRA_PROVISION_CALLBACK, receiver);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
final long ident = Binder.clearCallingIdentity();
try {
mContext.startActivityAsUser(intent, UserHandle.CURRENT);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
private void sendSilentTetherProvisionIntent(int type, ResultReceiver receiver) {
Intent intent = new Intent();
intent.putExtra(EXTRA_ADD_TETHER_TYPE, type);
intent.putExtra(EXTRA_RUN_PROVISION, true);
intent.putExtra(EXTRA_PROVISION_CALLBACK, receiver);
intent.setComponent(TETHER_SERVICE);
final long ident = Binder.clearCallingIdentity();
try {
mContext.startServiceAsUser(intent, UserHandle.CURRENT);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
@Override
public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
if (!isCallerShell()) {
Slog.w(TAG, "Only shell is allowed to call network watchlist shell commands");
return;
}
(new NetworkWatchlistShellCommand(this, mContext)).exec(this, in, out, err, args, callback,
resultReceiver);
}
public static void showIme(@NonNull View view) {
InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService
(Context.INPUT_METHOD_SERVICE);
// the public methods don't seem to work for me, so… reflection.
try {
Method showSoftInputUnchecked = InputMethodManager.class.getMethod(
"showSoftInputUnchecked", int.class, ResultReceiver.class);
showSoftInputUnchecked.setAccessible(true);
showSoftInputUnchecked.invoke(imm, 0, null);
} catch (Exception e) {
// ho hum
}
}
void dumpImpl(FileDescriptor fd, PrintWriter _pw, String[] args) {
final IndentingPrintWriter pw = new IndentingPrintWriter(_pw, " ");
if (args == null || args.length == 0 || "-a".equals(args[0])) {
pw.println("Known volumes:");
pw.increaseIndent();
for (int i = 0; i < mStates.size(); i++) {
final UUID uuid = mStates.keyAt(i);
final State state = mStates.valueAt(i);
if (StorageManager.UUID_DEFAULT.equals(uuid)) {
pw.println("Default:");
} else {
pw.println(uuid + ":");
}
pw.increaseIndent();
pw.printPair("level", State.levelToString(state.level));
pw.printPair("lastUsableBytes", state.lastUsableBytes);
pw.println();
pw.decreaseIndent();
}
pw.decreaseIndent();
pw.println();
pw.printPair("mSeq", mSeq.get());
pw.printPair("mForceState", State.levelToString(mForceLevel));
pw.println();
pw.println();
} else {
Shell shell = new Shell();
shell.exec(mRemoteService, null, fd, null, args, null, new ResultReceiver(null));
}
}