0
我遇到以下问题。未安装pdf阅读器时未显示消息
当一个文件被下载时,我会向用户显示一个通知,当他/她选择通知时,它会搜索适用的应用程序(例如PDF阅读器)以打开文件。
Eveything在我选中通知但是没有安装PDF阅读器时工作没有烤面包信息显示给用户。
有人可以帮助我吗?我知道try块是空的,因为我不知道到底是什么来调用toast消息。
谢谢。
编辑:它的工作原理当我取消注释“context.startActivity(目标);”但是这会自动启动打开的过程,它应该在用户选择通知时启动。
通知码:
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;
}
Thx Marcin,我得到一个错误,说:resolveActivity(PackageManager)不能应用于(PackageManager,int)。 我把你的代码放在openPDF方法中。 (target.resolveActivity(pm,PackageManager.MATCH_DEFAULT_ONLY)== null) – Simon
是的,对不起。该方法应该在下午不打算的时候被调用。我更新了我的答案。 –
由于类似问题的答案中提到了几种等效的方法,我只是将它们全部列出。 –