gpt4 book ai didi

java - 使用android intent从服务器打开pdf文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:50:25 26 4
gpt4 key购买 nike

我正在网上搜索如何使用 Android 上的默认 pdf 查看器从服务器打开 pdf 文件。我发现的是先下载文件,然后有意启动它或使用 google 文档加载它。我不想做所有这些。我只想在手机的默认 pdf 查看器中直接从服务器加载它。我试过有意地打开视频网址并且它有效。但是有意打开 pdf url 是行不通的。下面是我的代码;

private void openFilePDF(){
try{
Toast.makeText(getBaseContext(), "Opening PDF... ", Toast.LENGTH_SHORT).show();
Intent inte = new Intent(Intent.ACTION_VIEW);
inte.setDataAndType(
Uri.parse("http://122.248.233.68/pvfiles/Guide-2.pdf"),
"application/pdf");

startActivity(inte);
}catch(ActivityNotFoundException e){
Log.e("Viewer not installed on your device.", e.getMessage());
}
}

有什么方法可以在 Intent 中加载 pdf url 吗?

最佳答案

首先创建一个下载器类

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 文件的 Activity ,

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 中声明权限

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

关于java - 使用android intent从服务器打开pdf文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20603713/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com