我遇到以下问题。
当下载文件时,我向用户显示通知,当他/她选择通知时,它会搜索适用的应用程序(示例PDF阅读器)以打开文件。
当我选择通知但是当没有安装PDF阅读器时,Eveything正常工作没有向用户显示toast消息。
是的,有人可以帮助我吗?我知道try块是空的,因为我不知道究竟是什么来调用toast消息。谢谢。
编辑:当我取消注释“context.startActivity(target);”时,它可以正常工作但这会自动启动打开过程,它应该在用户选中通知时启动。
通知代码:
if (file.getName().endsWith(".pdf")) {
Intent install = openPdf(urlPath, context, mNotificationManager,
NOTIFYCATIONID);
PendingIntent pending = PendingIntent.getActivity(context, 0, install, 0);
mBuilder = new NotificationCompat.Builder(context)
.setContentTitle(appName)
.setContentText("ready to open pdf.");
mBuilder.setContentIntent(pending);
mBuilder.setSmallIcon(R.drawable.placeholder);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
}
打开PDF文件的代码:
public static Intent openPdf(String urlPath, Context context,
NotificationManager mNotificationManager, int NOTIFYCATIONID) {
File file = new File(urlPath);
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext = file.getName().substring(file.getName().lastIndexOf(".")+1);
String type = mime.getMimeTypeFromExtension(ext).toLowerCase();;
Intent target = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file));
target.setDataAndType(Uri.fromFile(file), type);
target.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
try {
//context.startActivity(target);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "No application found to open PDF, please install one.", Toast.LENGTH_SHORT).show();
}
mNotificationManager.cancel(NOTIFYCATIONID);
return target;
}
答案 0 :(得分:2)
您不应尝试启动活动以确定它是否存在。相反,您可以使用PackageManager检查是否有可以处理您的Intent的Activity,而无需启动它。
尝试以下方法之一(它们都是等效的):
PackageManager pm = context.getPackageManager();
if (pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) == null) {
Toast.makeText(context, "No application found to open PDF, please install one.", Toast.LENGTH_SHORT).show();
}
或:
PackageManager pm = context.getPackageManager();
if (intent.resolveActivity(pm) == null) {
Toast.makeText(context, "No application found to open PDF, please install one.", Toast.LENGTH_SHORT).show();
}
或:
PackageManager pm = context.getPackageManager();
if (pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) == 0) {
Toast.makeText(context, "No application found to open PDF, please install one.", Toast.LENGTH_SHORT).show();
}
而不是取消openPdf
中的通知,如果没有可用的应用并且根本不尝试显示通知,则只需返回null
。