下面列出了android.content.Intent#getByteArrayExtra ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* <p>Call this from your {@link Activity}'s
* {@link Activity#onActivityResult(int, int, Intent)} method.</p>
*
* @param requestCode request code from {@code onActivityResult()}
* @param resultCode result code from {@code onActivityResult()}
* @param intent {@link Intent} from {@code onActivityResult()}
* @return null if the event handled here was not related to this class, or
* else an {@link IntentResult} containing the result of the scan. If the user cancelled scanning,
* the fields will be null.
*/
public static IntentResult parseActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String formatName = intent.getStringExtra("SCAN_RESULT_FORMAT");
byte[] rawBytes = intent.getByteArrayExtra("SCAN_RESULT_BYTES");
int intentOrientation = intent.getIntExtra("SCAN_RESULT_ORIENTATION", Integer.MIN_VALUE);
Integer orientation = intentOrientation == Integer.MIN_VALUE ? null : intentOrientation;
String errorCorrectionLevel = intent.getStringExtra("SCAN_RESULT_ERROR_CORRECTION_LEVEL");
return new IntentResult(contents,
formatName,
rawBytes,
orientation,
errorCorrectionLevel);
}
return new IntentResult();
}
return null;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ACTIVITY_RESULT_SCAN){
if (data != null){
String result = data.getStringExtra("result");
mResultTextView.setText(result);
Bitmap barcode = null;
byte[] compressedBitmap = data.getByteArrayExtra("resultByte");
if (compressedBitmap != null) {
barcode = BitmapFactory.decodeByteArray(compressedBitmap, 0, compressedBitmap.length, null);
barcode = barcode.copy(Bitmap.Config.RGB_565, true);
mQRCodeImage.setImageBitmap(barcode);
}
}else {
mResultTextView.setText("没有结果!!!");
}
}
}
/**
* Returns a valid {@link ListenerUpcall} from {@code intent}, or {@code null} if one
* could not be parsed.
*/
private ListenerUpcall tryParseIntent(Intent intent) {
if (intent == null) {
return null;
}
byte[] upcallBytes = intent.getByteArrayExtra(ProtocolIntents.LISTENER_UPCALL_KEY);
if (upcallBytes == null) {
return null;
}
try {
ListenerUpcall upcall = ListenerUpcall.parseFrom(upcallBytes);
if (!validator.isListenerUpcallValid(upcall)) {
logger.warning("Ignoring invalid listener upcall: %s", upcall);
return null;
}
return upcall;
} catch (InvalidProtocolBufferException exception) {
logger.severe("Could not parse listener upcall from %s", Arrays.toString(upcallBytes));
return null;
}
}
private void checkBroadcastResponse(ByteString expectedResponseBytes)
throws InvalidProtocolBufferException {
List<Intent> broadcasts =
Shadows.shadowOf(RuntimeEnvironment.application).getBroadcastIntents();
assertThat(broadcasts.size()).isEqualTo(1);
Intent broadcastIntent = broadcasts.get(0);
assertThat(broadcastIntent.getAction())
.isEqualTo("example:0000000000000080");
assertThat(broadcastIntent.getCategories()).containsExactly(QueryUtil.BBQ_CATEGORY);
assertThat(broadcastIntent.getPackage()).isEqualTo(mQuery.getRequestingApp());
assertThat(broadcastIntent.getByteArrayExtra(QueryUtil.EXTRA_RESPONSE_MESSAGE)).isNotNull();
byte[] responseBytes = broadcastIntent.getByteArrayExtra(QueryUtil.EXTRA_RESPONSE_MESSAGE);
BroadcastQueryResponse response = BroadcastQueryResponse.parseFrom(responseBytes);
assertThat(response.getRequestId()).isEqualTo(mQuery.getRequestId());
assertThat(response.getResponseId()).isEqualTo(mQuery.getResponseId());
assertThat(response.getResponseMessage()).isEqualTo(expectedResponseBytes);
}
@Test
public void toResultIntentData() throws Exception {
HintRetrieveResult result = new HintRetrieveResult.Builder(
HintRetrieveResult.CODE_HINT_SELECTED)
.setHint(HINT)
.setAdditionalProperties(ValidAdditionalProperties.make())
.build();
Intent intent = result.toResultDataIntent();
assertThat(intent.hasExtra(ProtocolConstants.EXTRA_HINT_RESULT));
byte[] data = intent.getByteArrayExtra(ProtocolConstants.EXTRA_HINT_RESULT);
HintRetrieveResult readResult = HintRetrieveResult.fromProtobufBytes(data);
assertThat(readResult.getResultCode()).isEqualTo(HintRetrieveResult.CODE_HINT_SELECTED);
assertThat(readResult.getHint()).isNotNull();
ValidAdditionalProperties.assertEquals(readResult.getAdditionalProperties());
}
/**
* Returns a valid {@link ListenerUpcall} from {@code intent}, or {@code null} if one
* could not be parsed.
*/
private ListenerUpcall tryParseIntent(Intent intent) {
if (intent == null) {
return null;
}
byte[] upcallBytes = intent.getByteArrayExtra(ProtocolIntents.LISTENER_UPCALL_KEY);
if (upcallBytes == null) {
return null;
}
try {
ListenerUpcall upcall = ListenerUpcall.parseFrom(upcallBytes);
return upcall;
} catch (ValidationException exception) {
logger.severe("Could not parse listener upcall from %s", Arrays.toString(upcallBytes));
return null;
}
}
private void handleMessage(Intent intent) {
numGcmMessagesForTest.incrementAndGet();
String clientKey = intent.getStringExtra(MESSAGE_CLIENT_KEY);
AndroidClientProxy proxy = clientManager.get(clientKey);
// Client is unknown or unstarted; we can't deliver the message, but we need to
// remember that we dropped it if the client is known.
if ((proxy == null) || !proxy.isStarted()) {
logger.warning("Dropping GCM message for unknown or unstarted client: %s", clientKey);
handleGcmMessageForUnstartedClient(proxy);
return;
}
// We can deliver the message. Pass the new echo token to the channel.
String echoToken = intent.getStringExtra(MESSAGE_ECHO);
logger.fine("Update %s with new echo token: %s", clientKey, echoToken);
proxy.getChannel().updateEchoToken(echoToken);
byte [] message = intent.getByteArrayExtra(MESSAGE_DATA);
if (message != null) {
logger.fine("Deliver to %s message %s", clientKey, message);
proxy.getChannel().receiveMessage(message);
} else {
logger.severe("Got mailbox intent: %s", intent);
}
}
/**
* <p>Call this from your {@link Activity}'s
* {@link Activity#onActivityResult(int, int, Intent)} method.</p>
*
* @param requestCode request code from {@code onActivityResult()}
* @param resultCode result code from {@code onActivityResult()}
* @param intent {@link Intent} from {@code onActivityResult()}
* @return null if the event handled here was not related to this class, or
* else an {@link IntentResult} containing the result of the scan. If the user cancelled scanning,
* the fields will be null.
*/
public static IntentResult parseActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String formatName = intent.getStringExtra("SCAN_RESULT_FORMAT");
byte[] rawBytes = intent.getByteArrayExtra("SCAN_RESULT_BYTES");
int intentOrientation = intent.getIntExtra("SCAN_RESULT_ORIENTATION", Integer.MIN_VALUE);
Integer orientation = intentOrientation == Integer.MIN_VALUE ? null : intentOrientation;
String errorCorrectionLevel = intent.getStringExtra("SCAN_RESULT_ERROR_CORRECTION_LEVEL");
return new IntentResult(contents,
formatName,
rawBytes,
orientation,
errorCorrectionLevel);
}
return new IntentResult();
}
return null;
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent == null) {
return;
}
ApplicationLoader.postInitApplication();
int currentAccount = intent.getIntExtra("currentAccount", UserConfig.selectedAccount);
long did = intent.getLongExtra("did", 777000);
byte[] data = intent.getByteArrayExtra("data");
int mid = intent.getIntExtra("mid", 0);
SendMessagesHelper.getInstance(currentAccount).sendNotificationCallback(did, mid, data);
}
@Override
protected void handleDefaultAction(Intent intent, int flags, int startId) {
final byte[] bytes = intent.getByteArrayExtra(EXTRA_TIMER);
if (bytes == null) {
throw new IllegalStateException("Cannot start TimerNotificationService without a Timer");
}
final Timer timer = ParcelableUtil.unmarshall(bytes, Timer.CREATOR);
final long id = timer.getId();
boolean updateChronometer = false;
Timer oldTimer = mTimers.put(id, timer);
if (oldTimer != null) {
updateChronometer = oldTimer.endTime() != timer.endTime();
}
mControllers.put(id, new TimerController(timer, mUpdateHandler));
mMostRecentTimerId = id;
// If isUpdate == true, this won't call through because the id already exists in the
// internal mappings as well.
registerNewNoteBuilder(id);
// The note's title should change here every time, especially if the Timer's label was updated.
String title = timer.label();
if (title.isEmpty()) {
title = getString(R.string.timer);
}
setContentTitle(id, title);
if (updateChronometer) {
// Immediately push any duration updates, or else there will be a noticeable delay.
setBase(id, timer.endTime());
updateNotification(id, true);
}
// This handles any other notification updates like the title or actions, even if
// the timer is not running because the current thread will update the notification
// (besides the content text) before quitting.
syncNotificationWithTimerState(id, timer.isRunning());
}
@Override
public void onReceive(Context context, Intent intent) {
String deviceAddress = intent.getStringExtra(DeviceService.EXTRA_DEVICE_ADDRESS);
BTServiceProfile serviceProfile = intent.getParcelableExtra(DeviceService.EXTRA_SERVICE);
BTCharacteristicProfile chProfile = intent.getParcelableExtra(DeviceService.EXTRA_CHARACTERISTIC);
BTDescriptorProfile chDescriptor = intent.getParcelableExtra(DeviceService.EXTRA_DESCRIPTOR);
int status = intent.getIntExtra(DeviceService.EXTRA_STATUS, 0);
byte[] value = intent.getByteArrayExtra(DeviceService.EXTRA_VALUE);
onDescriptor(deviceAddress, serviceProfile.getService(), chProfile.getCharacteristic(),
chDescriptor.getDescriptor(),
chProfile.getCharacteristic().getValue(), status);
}
@Override
public void onReceive(Context context, Intent intent) {
byte[] responseBytes = intent.getByteArrayExtra(QueryUtil.EXTRA_RESPONSE_MESSAGE);
if (responseBytes == null) {
Log.w(LOG_TAG, "Received query response without a defined message");
return;
}
BroadcastQueryResponse response;
try {
response = BroadcastQueryResponse.parseFrom(responseBytes);
} catch (IOException e) {
Log.w(LOG_TAG, "Unable to parse query response message");
return;
}
String responder = mPendingQuery.mRespondersById.get(response.getResponseId());
if (responder == null) {
Log.w(LOG_TAG, "Received response from unknown responder");
return;
}
if (!mPendingQuery.mPendingResponses.remove(response.getResponseId())) {
Log.w(LOG_TAG, "Duplicate response received; ignoring");
return;
}
if (response.getResponseMessage() != null) {
QueryResponse queryResponse = new QueryResponse(
responder,
response.getResponseId(),
response.getResponseMessage().toByteArray());
mPendingQuery.mResponses.put(responder, queryResponse);
}
if (mPendingQuery.mPendingResponses.isEmpty()) {
mPendingQuery.complete();
}
}
@Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "intent: " + ((intent == null || intent.getAction() == null) ? "null" : intent.getAction()));
Log.e(TAG, "result: " + getResultCode());
Log.e(TAG, "pdu (if any): " + ((intent != null && intent.hasExtra("pdu")) ? getLogBytesHex(intent.getByteArrayExtra("pdu")) : ""));
if (intent == null) {
return;
}
if (SENT.equalsIgnoreCase(intent.getAction())) {
statusText.setText((getResultCode() == RESULT_OK ? R.string.sent : R.string.notsent));
resultText.setText(null);
} else if (DELIVER.equalsIgnoreCase(intent.getAction())) {
boolean delivered = false;
if (intent.hasExtra("pdu")) {
byte[] pdu = intent.getByteArrayExtra("pdu");
if (pdu != null && pdu.length > 1) {
lastSendResultPDU = pdu;
resultPduDetails.setVisibility(View.VISIBLE);
SmsTpdu parsedResultPdu = getSmsTpdu(pdu);
if (parsedResultPdu != null) {
Log.d(TAG, parsedResultPdu.toString());
delivered = parsedResultPdu.getSmsTpduType().equals(SmsTpduType.SMS_STATUS_REPORT) && ((SmsStatusReportTpdu) parsedResultPdu).getStatus().getCode() == Status.SMS_RECEIVED;
} else {
String resultPdu = getLogBytesHex(pdu).trim();
delivered = "00".equalsIgnoreCase(resultPdu.substring(resultPdu.length() - 2));
}
}
}
resultText.setText(delivered ? R.string.delivered : R.string.offline);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.settings_activity_title);
setContentView(R.layout.activity_container);
Toolbar toolbar = findViewById(R.id.container_toolbar);
setSupportActionBar(toolbar);
ViewStub stub = findViewById(R.id.container_stub);
stub.inflate();
Intent callingIntent = getIntent();
byte[] keyMaterial = callingIntent.getByteArrayExtra(Constants.EXTRA_SETTINGS_ENCRYPTION_KEY);
if (keyMaterial != null && keyMaterial.length > 0)
encryptionKey = EncryptionHelper.generateSymmetricKey(keyMaterial);
if (savedInstanceState != null) {
encryptionChanged = savedInstanceState.getBoolean(Constants.EXTRA_SETTINGS_ENCRYPTION_CHANGED, false);
byte[] encKey = savedInstanceState.getByteArray(Constants.EXTRA_SETTINGS_ENCRYPTION_KEY);
if (encKey != null) {
encryptionKey = EncryptionHelper.generateSymmetricKey(encKey);
}
}
fragment = new SettingsFragment();
getFragmentManager().beginTransaction()
.replace(R.id.container_content, fragment)
.commit();
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
sharedPref.registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onReceive(Context context, Intent intent) {
JobManager jobManager = ApplicationContext.getInstance(context).getJobManager();
long messageId = intent.getLongExtra("message_id", -1);
switch (intent.getAction()) {
case SENT_SMS_ACTION:
int result = getResultCode();
jobManager.add(new SmsSentJob(context, messageId, SENT_SMS_ACTION, result));
break;
case DELIVERED_SMS_ACTION:
byte[] pdu = intent.getByteArrayExtra("pdu");
if (pdu == null) {
Log.w(TAG, "No PDU in delivery receipt!");
break;
}
SmsMessage message = SmsMessage.createFromPdu(pdu);
if (message == null) {
Log.w(TAG, "Delivery receipt failed to parse!");
break;
}
jobManager.add(new SmsSentJob(context, messageId, DELIVERED_SMS_ACTION, message.getStatus()));
break;
default:
Log.w(TAG, "Unknown action: " + intent.getAction());
}
}
/**
* @see https://developer.android.com/reference/android/telephony/SmsMessage.html#createFromPdu%28byte[],%20java.lang.String%29
*/
private static SmsMessage createFromPdu(Intent intent) {
byte[] pdu = intent.getByteArrayExtra("pdu");
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String format = intent.getStringExtra("format");
return SmsMessage.createFromPdu(pdu, format);
} else {
return SmsMessage.createFromPdu(pdu);
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final PowerManager.WakeLock wl = JoH.getWakeLock("bluejay service", 60000);
try {
if (shouldServiceRun()) {
setAddress(BlueJay.getMac());
I.playSounds = BlueJay.shouldBeepOnConnect();
setAutoConnect();
if (intent != null) {
final String function = intent.getStringExtra("function");
if (function != null) {
UserError.Log.d(TAG, "RUNNING FUNCTION: " + function);
switch (function) {
case "wakeup":
checkConnection();
break;
case "refresh":
setSettings();
if (JoH.pratelimit("bj-set-time-via-refresh-" + BlueJay.getMac(), 300)) {
setTime();
}
break;
case "sendglucose":
if (shouldSendReadings()) {
sendGlucose();
}
break;
case "message":
final String message = intent.getStringExtra("message");
final String message_type = intent.getStringExtra("message_type");
if (JoH.ratelimit("bj-sendmessage" + message_type, 15)) {
sendNotification(message_type, message);
}
break;
case "png":
final byte[] bytes = intent.getByteArrayExtra("bytes_payload");
final String params = intent.getStringExtra("params");
final String type = intent.getStringExtra("type");
if (JoH.ratelimit("bj-sendpng", 15)) {
switch (type) {
case "colour":
sendColourPng(bytes, params);
break;
case "mono":
sendMonoPng(bytes, params);
break;
default:
UserError.Log.wtf(TAG, "Invalid png type: " + type);
}
}
break;
case "audioin":
UserError.Log.d(TAG, "Audio in request received");
break;
case "audioout":
UserError.Log.d(TAG, "Audio out request received");
break;
}
} else {
// no specific function
UserError.Log.d(TAG, "SET TIME CALLED");
changeState(SET_TIME);
}
}
//doQueue(); // start things in motion // This was previously enabled
return START_STICKY;
} else {
UserError.Log.d(TAG, "Service is NOT set be active - shutting down");
I.autoConnect = false; // avoid reconnection when shutting down
stopSelf();
return START_NOT_STICKY;
}
} finally {
JoH.releaseWakeLock(wl);
}
}
/**
* Returns the result of a {@link HintRetrieveResult}.
*
* <pre>{@code
* CredentialClient client = CredentialClient.getInstance(getContext());
*
* // ...
* @Override
* public void onActivityResult(int requestCode, int resultCode, Intent data) {
* super.onActivityResult(requestCode, resultCode, data);
* if (RC_RETRIEVE_HINT == requestCode) {
* HintRetrieveResult result = client.getHintRetrieveResult(data);
* if (result.isSuccessful()) {
* // A hint was retrieved, you may be able to automatically create an account for the
* // user, or offer the user to sign in if an existing account matches the hint.
* result.getHint();
* } else {
* // A credential was not retrieved, you may look at the result code to determine why
* // and decide what step to take next. For example, result code may inform you of the
* // user's intent such as HintRetrieveResult.CODE_USER_CANCELED.
* result.getResultCode();
* }
* }
* }
* }</pre>
*
* @see #getHintRetrieveIntent(HintRetrieveRequest)
*/
@NonNull
public HintRetrieveResult getHintRetrieveResult(Intent resultData) {
if (resultData == null) {
Log.i(LOG_TAG, "resultData is null, returning default response");
return HintRetrieveResult.UNKNOWN;
}
if (!resultData.hasExtra(EXTRA_HINT_RESULT)) {
Log.i(LOG_TAG, "hint result missing from response, returning default response");
return HintRetrieveResult.UNKNOWN;
}
byte[] resultBytes = resultData.getByteArrayExtra(EXTRA_HINT_RESULT);
if (resultBytes == null) {
Log.i(LOG_TAG, "No hint result found in result data, returning default response");
return HintRetrieveResult.UNKNOWN;
}
try {
return HintRetrieveResult.fromProtobufBytes(resultBytes);
} catch (MalformedDataException ex) {
Log.e(LOG_TAG, "hint result is malformed, returning default response", ex);
return HintRetrieveResult.UNKNOWN;
}
}
public static Intent convert(Intent input) {
Intent output = new Intent();
output.setAction(input.getAction());
// detect supported types
if(input.hasExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)) {
Parcelable[] messages = input.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
Bundle extras = new Bundle();
extras.putParcelableArray(NfcAdapter.EXTRA_NDEF_MESSAGES, messages);
output.putExtras(extras);
}
if(input.hasExtra(NfcAdapter.EXTRA_TAG)) {
android.nfc.Tag tag = (android.nfc.Tag) input.getParcelableExtra(NfcAdapter.EXTRA_TAG);
output.putExtra(NfcAdapter.EXTRA_TAG, new TagWrapper(tag));
}
if(input.hasExtra(NfcAdapter.EXTRA_AID)) {
output.putExtra(NfcAdapter.EXTRA_AID, input.getParcelableExtra(NfcAdapter.EXTRA_AID));
}
if(input.hasExtra(NfcAdapter.EXTRA_ID)) {
byte[] id = input.getByteArrayExtra(NfcAdapter.EXTRA_ID);
output.putExtra(NfcAdapter.EXTRA_ID, id);
}
// TODO forward all types
return output;
}
/**
* リクエストから画像ファイルのバイナリを取得する.
*
* @param request リクエストパラメータ
* @return 画像ファイルのバイナリ。無い場合はnullを返す。
*/
public static byte[] getData(final Intent request) {
return request.getByteArrayExtra(PARAM_DATA);
}