下面列出了怎么用android.content.ActivityNotFoundException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* open system file manager
*
* @param activity activity
* @param type file type
* @param requestCode code
* @param extraMimeType mimiType must be arrays
*/
private static void select(Activity activity, String type, int requestCode,
String... extraMimeType) {
Intent intent = new Intent();
intent.setType(type);
intent.putExtra(Intent.EXTRA_MIME_TYPES, extraMimeType);
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
try {
activity.startActivityForResult(intent, requestCode);
} catch (ActivityNotFoundException e) {
intent.setAction(Intent.ACTION_GET_CONTENT);
try {
activity.startActivityForResult(intent, requestCode);
} catch (ActivityNotFoundException e2) {
e2.printStackTrace();
}
}
}
private static void applyEvie(Context context, String launcherPackage, String launcherName) {
new MaterialDialog.Builder(context)
.typeface(
TypefaceHelper.getMedium(context),
TypefaceHelper.getRegular(context))
.title(launcherName)
.content(context.getResources().getString(R.string.apply_manual,
launcherName,
context.getResources().getString(R.string.app_name)) + "\n\n" +
context.getResources().getString(R.string.apply_manual_evie,
context.getResources().getString(R.string.app_name)))
.positiveText(android.R.string.ok)
.onPositive((dialog, which) -> {
try {
final Intent intent = context.getPackageManager().getLaunchIntentForPackage(launcherPackage);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
context.startActivity(intent);
((AppCompatActivity) context).finish();
} catch (ActivityNotFoundException | NullPointerException e) {
openGooglePlay(context, launcherPackage, launcherName);
}
})
.negativeText(android.R.string.cancel)
.show();
}
private void handleShare(@NonNull Fingerprint fingerprint, int segmentCount) {
String shareString =
getString(R.string.VerifyIdentityActivity_our_signal_safety_number) + "\n" +
getFormattedSafetyNumbers(fingerprint, segmentCount) + "\n";
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, shareString);
intent.setType("text/plain");
try {
startActivity(Intent.createChooser(intent, getString(R.string.VerifyIdentityActivity_share_safety_number_via)));
} catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), R.string.VerifyIdentityActivity_no_app_to_share_to, Toast.LENGTH_LONG).show();
}
}
private void showWebUI() {
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
//builder.setStartAnimations(mActivity, R.anim.right_in, R.anim.left_out);
builder.setStartAnimations(this, R.anim.activity_open_translate, R.anim.activity_close_scale);
builder.setExitAnimations(this, R.anim.activity_open_scale, R.anim.activity_close_translate);
builder.setToolbarColor(ResourcesCompat.getColor(getResources(), R.color.md_blue_500, null));
// builder.setSecondaryToolbarColor(ResourcesCompat.getColor(getResources(), R.color.md_white_1000, null));
CustomTabsIntent customTabsIntent = builder.build();
try {
customTabsIntent.launchUrl(this, mCurrentServer.getBaseUri());
} catch (ActivityNotFoundException e) {
showToast(getString(R.string.exception_no_chrome));
}
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.contact_image) {
String number = (String)view.getTag();
if (null == number) {
return;
}
Uri contactIdUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
Cursor cursor = activityRef.get().getContentResolver().query(contactIdUri, new String[] {PhoneLookup.CONTACT_ID}, null, null, null);
if (cursor == null || !cursor.moveToFirst()) {
unknownNumberDialog(number);
return;
}
String contactId = cursor.getString(0);
cursor.close();
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.withAppendedPath(Contacts.CONTENT_URI, contactId);
intent.setDataAndType(uri, "vnd.android.cursor.dir/contact");
try {
activityRef.get().startActivity(intent);
} catch (ActivityNotFoundException e) {
activityRef.get().showMissingContactsAppDialog();
}
}
}
private void saveTextFile(@NonNull String filename) {
try {
Intent saveTextFileIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
saveTextFileIntent.addCategory(Intent.CATEGORY_OPENABLE);
saveTextFileIntent.setType("text/plain");
saveTextFileIntent.putExtra(
Intent.EXTRA_TITLE,
filename + ".txt"
);
startActivityForResult(
saveTextFileIntent,
SettingsHelper.FILE_CREATE
);
} catch (ActivityNotFoundException e) {
L.e(e);
showSnackbarWithoutAction(
getString(R.string.message_error_start_file_selector)
);
}
}
private void processIntentForOthers(@NonNull Intent intent) {
final ComponentName preferredCamera = Settings.getInstance().getPreferredCamera();
boolean launched = false;
if (preferredCamera != null) {
Log.d(TAG, "Launch preferred camera: " + preferredCamera.toString());
try {
onStartCameraApp(preferredCamera);
launched = true;
} catch (ActivityNotFoundException e) {
e.printStackTrace();
Settings.getInstance().setPreferredCamera(null);
}
}
if (!launched) {
CameraChooserDialogFragment
.newInstance()
.show(getFragmentManager(), "CameraChooser");
}
}
private void onVoiceClicked() {
// guard against possible race conditions
if (mSearchable == null) {
return;
}
SearchableInfo searchable = mSearchable;
try {
if (searchable.getVoiceSearchLaunchWebSearch()) {
Intent webSearchIntent = createVoiceWebSearchIntent(mVoiceWebSearchIntent,
searchable);
getContext().startActivity(webSearchIntent);
} else if (searchable.getVoiceSearchLaunchRecognizer()) {
Intent appSearchIntent = createVoiceAppSearchIntent(mVoiceAppSearchIntent,
searchable);
getContext().startActivity(appSearchIntent);
}
} catch (ActivityNotFoundException e) {
// Should not happen, since we check the availability of
// voice search before showing the button. But just in case...
Log.w(LOG_TAG, "Could not find voice search activity");
}
}
@OnClick(R.id.about_link_rate)
public void onRate() {
Uri uri = Uri.parse(String.format("market://details?id=%s", BuildConfig.APPLICATION_ID));
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
/* To count with Play market backstack, After pressing back button,
* to taken back to our application, we need to add following flags to intent. */
int flags = Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
flags |= Intent.FLAG_ACTIVITY_NEW_DOCUMENT;
goToMarket.addFlags(flags);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(String.format("http://play.google.com/store/apps/details?id=%s", BuildConfig.APPLICATION_ID))));
}
}
private boolean prepareVpnService() throws ActivityNotFoundException {
Intent prepareVpnIntent = null;
try {
prepareVpnIntent = VpnService.prepare(this);
} catch (NullPointerException e) {
// This exception is not mentioned in the documentation, but it has been encountered by Intra
// users and also by other developers, e.g. https://stackoverflow.com/questions/45470113.
LogWrapper.logException(e);
return false;
}
if (prepareVpnIntent != null) {
Log.i(LOG_TAG, "Prepare VPN with activity");
startActivityForResult(prepareVpnIntent, REQUEST_CODE_PREPARE_VPN);
syncDnsStatus(); // Set DNS status to off in case the user does not grant VPN permissions
return false;
}
return true;
}
@Override
protected StartFragmentAction getStartFragmentAction() {
return new StartFragmentAction() {
@Override
public boolean startFragment(@NonNull UriRequest request, @NonNull Bundle bundle) throws ActivityNotFoundException, SecurityException {
String fragmentClassName = request.getStringField(FragmentTransactionHandler.FRAGMENT_CLASS_NAME);
if (TextUtils.isEmpty(fragmentClassName)) {
Debugger.fatal("FragmentBuildUriRequest.handleInternal()应返回的带有ClassName");
return false;
}
try {
Fragment fragment = Fragment.instantiate(request.getContext(), fragmentClassName, bundle);
if (fragment == null) {
return false;
}
//自定义处理不做transaction,直接放在request里面回调
request.putField(FRAGMENT,fragment);
return true;
} catch (Exception e) {
Debugger.e(e);
return false;
}
}
};
}
public boolean startAuthActivity() {
Intent intent = createAuthActivityIntent();
if (intent == null) {
return false;
}
intent.putExtra(EXTRA_VERSION, PROTOCOL_VERSION);
intent.putExtra(KEY_CLIENT_ID, mRequest.getClientId());
intent.putExtra(KEY_REDIRECT_URI, mRequest.getRedirectUri());
intent.putExtra(KEY_RESPONSE_TYPE, mRequest.getResponseType());
intent.putExtra(KEY_REQUESTED_SCOPES, mRequest.getScopes());
try {
mContextActivity.startActivityForResult(intent, LoginActivity.REQUEST_CODE);
} catch (ActivityNotFoundException e) {
return false;
}
return true;
}
@Override
protected void buildPreferences(@NonNull Context context) {
MaterialStandardPreference importProfiles = new MaterialStandardPreference(context);
importProfiles.setTitle(R.string.importProfiles);
importProfiles.setSummary(R.string.importProfiles_summary);
addPreference(importProfiles);
importProfiles.setOnClickListener(v -> {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
try {
startActivityForResult(Intent.createChooser(intent, "Select a file"), IMPORT_PROFILES_CODE);
} catch (ActivityNotFoundException ex) {
showToast(Toaster.build().message(R.string.noFilemanager));
}
});
MaterialStandardPreference exportProfiles = new MaterialStandardPreference(context);
exportProfiles.setTitle(R.string.exportProfiles);
exportProfiles.setSummary(R.string.exportProfiles_summary);
addPreference(exportProfiles);
exportProfiles.setOnClickListener(v -> doExport());
}
private static void create(Activity activity, String type, int requestCode,
String... extraMimeType) {
Intent intent = new Intent();
// intent.setType(type);
//intent.putExtra(Intent.EXTRA_MIME_TYPES, extraMimeType);
intent.setAction(Intent.ACTION_OPEN_DOCUMENT_TREE);
try {
activity.startActivityForResult(intent, requestCode);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
@NonNull
Request getRequest(
@NonNull Context context,
@NonNull LineAuthenticationConfig config,
@NonNull PKCECode pkceCode,
@NonNull LineAuthenticationParams params)
throws ActivityNotFoundException {
// "state" may be guessed easily but there is no problem as the follows.
// In case of LINE SDK, the correctness of "redirect_uri" will be checked with using PKCE
// instead of "state".
final String oAuthState = createRandomAlphaNumeric(LENGTH_OAUTH_STATE);
authenticationStatus.setOAuthState(oAuthState);
final String openIdNonce;
if (params.getScopes().contains(Scope.OPENID_CONNECT)) {
if (!TextUtils.isEmpty(params.getNonce())) {
openIdNonce = params.getNonce();
} else {
// generate a random string for it, if no `nonce` param specified
openIdNonce = createRandomAlphaNumeric(LENGTH_OPENID_NONCE);
}
} else {
openIdNonce = null;
}
authenticationStatus.setOpenIdNonce(openIdNonce);
final String redirectUri = createRedirectUri(context);
final Uri loginUri = createLoginUrl(config, pkceCode, params, oAuthState, openIdNonce, redirectUri);
AuthenticationIntentHolder intentHolder = getAuthenticationIntentHolder(
context, loginUri, config.isLineAppAuthenticationDisabled());
return new Request(
intentHolder.getIntent(),
intentHolder.getStartActivityOptions(),
redirectUri,
intentHolder.isLineAppAuthentication);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
setTitle(R.string.searchTorrent);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) actionBar.setDisplayHomeAsUpEnabled(true);
message = findViewById(R.id.search_message);
rmv = findViewById(R.id.search_rmv);
rmv.stopLoading();
rmv.disableSwipeRefresh();
rmv.linearLayoutManager(RecyclerView.VERTICAL, false);
rmv.dividerDecoration(RecyclerView.VERTICAL);
Button messageMore = findViewById(R.id.search_messageMore);
messageMore.setOnClickListener(view -> {
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://swaggerhub.com/apis/devgianlu/torrent-search-engine")));
} catch (ActivityNotFoundException ex) {
messageMore.setVisibility(View.GONE);
}
});
searchApi = SearchApi.get();
}
@Override
public View getView(int position, View view, ViewGroup viewGroup) {
ViewHolder holder;
if (view == null) {
view = View.inflate(mContext, R.layout.fragment_other_apps_item_list, null);
holder = new ViewHolder(view);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
CandyBarApplication.OtherApp otherApp = mOtherApps.get(position);
String uri = otherApp.getIcon();
if (!URLUtil.isValidUrl(uri)) {
uri = "drawable://" + DrawableHelper.getResourceId(mContext, uri);
}
ImageLoader.getInstance().displayImage(
uri, holder.image, ImageConfig.getDefaultImageOptions(true));
holder.title.setText(otherApp.getTitle());
if (otherApp.getDescription() == null || otherApp.getDescription().length() == 0) {
holder.desc.setVisibility(View.GONE);
} else {
holder.desc.setText(otherApp.getDescription());
holder.desc.setVisibility(View.VISIBLE);
}
holder.container.setOnClickListener(v -> {
if (!URLUtil.isValidUrl(otherApp.getUrl())) return;
try {
mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(otherApp.getUrl())));
} catch (ActivityNotFoundException e) {
LogUtil.e(Log.getStackTraceString(e));
}
});
return view;
}
@Override
public View getView(int position, View view, ViewGroup viewGroup) {
ViewHolder holder;
if (view == null) {
view = View.inflate(mContext, R.layout.fragment_credits_item_list, null);
holder = new ViewHolder(view);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
Credit credit = mCredits.get(position);
holder.title.setText(credit.getName());
holder.subtitle.setText(credit.getContribution());
holder.container.setOnClickListener(view1 -> {
String link = credit.getLink();
if (URLUtil.isValidUrl(link)) {
try {
mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(link)));
} catch (ActivityNotFoundException e) {
LogUtil.e(Log.getStackTraceString(e));
}
}
});
if (credit.getContribution().length() == 0) {
holder.subtitle.setVisibility(View.GONE);
} else {
holder.subtitle.setVisibility(View.VISIBLE);
}
ImageLoader.getInstance().displayImage(credit.getImage(),
new ImageViewAware(holder.image), mOptions.build(),
new ImageSize(144, 144), null, null);
return view;
}
@Override
public void startActivity(Intent intent) {
if (intent.getStringExtra(Browser.EXTRA_APPLICATION_ID) != null) {
intent.removeExtra(Browser.EXTRA_APPLICATION_ID);
}
try {
super.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.w(TAG, e);
Toast.makeText(this, R.string.ConversationActivity_there_is_no_app_available_to_handle_this_link_on_your_device, Toast.LENGTH_LONG).show();
}
}
private void handleOpenBrowser(String urlString) {
if (TextUtils.isEmpty(urlString)) {
listener.onConsentFormError("No valid URL for browser navigation.");
return;
}
try {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlString));
context.startActivity(browserIntent);
} catch (ActivityNotFoundException exception) {
listener.onConsentFormError("No Activity found to handle browser intent.");
}
}
private static void startInsecureCallInternal(@NonNull Activity activity, @NonNull Recipient recipient) {
try {
Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + recipient.requireSmsAddress()));
activity.startActivity(dialIntent);
} catch (ActivityNotFoundException anfe) {
Log.w(TAG, anfe);
Dialogs.showAlertDialog(activity,
activity.getString(R.string.ConversationActivity_calls_not_supported),
activity.getString(R.string.ConversationActivity_this_device_does_not_appear_to_support_dial_actions));
}
}
private static void showFileExternally(@NonNull Context context, @NonNull MediaDatabase.MediaRecord mediaRecord) {
Uri uri = mediaRecord.getAttachment().getDataUri();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(PartAuthority.getAttachmentPublicUri(uri), mediaRecord.getContentType());
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity existed to view the media.");
Toast.makeText(context, R.string.ConversationItem_unable_to_open_media, Toast.LENGTH_LONG).show();
}
}
@Override
public boolean startFragment(@NonNull UriRequest request, @NonNull Bundle bundle) throws ActivityNotFoundException, SecurityException {
String fragmentClassName = request.getStringField(FragmentTransactionHandler.FRAGMENT_CLASS_NAME);
if (TextUtils.isEmpty(fragmentClassName)) {
Debugger.fatal("FragmentTransactionHandler.handleInternal()应返回的带有ClassName");
return false;
}
if (mContainerViewId == 0) {
Debugger.fatal("FragmentTransactionHandler.handleInternal()mContainerViewId");
return false;
}
try {
Fragment fragment = Fragment.instantiate(request.getContext(), fragmentClassName, bundle);
if (fragment == null) {
return false;
}
FragmentTransaction transaction = mFragmentManager.beginTransaction();
switch (mStartType) {
case TYPE_ADD:
transaction.add(mContainerViewId, fragment, mTag);
break;
case TYPE_REPLACE:
transaction.replace(mContainerViewId, fragment, mTag);
break;
}
if (mAllowingStateLoss) {
transaction.commitAllowingStateLoss();
} else {
transaction.commit();
}
return true;
} catch (Exception e) {
Debugger.e("FragmentTransactionUriRequest",e);
return false;
}
}
private void openFile(String filePath) {
final Uri data = FileProvider.getUriForFile(getApplicationContext(), "edu_cn.pku.course", new File(filePath));
grantUriPermission(getPackageName(), data, Intent.FLAG_GRANT_READ_URI_PERMISSION);
MimeTypeMap myMime = MimeTypeMap.getSingleton();
Intent newIntent = new Intent(Intent.ACTION_VIEW);
String mimeType = myMime.getMimeTypeFromExtension(fileExt(filePath));
newIntent.setDataAndType(data, mimeType);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
newIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(newIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "No handler for this type of file.", Toast.LENGTH_LONG).show();
}
}
public void moreApp() {
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pub:Appkrunch")));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/developer?id=Appkrunch")));
}
}
/**
* Opens the URL on a Custom Tab if possible. Otherwise fallsback to opening it on a WebView.
*
* @param activity The host activity.
* @param customTabsIntent a CustomTabsIntent to be used if Custom Tabs is available.
* @param uri the Uri to be opened.
* @param fallback a CustomTabFallback to be used if Custom Tabs is not available.
*/
public static void openCustomTab(Activity activity,
CustomTabsIntent customTabsIntent,
Uri uri,
CustomTabFallback fallback) {
String packageName = CustomTabsHelper.getPackageNameToUse(activity);
//If we cant find a package name, it means theres no browser that supports
//Chrome Custom Tabs installed. So, we fallback to the webview
//如果使用了不使用Chrome内核,则直接打开
if(UserPreference.queryValueByKey(UserPreference.notUseChrome,"0").equals("1")){
if (fallback != null) {
fallback.openUri(activity, uri);
}
}else {
if (packageName == null) {//普通打开
if (fallback != null) {
fallback.openUri(activity, uri);
}
} else {
customTabsIntent.intent.setPackage(packageName);
try {
customTabsIntent.launchUrl(activity, uri);
}catch (ActivityNotFoundException e){
ALog.d("为什么活动没了?" + e);
//普通方法
if (fallback != null) {
fallback.openUri(activity, uri);
}
}
}
}
}
/**
* Open a file not supported by Amaze
* @param f the file
* @param c
* @param forcechooser force the chooser to show up even when set default by user
*/
public static void openunknown(File f, Context c, boolean forcechooser) {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
String type = MimeTypes.getMimeType(f);
Log.d(TAG, "openunknown " + f + ", " + forcechooser + ", " + type);
if (type != null && type.trim().length() != 0 && !type.equals("*/*")) {
//Uri uri=fileToContentUri(c, f);
//if(uri==null)
Uri uri=Uri.fromFile(f);
intent.setDataAndType(uri, type);
Intent startintent;
if (forcechooser) {
startintent = Intent.createChooser(intent, c.getResources().getString(R.string.openwith));
} else {
startintent = intent;
}
try {
c.startActivity(startintent);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
Toast.makeText(c, R.string.noappfound, Toast.LENGTH_SHORT).show();
openWith(f, c);
}
} else {
// failed to load mime type
openWith(f, c);
}
}
@Override
public void run() {
Intent intent = new Intent();
intent.setAction("com.googlecode.android_scripting.action.LAUNCH_FOREGROUND_SCRIPT");
intent.putExtra("com.googlecode.android_scripting.extra.SCRIPT_PATH", mInstanceState.filename );
intent.setClassName("com.googlecode.android_scripting", "com.googlecode.android_scripting.activity.ScriptingLayerServiceLauncher");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
}
}
public void createContact(String number) {
Intent intent = new Intent(ContactsContract.Intents.Insert.ACTION, ContactsContract.Contacts.CONTENT_URI);
intent.putExtra(ContactsContract.Intents.Insert.PHONE, number);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
showMissingContactsAppDialog();
}
}
private void rateApp() {
Uri uri = Uri.parse("market://details?id=" + context.getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
context.startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
context.startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + context.getPackageName())));
}
}