下面列出了怎么用android.content.res.Resources.NotFoundException的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zoom_image);
AmbientModeSupport.attach(this);
// Check if integer was actually given.
if (!(getIntent().hasExtra(getString(R.string.intent_extra_image)))) {
throw new NotFoundException("Expecting extras");
}
// Grab the resource id from extras and set the image resource.
int value = getIntent().getIntExtra(getString(R.string.intent_extra_image), 0);
ImageView expandedImage = findViewById(R.id.expanded_image);
expandedImage.setImageResource(value);
}
/**
* Return a brief summary of this wallpaper's behavior.
*/
public CharSequence loadDescription(PackageManager pm) throws NotFoundException {
String packageName = mService.resolvePackageName;
ApplicationInfo applicationInfo = null;
if (packageName == null) {
packageName = mService.serviceInfo.packageName;
applicationInfo = mService.serviceInfo.applicationInfo;
}
if (mService.serviceInfo.descriptionRes != 0) {
return pm.getText(packageName, mService.serviceInfo.descriptionRes,
applicationInfo);
}
if (mDescriptionResource <= 0) throw new NotFoundException();
return pm.getText(packageName, mDescriptionResource,
mService.serviceInfo.applicationInfo);
}
/**
* Return the resource ID for a given resource ID.
*
* Basically its' a wrapper over {@link Resources#getIdentifier(String, String, String)}, except
* if {@code resourceName} is an integer then it'll just return its value. (Which also the
* aforementioned method would do internally, but not documented, so doing here explicitly.)
*
* @param res {@link Resources} for the publisher. Must have been loaded with
* {@link PackageManager#getResourcesForApplicationAsUser}.
*
* @hide
*/
@VisibleForTesting
public static int lookUpResourceId(@NonNull Resources res, @Nullable String resourceName,
@Nullable String resourceType, String packageName) {
if (resourceName == null) {
return 0;
}
try {
try {
// It the name can be parsed as an integer, just use it.
return Integer.parseInt(resourceName);
} catch (NumberFormatException ignore) {
}
return res.getIdentifier(resourceName, resourceType, packageName);
} catch (NotFoundException e) {
Log.e(TAG, "Resource ID for name=" + resourceName + " not found in package "
+ packageName);
return 0;
}
}
@NonNull
CharSequence getQuantityText(@PluralsRes int id, int quantity) throws NotFoundException {
PluralRules rule = getPluralRule();
CharSequence res = mAssets.getResourceBagText(id,
attrForQuantityCode(rule.select(quantity)));
if (res != null) {
return res;
}
res = mAssets.getResourceBagText(id, ID_OTHER);
if (res != null) {
return res;
}
throw new NotFoundException("Plural resource ID #0x" + Integer.toHexString(id)
+ " quantity=" + quantity
+ " item=" + rule.select(quantity));
}
String[] getTheme() {
synchronized (mKey) {
final int N = mKey.mCount;
final String[] themes = new String[N * 2];
for (int i = 0, j = N - 1; i < themes.length; i += 2, --j) {
final int resId = mKey.mResId[j];
final boolean forced = mKey.mForce[j];
try {
themes[i] = getResourceName(resId);
} catch (NotFoundException e) {
themes[i] = Integer.toHexString(i);
}
themes[i + 1] = forced ? "forced" : "not forced";
}
return themes;
}
}
/**
* Extracts a {@link Drawable} from the parent activity's {@code windowBackground}.
*
* {@code android:windowBackground} is specifically reused instead of a other attributes
* because the Android framework can display it fast enough when launching the app as opposed
* to anything defined in the Activity subclass.
*
* Returns null if no {@code windowBackground} is set for the activity.
*/
@SuppressWarnings("deprecation")
private Drawable getLaunchScreenDrawableFromActivityTheme() {
TypedValue typedValue = new TypedValue();
if (!activity.getTheme().resolveAttribute(
android.R.attr.windowBackground,
typedValue,
true)) {;
return null;
}
if (typedValue.resourceId == 0) {
return null;
}
try {
return activity.getResources().getDrawable(typedValue.resourceId);
} catch (NotFoundException e) {
Log.e(TAG, "Referenced launch screen windowBackground resource does not exist");
return null;
}
}
private Drawable resolveResource() {
Resources rsrc = getResources();
if (rsrc == null) {
return null;
}
Drawable d = null;
if (mResource != 0) {
try {
d = rsrc.getDrawable(mResource);
} catch (NotFoundException e) {
// Log.w(TAG, "Unable to find resource: " + mResource, e);
// Don't try again.
mResource = 0;
}
}
return SelectableRoundedCornerDrawable.fromDrawable(d, getResources());
}
public void showToast(String resId, int duration) {
String res = null;
if (TextUtils.empty(resId)) {
resId = "umgr_rcode_fail";
}
try {
res = L10NString.getString(resId);
} catch (NotFoundException e) {
LOG.e(TAG, "[resId:" + resId + "] get string failed(NotFoundException)", e);
}
try {
if (!TextUtils.empty(res)) {
ToastHelper.getInstance().shortOrLongToast((Context) this, res, duration);
}
} catch (NotFoundException e2) {
LOG.e(TAG, "[resId:" + resId + "] show toast failed(NotFoundException)", e2);
}
}
/**
* Obtains the view's background from a specific typed array.
*
* @param typedArray
* The typed array, the background should be obtained from, as an instance of the class
* {@link TypedArray}. The typed array may not be null
*/
private void obtainBackground(@NonNull final TypedArray typedArray) {
Drawable background = typedArray.getDrawable(R.styleable.TabSwitcher_android_background);
if (background == null) {
try {
background = themeHelper.getDrawable(getLayout(), R.attr.tabSwitcherBackground);
} catch (NotFoundException e) {
// There's nothing we can do
}
}
if (background != null) {
ViewUtil.setBackground(this, background);
}
}
/**
* Return the color state list, which should be used to tint the close button of tabs.
*
* @param tab
* The tab, the color state list should be returned for, as an instance of the class
* {@link Tab} or null, if the color state list should not be returned for a specific
* tab
* @return The color state list, which should be used to tint the close button of tabs, as an
* instance of the class {@link ColorStateList} or null, if the close button should not be
* tinted
*/
@Nullable
private ColorStateList getTabCloseButtonIconTintList(@Nullable final Tab tab) {
ColorStateList tintList = tab != null ? tab.getCloseButtonIconTintList() : null;
if (tintList == null) {
tintList = model.getTabCloseButtonIconTintList();
if (tintList == null) {
try {
tintList = themeHelper.getColorStateList(tabSwitcher.getLayout(),
R.attr.tabSwitcherTabCloseButtonIconTint);
} catch (NotFoundException e) {
tintList = null;
}
}
}
return tintList;
}
/**
* Obtains the background of the button bar from the activity's current theme.
*/
private void obtainButtonBarBackground() {
try {
int color =
ThemeUtil.getColor(getActivity(), R.attr.restoreDefaultsButtonBarBackground);
setButtonBarBackgroundColor(color);
} catch (NotFoundException e) {
int resourceId = ThemeUtil
.getResId(getActivity(), R.attr.restoreDefaultsButtonBarBackground, -1);
if (resourceId != -1) {
setButtonBarBackground(resourceId);
} else {
setButtonBarBackgroundColor(
ContextCompat.getColor(getActivity(), R.color.button_bar_background_light));
}
}
}
/**
* Returns the title of the toolbar, which is shown, when the tab switcher is shown. When using
* the tablet layout, the title corresponds to the primary toolbar.
*
* @return The title of the toolbar, which is shown, when the tab switcher is shown, as an
* instance of the type {@link CharSequence} or null, if no title is set
*/
@Nullable
public final CharSequence getToolbarTitle() {
CharSequence title = model.getToolbarTitle();
if (TextUtils.isEmpty(title)) {
try {
title = themeHelper
.getText(tabSwitcher.getLayout(), R.attr.tabSwitcherToolbarTitle);
} catch (NotFoundException e) {
title = null;
}
}
return title;
}
/**
* Returns the color, which corresponds to a specific theme attribute, regarding the theme,
* which is used when using a specific layout.
*
* @param layout
* The layout as a value of the enum {@link Layout}. The layout may not be null
* @param resourceId
* The resource id of the theme attribute, the color should be obtained from, as an
* {@link Integer} value. The resource id must correspond to a valid theme attribute
* @return The color, which has been obtained, as an {@link Integer} value
*/
@ColorInt
public int getColor(@NonNull final Layout layout, @AttrRes final int resourceId) {
try {
return ThemeUtil.getColor(context, resourceId);
} catch (NotFoundException e1) {
int themeResourceId = getThemeResourceId(layout);
try {
return ThemeUtil.getColor(context, themeResourceId, resourceId);
} catch (NotFoundException e) {
themeResourceId = obtainThemeFromThemeAttributes(layout, themeResourceId);
return ThemeUtil.getColor(context, themeResourceId, resourceId);
}
}
}
/**
* Returns the color state list, which corresponds to a specific theme attribute, regarding the
* theme, which is used when using a specific layout.
*
* @param layout
* The layout as a value of the enum {@link Layout}. The layout may not be null
* @param resourceId
* The resource id of the theme attribute, the color state list should be obtained from,
* as an {@link Integer} value. The resource id must correspond to a valid theme
* attribute
* @return The color state list, which has been obtained, as an instance of the class {@link
* ColorStateList}
*/
public ColorStateList getColorStateList(@NonNull final Layout layout,
@AttrRes final int resourceId) {
try {
return ThemeUtil.getColorStateList(context, resourceId);
} catch (NotFoundException e1) {
int themeResourceId = getThemeResourceId(layout);
try {
return ThemeUtil.getColorStateList(context, themeResourceId, resourceId);
} catch (NotFoundException e) {
themeResourceId = obtainThemeFromThemeAttributes(layout, themeResourceId);
return ThemeUtil.getColorStateList(context, themeResourceId, resourceId);
}
}
}
private String getDescriptionOrId(View view) {
String result = view.getContentDescription() != null ? view
.getContentDescription().toString() : null;
if (isNullOrEmpty(result)) {
if (view.getId() != View.NO_ID) {
try {
result = String.format("with id: \"%s\"", view.getContext()
.getResources().getResourceEntryName(view.getId()));
} catch (NotFoundException e) {
result = String.format(Locale.ENGLISH, "with id: \"%d\"",
view.getId());
}
}
} else {
result = String.format("\"%s\"", result);
}
return result;
}
/**
* Updates the view associated to the activity after the finish of an operation trying
* to create a new folder.
*
* @param operation Creation operation performed.
* @param result Result of the creation.
*/
private void onCreateFolderOperationFinish(
CreateFolderOperation operation, RemoteOperationResult result
) {
if (result.isSuccess()) {
refreshListOfFilesFragment();
} else {
try {
Toast msg = Toast.makeText(FolderPickerActivity.this,
ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
Toast.LENGTH_LONG);
msg.show();
} catch (NotFoundException e) {
Log_OC.e(TAG, "Error while trying to show fail message " , e);
}
}
}
/**
* Updates the view associated to the activity after the finish of an operation trying to copy a
* file.
*
* @param operation Copy operation performed.
* @param result Result of the copy operation.
*/
private void onCopyFileOperationFinish(CopyFileOperation operation, RemoteOperationResult result) {
if (result.isSuccess()) {
dismissLoadingDialog();
refreshListOfFilesFragment();
} else {
dismissLoadingDialog();
try {
Toast msg = Toast.makeText(FileDisplayActivity.this,
ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
Toast.LENGTH_LONG);
msg.show();
} catch (NotFoundException e) {
Log_OC.e(TAG, "Error while trying to show fail message ", e);
}
}
}
private Drawable resolveResource() {
Resources rsrc = getResources();
if (rsrc == null) {
return null;
}
Drawable d = null;
if (mResource != 0) {
try {
d = rsrc.getDrawable(mResource);
} catch (NotFoundException e) {
// Log.w(TAG, "Unable to find resource: " + mResource, e);
// Don't try again.
mResource = 0;
}
}
return SelectableRoundedCornerDrawable.fromDrawable(d, getResources());
}
private Drawable resolveResource() {
Resources rsrc = getResources();
if (rsrc == null) {
return null;
}
Drawable d = null;
if (mResource != 0) {
try {
d = rsrc.getDrawable(mResource);
} catch (NotFoundException e) {
Log.w(TAG, "Unable to find resource: " + mResource, e);
// Don't try again.
mResource = 0;
}
}
return SelectableRoundedCornerDrawable.fromDrawable(d, getResources());
}
private String getResourceName() {
try {
return getResources().getResourceEntryName(getId());
} catch (NotFoundException e) {
return "";
}
}
/**
* @see android.content.res.Resources#getColor(int id).
*/
@SuppressWarnings("deprecation")
public static int getColor(Resources res, int id) throws NotFoundException {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return res.getColor(id, null);
} else {
return res.getColor(id);
}
}
private static ObjectAnimator loadObjectAnimator(Resources res, Theme theme, AttributeSet attrs,
float pathErrorScale) throws NotFoundException {
ObjectAnimator anim = new ObjectAnimator();
loadAnimator(res, theme, attrs, anim, pathErrorScale);
return anim;
}
/**
* Gets the human readable media size label.
*
* @param packageManager The package manager for loading the label.
* @return The human readable label.
*/
public @NonNull String getLabel(@NonNull PackageManager packageManager) {
if (!TextUtils.isEmpty(mPackageName) && mLabelResId > 0) {
try {
return packageManager.getResourcesForApplication(
mPackageName).getString(mLabelResId);
} catch (NotFoundException | NameNotFoundException e) {
Log.w(LOG_TAG, "Could not load resouce" + mLabelResId
+ " from package " + mPackageName);
}
}
return mLabel;
}
/**
* Plays the vibration pattern associated with the given resource ID.
*
* @param resId The vibration pattern's resource identifier.
* @return {@code true} if successful.
*/
public boolean playHaptic(int resId, @Nullable EventId eventId) {
if (!mHapticEnabled || resId == 0) {
return false;
}
LogUtils.v(TAG, "playHaptic() resId=%d eventId=%s", resId, eventId);
final int[] patternArray;
try {
patternArray = mResources.getIntArray(resId);
} catch (NotFoundException e) {
LogUtils.e(TAG, "Failed to load pattern %d", resId);
return false;
}
final long[] pattern = new long[patternArray.length];
for (int i = 0; i < patternArray.length; i++) {
pattern[i] = patternArray[i];
}
long nanoTime = System.nanoTime();
for (HapticFeedbackListener listener : mHapticFeedbackListeners) {
listener.onHapticFeedbackStarting(nanoTime);
}
mVibrator.vibrate(pattern, -1);
return true;
}
/**
* Return a string indicating the author(s) of this wallpaper.
*/
public CharSequence loadAuthor(PackageManager pm) throws NotFoundException {
if (mAuthorResource <= 0) throw new NotFoundException();
String packageName = mService.resolvePackageName;
ApplicationInfo applicationInfo = null;
if (packageName == null) {
packageName = mService.serviceInfo.packageName;
applicationInfo = mService.serviceInfo.applicationInfo;
}
return pm.getText(packageName, mAuthorResource, applicationInfo);
}
/**
* Obtains the elevation of the toolbar, which is used to show the bread crumb of the currently
* selected preference fragment, when using the split screen layout.
*/
private void obtainBreadcrumbElevation() {
int elevation;
try {
elevation = ThemeUtil.getDimensionPixelSize(this, R.attr.breadCrumbElevation);
} catch (NotFoundException e) {
elevation = getResources().getDimensionPixelSize(R.dimen.bread_crumb_toolbar_elevation);
}
setBreadCrumbElevation(pixelsToDp(this, elevation));
}
/**
* Retrieves a title of the URI that specifies a link for further context about this wallpaper.
*
* @param pm An instance of {@link PackageManager} to retrieve the title.
* @return The title.
*/
public CharSequence loadContextDescription(PackageManager pm) throws NotFoundException {
if (mContextDescriptionResource <= 0) throw new NotFoundException();
String packageName = mService.resolvePackageName;
ApplicationInfo applicationInfo = null;
if (packageName == null) {
packageName = mService.serviceInfo.packageName;
applicationInfo = mService.serviceInfo.applicationInfo;
}
return pm.getText(packageName, mContextDescriptionResource, applicationInfo).toString();
}
/**
* Load a string resource from the publisher app.
*
* @param resId resource ID
* @param defValue default value to be returned when the specified resource isn't found.
*/
private CharSequence getResourceString(Resources res, int resId, CharSequence defValue) {
try {
return res.getString(resId);
} catch (NotFoundException e) {
Log.e(TAG, "Resource for ID=" + resId + " not found in package " + mPackageName);
return defValue;
}
}
/**
* Obtains the background color of the toolbar, which is used to show the bread crumb of the
* currently selected navigation preference, when using the split screen layout, from the
* activity's theme.
*/
private void obtainBreadCrumbBackgroundColor() {
int color;
try {
color = ThemeUtil.getColor(this, R.attr.breadCrumbBackgroundColor);
} catch (NotFoundException e) {
color = ContextCompat.getColor(this, R.color.bread_crumb_background_light);
}
setBreadCrumbBackgroundColor(color);
}
void getValue(@AnyRes int id, TypedValue outValue, boolean resolveRefs)
throws NotFoundException {
boolean found = mAssets.getResourceValue(id, 0, outValue, resolveRefs);
if (found) {
return;
}
throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id));
}