下面列出了android.os.Bundle#keySet ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Check that only values of the following types are in the Bundle:
* <ul>
* <li>Integer</li>
* <li>Long</li>
* <li>Boolean</li>
* <li>Float</li>
* <li>Double</li>
* <li>String</li>
* <li>Account</li>
* <li>null</li>
* </ul>
* @param extras the Bundle to check
*/
public static void validateSyncExtrasBundle(Bundle extras) {
try {
for (String key : extras.keySet()) {
Object value = extras.get(key);
if (value == null) continue;
if (value instanceof Long) continue;
if (value instanceof Integer) continue;
if (value instanceof Boolean) continue;
if (value instanceof Float) continue;
if (value instanceof Double) continue;
if (value instanceof String) continue;
if (value instanceof Account) continue;
throw new IllegalArgumentException("unexpected value type: "
+ value.getClass().getName());
}
} catch (IllegalArgumentException e) {
throw e;
} catch (RuntimeException exc) {
throw new IllegalArgumentException("error unparceling Bundle", exc);
}
}
/**
* Generate the multi-part post body providing the parameters and boundary
* string
*
* @param parameters the parameters need to be posted
* @param boundary the random string as boundary
* @return a string of the post body
*/
@Deprecated
public static String encodePostBody(Bundle parameters, String boundary) {
if (parameters == null) return "";
StringBuilder sb = new StringBuilder();
for (String key : parameters.keySet()) {
Object parameter = parameters.get(key);
if (!(parameter instanceof String)) {
continue;
}
sb.append("Content-Disposition: form-data; name=\"" + key +
"\"\r\n\r\n" + (String)parameter);
sb.append("\r\n" + "--" + boundary + "\r\n");
}
return sb.toString();
}
@Override
public void instrumentationStatus(ComponentName name, int resultCode, Bundle results) {
synchronized (this) {
// pretty printer mode?
String pretty = null;
if (!mRawMode && results != null) {
pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT);
}
if (pretty != null) {
System.out.print(pretty);
} else {
if (results != null) {
for (String key : results.keySet()) {
System.out.println("INSTRUMENTATION_STATUS: " + key + "=" + results.get(key));
}
}
System.out.println("INSTRUMENTATION_STATUS_CODE: " + resultCode);
}
notifyAll();
}
}
@Override
protected void handleOnNewIntent(Intent data) {
super.handleOnNewIntent(data);
Bundle bundle = data.getExtras();
if(bundle != null && bundle.containsKey("google.message_id")) {
JSObject notificationJson = new JSObject();
JSObject dataObject = new JSObject();
for (String key : bundle.keySet()) {
if (key.equals("google.message_id")) {
notificationJson.put("id", bundle.get(key));
} else {
Object value = bundle.get(key);
String valueStr = (value != null) ? value.toString() : null;
dataObject.put(key, valueStr);
}
}
notificationJson.put("data", dataObject);
JSObject actionJson = new JSObject();
actionJson.put("actionId", "tap");
actionJson.put("notification", notificationJson);
notifyListeners("pushNotificationActionPerformed", actionJson, true);
}
}
@Test
public void testExtension_DifferentBundle() {
DynamicLinkData originalDynamicLink = addExtension(genDynamicLinkData());
DynamicLinkData extraDynamicLink = addExtension(genDynamicLinkData());
// Add one more bundle key.
Bundle bundle = extraDynamicLink.getExtensionBundle();
bundle.putString(KEY_TEST_EXTRA, TEST_STRING_VALUE);
extraDynamicLink.setExtensionData(bundle);
Bundle originalBundle = originalDynamicLink.getExtensionBundle();
Bundle extraBundle = extraDynamicLink.getExtensionBundle();
Set<String> extraKeys = extraBundle.keySet();
Set<String> originalKeys = originalBundle.keySet();
assertTrue(extraKeys.containsAll(originalKeys));
// Identify that the bundles are different, missing keys.
assertFalse(originalKeys.containsAll(extraKeys));
}
private LogcatReaderLoader(Parcel in) {
this.recordingMode = in.readInt() == 1;
this.multiple = in.readInt() == 1;
Bundle bundle = in.readBundle();
for (String key : bundle.keySet()) {
lastLines.put(key, bundle.getString(key));
}
}
/**
* For debugging the intent extras
*
* @param bundle containing potential extras
*/
private static void examineBundle(@Nullable final Bundle bundle) {
MyLog.i(CLS_NAME, "examineBundle");
if (bundle != null) {
final Set<String> keys = bundle.keySet();
//noinspection Convert2streamapi
for (final String key : keys) {
MyLog.v(CLS_NAME, "examineBundle: " + key + " ~ " + bundle.get(key));
}
}
}
/**
* Returns true if {@param original} contains all entries defined in {@param updates} and
* have the same value.
* The comparison uses {@link Object#equals(Object)} to compare the values.
*/
public static boolean containsAll(Bundle original, Bundle updates) {
for (String key : updates.keySet()) {
Object value1 = updates.get(key);
Object value2 = original.get(key);
if (value1 == null) {
if (value2 != null) {
return false;
}
} else if (!value1.equals(value2)) {
return false;
}
}
return true;
}
public static <T extends Serializable> Map<String, T> readSerializableMap(Parcel parcel) {
Map<String, T> map = new ArrayMap<>();
Bundle bundle = parcel.readBundle(Parcelables.class.getClassLoader());
for (String key : bundle.keySet()) {
@SuppressWarnings("unchecked")
T serializable = (T) bundle.getSerializable(key);
map.put(key, serializable);
}
return map;
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
if (state != null) {
Bundle bundle = (Bundle)state;
bundle.setClassLoader(loader);
Parcelable[] fss = bundle.getParcelableArray("states");
mSavedState.clear();
mFragments.clear();
if (fss != null) {
for (int i=0; i<fss.length; i++) {
mSavedState.add((Fragment.SavedState)fss[i]);
}
}
Iterable<String> keys = bundle.keySet();
for (String key: keys) {
if (key.startsWith("f")) {
int index = Integer.parseInt(key.substring(1));
Fragment f = mFragmentManager.getFragment(bundle, key);
if (f != null) {
while (mFragments.size() <= index) {
mFragments.add(null);
}
f.setMenuVisibility(false);
mFragments.set(index, f);
} else {
Log.w(TAG, "Bad fragment at key " + key);
}
}
}
}
}
public static void dumpBundle(Bundle bundle, String tag) {
if (bundle != null) {
for (String key : bundle.keySet()) {
Object value = bundle.get(key);
if (value != null) {
UserError.Log.d(tag, String.format("%s %s (%s)", key,
value.toString(), value.getClass().getName()));
}
}
} else {
UserError.Log.d(tag, "Bundle is empty");
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private JSONObject convertBundleToJson(Bundle bundle) throws JSONException {
JSONObject json = new JSONObject();
Set<String> keys = bundle.keySet();
for (String key : keys) {
Object value = bundle.get(key);
if (value instanceof Bundle) value = convertBundleToJson((Bundle) value);
if (value instanceof Bundle[]) value = convertBundleArrayToJson((Bundle[]) value);
json.put(key, JSONObject.wrap(value));
}
return json;
}
private static void bundleToString(StringBuilder builder, Bundle data) {
final Set<String> keySet = data.keySet();
builder.append("[Bundle with ").append(keySet.size()).append(" keys:");
for (String key : keySet) {
builder.append(' ').append(key).append('=');
Object value = data.get(key);
if ((value instanceof Bundle)) {
bundleToString(builder, (Bundle) value);
} else {
builder.append((value instanceof Object[])
? Arrays.toString((Object[]) value) : value);
}
}
builder.append(']');
}
private List<String> buildShellParams(Bundle arguments) throws IOException, ClientNotConnected {
List<String> params = new ArrayList<>();
params.add("instrument");
params.add("-w");
params.add("-r");
for (String key : arguments.keySet()) {
params.add("-e");
params.add(key);
params.add(arguments.getString(key));
}
params.add(getTargetInstrumentation());
return params;
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
if (state != null) {
Bundle bundle = (Bundle) state;
bundle.setClassLoader(loader);
Parcelable[] fss = bundle.getParcelableArray("states");
mSavedState.clear();
mFragments.clear();
if (fss != null) {
for (Parcelable fs : fss) {
mSavedState.add((Fragment.SavedState) fs);
}
}
Iterable<String> keys = bundle.keySet();
for (String key : keys) {
if (key.startsWith("f")) {
int index = Integer.parseInt(key.substring(1));
Fragment f = mFragmentManager.getFragment(bundle, key);
if (f != null) {
while (mFragments.size() <= index) {
mFragments.add(null);
}
f.setMenuVisibility(false);
mFragments.set(index, f);
} else {
Log.w(TAG, "Bad fragment at key " + key);
}
}
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bundle bundle = data == null ? null : data.getBundleExtra("result");
if (bundle != null) {
HashMap<String, String> settingsUpdated = new HashMap<>();
for (String key : bundle.keySet()) {
settingsUpdated.put(key, bundle.getString(key));
}
if (settingsUpdated.containsKey(getString(R.string.pref_key_mmol))) mQuickSettings.refresh();
if (settingsUpdated.size() > 0) mService.sendData(WearableApi.SETTINGS, settingsUpdated, null);
}
super.onActivityResult(requestCode, resultCode, data);
}
public Map<String, Object> getAsMap() {
Cursor cursor = execute();
try {
Map<String, Object> result = new HashMap<>();
Bundle bundle = cursor.getExtras();
for (String column : bundle.keySet()) {
result.put(column, bundle.get(column));
}
return result;
} finally {
cursor.close();
mDb.close();
}
}
JSONObject convertJSONObject(Bundle bundle) throws JSONException {
JSONObject json = new JSONObject();
Set<String> keys = bundle.keySet();
for (String key : keys) {
Object value = bundle.get(key);
if (value instanceof Bundle) {
json.put(key, convertJSONObject((Bundle)value));
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
json.put(key, JSONObject.wrap(value));
} else {
json.put(key, value);
}
}
return json;
}
public AppEvent(
Context context,
String eventName,
Double valueToSum,
Bundle parameters,
boolean isImplicitlyLogged
) {
validateIdentifier(eventName);
this.name = eventName;
isImplicit = isImplicitlyLogged;
jsonObject = new JSONObject();
try {
jsonObject.put("_eventName", eventName);
jsonObject.put("_logTime", System.currentTimeMillis() / 1000);
jsonObject.put("_ui", Utility.getActivityName(context));
if (valueToSum != null) {
jsonObject.put("_valueToSum", valueToSum.doubleValue());
}
if (isImplicit) {
jsonObject.put("_implicitlyLogged", "1");
}
String appVersion = Settings.getAppVersion();
if (appVersion != null) {
jsonObject.put("_appVersion", appVersion);
}
if (parameters != null) {
for (String key : parameters.keySet()) {
validateIdentifier(key);
Object value = parameters.get(key);
if (!(value instanceof String) && !(value instanceof Number)) {
throw new FacebookException(
String.format(
"Parameter value '%s' for key '%s' should be a string or a numeric type.",
value,
key)
);
}
jsonObject.put(key, value.toString());
}
}
if (!isImplicit) {
Logger.log(LoggingBehavior.APP_EVENTS, "AppEvents",
"Created app event '%s'", jsonObject.toString());
}
} catch (JSONException jsonException) {
// If any of the above failed, just consider this an illegal event.
Logger.log(LoggingBehavior.APP_EVENTS, "AppEvents",
"JSON encoding for app event failed: '%s'", jsonException.toString());
jsonObject = null;
}
}
private void updatePart(Bundle bundle) {
for (String key :
bundle.keySet()) {
String value = bundle.getString(key);
switch (key) {
case "latest":
setTextColor(mBinding.quoteLatest, value, bundle.getString("pre_settlement"));
break;
case "change":
if (!(DALIANZUHE.equals(mTitle) || ZHENGZHOUZUHE.equals(mTitle)) && mSwitchChange) {
setChangeTextColor(mBinding.quoteChangePercent, value);
}
break;
case "change_percent":
if (!(DALIANZUHE.equals(mTitle) || ZHENGZHOUZUHE.equals(mTitle)) && !mSwitchChange) {
setChangeTextColor(mBinding.quoteChangePercent, value);
}
break;
case "volume":
if (!(DALIANZUHE.equals(mTitle) || ZHENGZHOUZUHE.equals(mTitle)) && mSwitchVolume) {
mBinding.quoteOpenInterest.setText(value);
}
break;
case "open_interest":
if (!(DALIANZUHE.equals(mTitle) || ZHENGZHOUZUHE.equals(mTitle)) && !mSwitchVolume) {
mBinding.quoteOpenInterest.setText(value);
}
break;
case "bid_price1":
if ((DALIANZUHE.equals(mTitle) || ZHENGZHOUZUHE.equals(mTitle)) && !mSwitchChange) {
setTextColor(mBinding.quoteChangePercent, value, bundle.getString("pre_settlement"));
}
break;
case "bid_volume1":
if ((DALIANZUHE.equals(mTitle) || ZHENGZHOUZUHE.equals(mTitle)) && mSwitchChange) {
mBinding.quoteChangePercent.setText(value);
mBinding.quoteChangePercent.setTextColor(ContextCompat.getColor(sContext, R.color.text_white));
}
break;
case "ask_price1":
if ((DALIANZUHE.equals(mTitle) || ZHENGZHOUZUHE.equals(mTitle)) && !mSwitchVolume) {
setTextColor(mBinding.quoteOpenInterest, value, bundle.getString("pre_settlement"));
}
break;
case "ask_volume1":
if ((DALIANZUHE.equals(mTitle) || ZHENGZHOUZUHE.equals(mTitle)) && mSwitchVolume) {
mBinding.quoteOpenInterest.setText(value);
mBinding.quoteOpenInterest.setTextColor(ContextCompat.getColor(sContext, R.color.text_white));
}
break;
default:
break;
}
}
}