下面列出了怎么用android.os.PersistableBundle的API类实例代码及写法,或者点击链接到github查看源代码。
@ReactMethod
@TargetApi(25)
public void popInitialAction(Promise promise) {
try {
Activity currentActivity = getCurrentActivity();
WritableMap map = null;
if (currentActivity != null) {
Intent intent = currentActivity.getIntent();
if (ACTION_SHORTCUT.equals(intent.getAction())) {
PersistableBundle bundle = intent.getParcelableExtra(SHORTCUT_ITEM);
if (bundle != null) {
ShortcutItem item = ShortcutItem.fromPersistableBundle(bundle);
map = item.toWritableMap();
}
}
}
promise.resolve(map);
} catch (Exception e) {
promise.reject(new JSApplicationIllegalArgumentException(
"AppShortcuts.popInitialAction error. " + e.getMessage()));
}
}
/**
* Manually requests a job to run now.
*
* <p>To check the current status of the sync, register a {@link
* android.content.BroadcastReceiver} with an {@link android.content.IntentFilter} which checks
* for the action {@link #ACTION_SYNC_STATUS_CHANGED}.
*
* <p>The sync status is an extra parameter in the {@link Intent} with key {@link #SYNC_STATUS}.
* The sync status is either {@link #SYNC_STARTED} or {@link #SYNC_FINISHED}.
*
* <p>Check that the value of {@link #BUNDLE_KEY_INPUT_ID} matches your {@link
* android.media.tv.TvInputService}. If you're calling this from your setup activity, you can
* get the extra parameter {@link TvInputInfo#EXTRA_INPUT_ID}.
*
* <p>
*
* @param context Application's context.
* @param inputId Component name for the app's TvInputService. This can be received through an
* Intent extra parameter {@link TvInputInfo#EXTRA_INPUT_ID}.
* @param syncDuration The duration of EPG content to fetch in milliseconds. For a manual sync,
* this should be relatively short. For a background sync this should be long.
* @param jobServiceComponent The {@link EpgSyncJobService} class that will run.
*/
public static void requestImmediateSync(
Context context, String inputId, long syncDuration, ComponentName jobServiceComponent) {
if (jobServiceComponent.getClass().isAssignableFrom(EpgSyncJobService.class)) {
throw new IllegalArgumentException("This class does not extend EpgSyncJobService");
}
PersistableBundle persistableBundle = new PersistableBundle();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
persistableBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
persistableBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
}
persistableBundle.putString(EpgSyncJobService.BUNDLE_KEY_INPUT_ID, inputId);
persistableBundle.putLong(EpgSyncJobService.BUNDLE_KEY_SYNC_PERIOD, syncDuration);
JobInfo.Builder builder = new JobInfo.Builder(REQUEST_SYNC_JOB_ID, jobServiceComponent);
JobInfo jobInfo =
builder.setExtras(persistableBundle)
.setOverrideDeadline(EpgSyncJobService.OVERRIDE_DEADLINE_MILLIS)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.build();
scheduleJob(context, jobInfo);
if (DEBUG) {
Log.d(TAG, "Single job scheduled");
}
}
private void showEditDialog(final String key) {
mEditingKey = key;
int type = KeyValuePairDialogFragment.DialogType.BOOL_TYPE;
Object value = null;
if (key != null) {
value = mBundle.get(key);
if (value instanceof Boolean) {
type = KeyValuePairDialogFragment.DialogType.BOOL_TYPE;
} else if (value instanceof Integer) {
type = KeyValuePairDialogFragment.DialogType.INT_TYPE;
} else if (value instanceof String) {
type = KeyValuePairDialogFragment.DialogType.STRING_TYPE;
} else if (value instanceof String[]) {
type = KeyValuePairDialogFragment.DialogType.STRING_ARRAY_TYPE;
} else if (value instanceof PersistableBundle) {
type = KeyValuePairDialogFragment.DialogType.BUNDLE_TYPE;
value = BundleUtil.persistableBundleToBundle((PersistableBundle) value);
}
}
KeyValuePairDialogFragment dialogFragment =
KeyValuePairDialogFragment.newInstance(type, true, key, value, SUPPORTED_TYPE,
mResolveInfo.loadLabel(mPackageManager).toString());
dialogFragment.setTargetFragment(this, RESULT_CODE_EDIT_DIALOG);
dialogFragment.show(getFragmentManager(), "dialog");
}
private void sendJSEvent(Intent intent) {
if (!ACTION_SHORTCUT.equals(intent.getAction()) || !isShortcutSupported()) {
return;
}
ShortcutItem item = null;
PersistableBundle bundle = intent.getParcelableExtra(SHORTCUT_ITEM);
if (bundle != null) {
item = ShortcutItem.fromPersistableBundle(bundle);
}
if (item != null) {
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("quickActionShortcut", item.toWritableMap());
}
}
/**
* Initializes a job that will periodically update the app's channels and programs.
*
* @param context Application's context.
* @param inputId Component name for the app's TvInputService. This can be received through an
* Intent extra parameter {@link TvInputInfo#EXTRA_INPUT_ID}.
* @param jobServiceComponent The {@link EpgSyncJobService} component name that will run.
* @param fullSyncPeriod The period between when the job will run a full background sync in
* milliseconds.
* @param syncDuration The duration of EPG content to fetch in milliseconds. For a manual sync,
* this should be relatively short. For a background sync this should be long.
*/
public static void setUpPeriodicSync(
Context context,
String inputId,
ComponentName jobServiceComponent,
long fullSyncPeriod,
long syncDuration) {
if (jobServiceComponent.getClass().isAssignableFrom(EpgSyncJobService.class)) {
throw new IllegalArgumentException("This class does not extend EpgSyncJobService");
}
PersistableBundle persistableBundle = new PersistableBundle();
persistableBundle.putString(EpgSyncJobService.BUNDLE_KEY_INPUT_ID, inputId);
persistableBundle.putLong(EpgSyncJobService.BUNDLE_KEY_SYNC_PERIOD, syncDuration);
JobInfo.Builder builder = new JobInfo.Builder(PERIODIC_SYNC_JOB_ID, jobServiceComponent);
JobInfo jobInfo =
builder.setExtras(persistableBundle)
.setPeriodic(fullSyncPeriod)
.setPersisted(true)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.build();
scheduleJob(context, jobInfo);
if (DEBUG) {
Log.d(TAG, "Job has been scheduled for every " + fullSyncPeriod + "ms");
}
}
@Override
public void updateSystemUpdateInfo(PersistableBundle infoBundle) {
mContext.enforceCallingOrSelfPermission(Manifest.permission.RECOVERY, TAG);
int status = infoBundle.getInt(KEY_STATUS, STATUS_UNKNOWN);
if (status == STATUS_UNKNOWN) {
Slog.w(TAG, "Invalid status info. Ignored");
return;
}
// There could be multiple updater apps running on a device. But only one at most should
// be active (i.e. with a pending update), with the rest reporting idle status. We will
// only accept the reported status if any of the following conditions holds:
// a) none has been reported before;
// b) the current on-file status was last reported by the same caller;
// c) an active update is being reported.
int uid = Binder.getCallingUid();
if (mLastUid == UID_UNKNOWN || mLastUid == uid || status != STATUS_IDLE) {
synchronized (mLock) {
saveSystemUpdateInfoLocked(infoBundle, uid);
}
} else {
Slog.i(TAG, "Inactive updater reporting IDLE status. Ignored");
}
}
public static void scheduleAddWatchNextRequest(Context context, ClipData clipData) {
JobScheduler scheduler = (JobScheduler) context.getSystemService(JOB_SCHEDULER_SERVICE);
PersistableBundle bundle = new PersistableBundle();
bundle.putString(ID_KEY, clipData.getClipId());
bundle.putString(CONTENT_ID_KEY, clipData.getContentId());
bundle.putLong(DURATION_KEY, clipData.getDuration());
bundle.putLong(PROGRESS_KEY, clipData.getProgress());
bundle.putString(TITLE_KEY, clipData.getTitle());
bundle.putString(DESCRIPTION_KEY, clipData.getDescription());
bundle.putString(CARD_IMAGE_URL_KEY, clipData.getCardImageUrl());
scheduler.schedule(new JobInfo.Builder(1,
new ComponentName(context, AddWatchNextService.class))
.setExtras(bundle)
.build());
}
@TargetApi(VERSION_CODES.LOLLIPOP_MR1)
public static Bundle persistableBundleToBundle(PersistableBundle persistableBundle) {
Set<String> keySet = persistableBundle.keySet();
Bundle bundle = new Bundle();
for (String key : keySet) {
Object value = persistableBundle.get(key);
if (value instanceof Boolean) {
bundle.putBoolean(key, (boolean) value);
} else if (value instanceof Integer) {
bundle.putInt(key, (int) value);
} else if (value instanceof String) {
bundle.putString(key, (String) value);
} else if (value instanceof String[]) {
bundle.putStringArray(key, (String[]) value);
} else if (value instanceof PersistableBundle) {
Bundle innerBundle = persistableBundleToBundle((PersistableBundle) value);
bundle.putBundle(key, innerBundle);
}
}
return bundle;
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
static public boolean checkAndRequestIslandPermission(Context context) {
final String TYPE_DELEGATION = "com.oasisfeng.island.delegation";
final String DELEGATION_APP_OPS = "-island-delegation-app-ops";
final String DELEGATION_PACKAGE_ACCESS = "delegation-package-access";
final RestrictionsManager rm = (RestrictionsManager) context.getSystemService(Context.RESTRICTIONS_SERVICE);
if (rm != null && rm.hasRestrictionsProvider()) { // Otherwise, current user is not managed by Island or the version of Island is too low.
final String[] delegations = rm.getApplicationRestrictions().getStringArray(TYPE_DELEGATION);
if (delegations == null || !Arrays.asList(delegations).contains(DELEGATION_PACKAGE_ACCESS)) {
final PersistableBundle request = new PersistableBundle();
request.putString(RestrictionsManager.REQUEST_KEY_DATA, DELEGATION_PACKAGE_ACCESS);
rm.requestPermission(TYPE_DELEGATION, "cf.playhi.freezeyou.android.app-ops", request);
} else {
return true;
}
}
return false;
}
public static PersistableBundle fromAddress(android.location.Address address) {
if (address == null) {
return null;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
PersistableBundle persistableBundle = new PersistableBundle();
persistableBundle.putString("country", address.getLocale().getCountry());
persistableBundle.putString("language", address.getLocale().getLanguage());
persistableBundle.putString("variant", address.getLocale().getVariant());
persistableBundle.putString("locality", address.getLocality());
persistableBundle.putString("subLocality", address.getSubLocality());
persistableBundle.putString("adminArea", address.getAdminArea());
persistableBundle.putString("subAdminArea", address.getSubAdminArea());
persistableBundle.putString("countryName", address.getCountryName());
return persistableBundle;
} else {
return null;
}
}
@Override
@Nullable
@TargetApi(28)
public PersistableBundle getMetrics() {
if (Util.SDK_INT < 28) {
return null;
}
return mediaDrm.getMetrics();
}
/***************************************************/
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
outState.putString(EXTRA_BILL_ID,mBillId);
outState.putString(EXTRA_BILL_NAME,mBillName);
}
public static void scheduleDeleteWatchNextRequest(Context context, String clipId) {
JobScheduler scheduler = (JobScheduler) context.getSystemService(JOB_SCHEDULER_SERVICE);
PersistableBundle bundle = new PersistableBundle();
bundle.putString(ID_KEY, clipId);
scheduler.schedule(new JobInfo.Builder(1, new ComponentName(context,
DeleteWatchNextService.class))
.setExtras(bundle)
.build());
}
static String getString(Object bundle, String key, String defaultValue) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return ((PersistableBundle) bundle).getString(key, defaultValue);
} else {
String str = ((Bundle) bundle).getString(key);
return str == null ? defaultValue : str;
}
}
public LicenseKey(PersistableBundle persistentBundle) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
id = persistentBundle.getLong("id");
requestUri = persistentBundle.getString("requestUri");
initialLicense = persistentBundle.getString("initialLicense");
token = persistentBundle.getString("token");
lastCallTimeInMs = persistentBundle.getLong("lastCallTimeInMs");
}
}
static void putStringArray(Object bundle, String key, String[] value) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
((PersistableBundle) bundle).putStringArray(key, value);
} else {
((Bundle) bundle).putStringArray(key, value);
}
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onRestoreInstanceState(savedInstanceState, persistentState);
firstname.setText(savedInstanceState.getString("firstname"));
lastname.setText(savedInstanceState.getString("lastname"));
username.setText(savedInstanceState.getString("email"));
setViews(true);
}
@Override
public String[] setPackagesSuspended(String[] packageNames, boolean suspended,
PersistableBundle appExtras, PersistableBundle launcherExtras,
SuspendDialogInfo dialogInfo) {
try {
return mPM.setPackagesSuspendedAsUser(packageNames, suspended, appExtras,
launcherExtras, dialogInfo, mContext.getOpPackageName(),
getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
@Override
public Bundle getSuspendedPackageAppExtras() {
final PersistableBundle extras;
try {
extras = mPM.getSuspendedPackageAppExtras(mContext.getOpPackageName(),
getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
return extras != null ? new Bundle(extras.deepCopy()) : null;
}
static void write(Parcel parcel, Object bundle) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
parcel.writePersistableBundle((PersistableBundle) bundle);
} else {
parcel.writeBundle((Bundle) bundle);
}
}
static void putAll(Object bundle, Object allBundle) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
((PersistableBundle) bundle).putAll((PersistableBundle) allBundle);
} else {
((Bundle) bundle).putAll((Bundle) allBundle);
}
}
@Nullable
private PersistableBundle readInfoFileLocked(XmlPullParser parser)
throws XmlPullParserException, IOException {
int type;
while ((type = parser.next()) != END_DOCUMENT) {
if (type == START_TAG && TAG_INFO.equals(parser.getName())) {
return PersistableBundle.restoreFromXml(parser);
}
}
return null;
}
private void maybePassAffiliationIds(Intent intent, PersistableBundle adminExtras) {
if (Util.isDeviceOwner(getActivity())
&& ACTION_PROVISION_MANAGED_PROFILE.equals(intent.getAction())
&& Util.SDK_INT >= VERSION_CODES.O) {
passAffiliationIds(intent, adminExtras);
}
}
@Override
public PersistableBundle getSeedAccountOptions() throws RemoteException {
checkManageUsersPermission("Cannot get seed account information");
synchronized (mUsersLock) {
UserData userData = getUserDataLU(UserHandle.getCallingUserId());
return userData.seedAccountOptions;
}
}
static String[] getStringArray(Object bundle, String key) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return ((PersistableBundle) bundle).getStringArray(key);
} else {
return ((Bundle) bundle).getStringArray(key);
}
}
static void writeTagExtra(XmlSerializer out, String tag, PersistableBundle bundle)
throws IOException, XmlPullParserException {
if (bundle == null) return;
out.startTag(null, tag);
bundle.saveToXml(out);
out.endTag(null, tag);
}
private void subscriptionOrSimChanged(Context context) {
if (DEBUG) Log.d(TAG, "received SIM related action: ");
TelephonyManager phone = (TelephonyManager)
mContext.getSystemService(Context.TELEPHONY_SERVICE);
CarrierConfigManager configManager = (CarrierConfigManager)
mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE);
String mccMnc = phone.getSimOperator();
boolean isKeepLppProfile = false;
if (!TextUtils.isEmpty(mccMnc)) {
if (DEBUG) Log.d(TAG, "SIM MCC/MNC is available: " + mccMnc);
synchronized (mLock) {
if (configManager != null) {
PersistableBundle b = configManager.getConfig();
if (b != null) {
isKeepLppProfile =
b.getBoolean(CarrierConfigManager.KEY_PERSIST_LPP_MODE_BOOL);
}
}
if (isKeepLppProfile) {
// load current properties for the carrier
loadPropertiesFromResource(context, mProperties);
String lpp_profile = mProperties.getProperty("LPP_PROFILE");
// set the persist property LPP_PROFILE for the value
if (lpp_profile != null) {
SystemProperties.set(LPP_PROFILE, lpp_profile);
}
} else {
// reset the persist property
SystemProperties.set(LPP_PROFILE, "");
}
reloadGpsProperties(context, mProperties);
mNIHandler.setSuplEsEnabled(mSuplEsEnabled);
}
} else {
if (DEBUG) Log.d(TAG, "SIM MCC/MNC is still not available");
}
}
static Object get(Object bundle, String key) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return ((PersistableBundle) bundle).get(key);
} else {
return ((Bundle) bundle).get(key);
}
}
/**
* Intercept standard Restrictions Provider broadcasts. Implementations
* should not override this method; it is better to implement the
* convenience callbacks for each action.
*/
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (RestrictionsManager.ACTION_REQUEST_PERMISSION.equals(action)) {
String packageName = intent.getStringExtra(RestrictionsManager.EXTRA_PACKAGE_NAME);
String requestType = intent.getStringExtra(RestrictionsManager.EXTRA_REQUEST_TYPE);
String requestId = intent.getStringExtra(RestrictionsManager.EXTRA_REQUEST_ID);
PersistableBundle request = (PersistableBundle)
intent.getParcelableExtra(RestrictionsManager.EXTRA_REQUEST_BUNDLE);
onRequestPermission(context, packageName, requestType, requestId, request);
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
public static Bundle getBundle(PersistableBundle arg) {
Bundle result = new Bundle();
for (String key : arg.keySet())
if (arg.get(key) instanceof Boolean)
result.putBoolean(key, arg.getBoolean(key));
else if (arg.get(key) instanceof Integer)
result.putInt(key, arg.getInt(key));
else if (arg.get(key) instanceof Long)
result.putLong(key, arg.getLong(key));
else if (arg.get(key) instanceof String || arg.get(key) == null)
result.putString(key, arg.getString(key));
return result;
}