android接收服务器pdf文件并显示,java – 使用android intent从服务器打开pdf文件

本文介绍了如何在Android应用中创建一个下载器类,通过HTTP请求从指定URL下载PDF文件,并将其存储到设备外部存储。步骤包括创建下载器方法、在MainActivity中调用下载并展示PDF,以及在AndroidManifest.xml中声明持久权限。
摘要由CSDN通过智能技术生成

首先创建一个下载器类

public class Downloader {

public static void DownloadFile(String fileURL, File directory) {

try {

FileOutputStream f = new FileOutputStream(directory);

URL u = new URL(fileURL);

HttpURLConnection c = (HttpURLConnection) u.openConnection();

c.setRequestMethod("GET");

c.setDoOutput(true);

c.connect();

InputStream in = c.getInputStream();

byte[] buffer = new byte[1024];

int len1 = 0;

while ((len1 = in.read(buffer)) > 0) {

f.write(buffer, 0, len1);

}

f.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

之后创建一个从互联网下载PDF文件的活动,

public class MainActivity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

String extStorageDirectory = Environment.getExternalStorageDirectory()

.toString();

File folder = new File(extStorageDirectory, "pdf");

folder.mkdir();

File file = new File(folder, "Read.pdf");

try {

file.createNewFile();

} catch (IOException e1) {

e1.printStackTrace();

}

Downloader.DownloadFile("http://122.248.233.68/pvfiles/Guide-2.pdf", file);

showPdf();

}

public void showPdf()

{

File file = new File(Environment.getExternalStorageDirectory()+"/Mypdf/Read.pdf");

PackageManager packageManager = getPackageManager();

Intent testIntent = new Intent(Intent.ACTION_VIEW);

testIntent.setType("application/pdf");

List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);

Intent intent = new Intent();

intent.setAction(Intent.ACTION_VIEW);

Uri uri = Uri.fromFile(file);

intent.setDataAndType(uri, "application/pdf");

startActivity(intent);

}

}

最后终于在AndroidManifest.xml中声明了持久性

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值