从服务器下载PDF文件,下载完成后可以使用待处理意图打开此PDF文件。
在编写代码之前,请查看下面显示我的附加代码功能的图像。
![enter image description here](https://istack.dev59.com/GKS6O.webp)
步骤 - 1:您需要创建一个异步任务来从服务器 URL 下载文件。请参见以下代码:
public class DownloadFileFromURL extends AsyncTask<String, Integer, String> {
private NotificationManager mNotifyManager;
private NotificationCompat.Builder build;
private File fileurl;
int id = 123;
OutputStream output;
private Context context;
private String selectedDate;
private String ts = "";
public DownloadFileFromURL(Context context, String selectedDate) {
this.context = context;
this.selectedDate = selectedDate;
}
protected void onPreExecute() {
super.onPreExecute();
mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
build = new NotificationCompat.Builder(context);
build.setContentTitle("Download")
.setContentText("Download in progress")
.setChannelId(id + "")
.setAutoCancel(false)
.setDefaults(0)
.setSmallIcon(R.drawable.ic_menu_download);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(id + "",
"Social Media Downloader",
NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("no sound");
channel.setSound(null, null);
channel.enableLights(false);
channel.setLightColor(Color.BLUE);
channel.enableVibration(false);
mNotifyManager.createNotificationChannel(channel);
}
build.setProgress(100, 0, false);
mNotifyManager.notify(id, build.build());
String msg = "Download started";
}
@Override
protected String doInBackground(String... f_url) {
int count;
ts = selectedDate.split("T")[0];
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(),
8192);
output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ Const.DownloadPath + ts + ".pdf");
fileurl = new File(Environment.getExternalStorageDirectory()
+ Const.DownloadPath + ts + ".pdf");
byte[] data = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
int cur = (int) ((total * 100) / lenghtOfFile);
publishProgress(Math.min(cur, 100));
if (Math.min(cur, 100) > 98) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Log.d("Failure", "sleeping failure");
}
}
Log.i("currentProgress", "currentProgress: " + Math.min(cur, 100) + "\n " + cur);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
build.setProgress(100, progress[0], false);
mNotifyManager.notify(id, build.build());
super.onProgressUpdate(progress);
}
@Override
protected void onPostExecute(String file_url) {
build.setContentText("Download complete");
Intent intent = new Intent(context, DownloadBroadcastReceiver.class);
Uri finalurl = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", fileurl);
intent.putExtra("currenturl", finalurl.toString());
intent.putExtra("selectedfilename", ts);
context.sendBroadcast(intent);
build.setProgress(0, 0, false);
mNotifyManager.notify(id, build.build());
} }
在上面的代码中,我使用 DownloadFileFromURL.java 类文件创建了异步任务。在这个类文件中编写了一段代码,在 Android O 和旧版本中显示通知。
步骤2:下载完成后,我将其发送到广播接收器。借助广播接收器,您可以轻松地在待定意图中打开 PDF 文件。您可以在异步任务的 onPostExecute 方法中查看广播接收器代码。
请参见下面的代码以处理广播接收器中的待定意图。
public class DownloadBroadcastReceiver extends BroadcastReceiver {
private NotificationManager mNotifyManager;
private NotificationCompat.Builder build;
private int rId=123;
private String localuri="";
private String selectedfilename="";
@Override
public void onReceive(Context context, Intent intent) {
localuri=intent.getStringExtra("currenturl");
selectedfilename=intent.getStringExtra("selectedfilename");
startNotification(context,intent);
}
private void startNotification(Context context, Intent intent) {
Log.e("fat", "startNotification: "+localuri );
File fileurl = new File(Environment.getExternalStorageDirectory()
+ Const.DownloadPath + selectedfilename+".pdf");
Uri finalurl = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID+".provider", fileurl);
Intent downloadintent = new Intent(Intent.ACTION_VIEW);
downloadintent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_CLEAR_TOP);
downloadintent.setDataAndType(finalurl, "application/pdf");
grantAllUriPermissions(context, downloadintent, finalurl);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, downloadintent,
PendingIntent.FLAG_UPDATE_CURRENT);
mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
build = new NotificationCompat.Builder(context);
build.setContentTitle("Download Completed")
.setContentText("Open Downloaded FIle")
.setChannelId(rId+"")
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setSmallIcon(R.drawable.ic_menu_download);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(rId+"" ,
"Call Reminder",
NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("With sound");
channel.setSound(null,null);
channel.enableLights(false);
channel.setLightColor(Color.BLUE);
channel.enableVibration(true);
mNotifyManager.createNotificationChannel(channel);
}
mNotifyManager.notify(rId, build.build());
}
private void grantAllUriPermissions(Context context, Intent downloadintent, Uri finalurl) {
List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(downloadintent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
context.grantUriPermission(packageName, finalurl, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
} }
在上面的代码中,您可以看到我在通知紧凑建造者中添加了挂起意图。
注意:当您添加待定意图时,您必须使用以下代码分配访问权限,我已经添加了。
downloadintent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_CLEAR_TOP);
grantAllUriPermissions(context, downloadintent, finalurl);
这里创建了GrantAllpermission方法,支持所有设备。
private void grantAllUriPermissions(Context context, Intent downloadintent, Uri finalurl) {
List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(downloadintent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
context.grantUriPermission(packageName, finalurl, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
步骤 -3 : 使用以下代码将您的广播接收器添加到Android清单文件中。
<receiver android:name=".services.DownloadBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
步骤 - 4:在Android清单文件中添加文件提供程序。通过文件提供程序,您可以打开设备存储中的文件。
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_provider_path" />
</provider>
注意:如果您遇到在Android 10(O)设备上的问题,则需要将以下代码添加到您的Android清单文件中的应用程序中。
android:requestLegacyExternalStorage="true"
通过使用requestLegacyExternalStorage,您可以轻松获取已下载文件的列表。
步骤-5:现在最后一步是在单击事件中调用异步类文件。这里我编写了PDF图像单击代码。要调用异步任务,请使用以下代码。
new DownloadFileFromURL(fContext,selectedDate).execute(currentResponse.getData());
您可以从以下链接下载完整的代码文件:
DownloadFileFromURL.java类文件
DownloadBroadcastReceiver.java类文件