web-dev-qa-db-ja.com

SDカードからインテント経由でPDFを開く方法

Intentを起動して、アプリのアセットフォルダー内でPDFを開こうとしています。数十件の記事を読みましたが、まだ行き詰っています。どうやら、まずpdfをsdカードにコピーしてからIntentを起動する必要があります。それでも動作しません。

問題はIntentの起動だと思うので、このコードを使用してSDカードにコピーしたファイル「example.pdf」を開こうとしています。

Log.w("IR", "TRYING TO RENDER: " + Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf"), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

try {
    startActivity(intent);
    Log.e("IR", "No exception");
} 
catch (ActivityNotFoundException e) {
    Log.e("IR", "error: " + e.getMessage());
    Toast.makeText(InvestorRelations.this, 
        "No Application Available to View PDF", 
        Toast.LENGTH_SHORT).show();
}

これは私のLogCat出力です。

05-10 10:35:10.950: W/IR(4508): TRYING TO RENDER: /mnt/sdcard/example.pdf
05-10 10:35:10.960: E/IR(4508): No exception

このコードが実行される場合を除いて、次のToastを取得します(アプリによって生成されません)

「サポートされていないドキュメントタイプ」

しかし、インストールされたPDF表示アプリを使用して手動でドキュメントを開くことができます。どんな助けでも大歓迎です。

46
Mike T

このコードを試して、/ sdcardからPDFファイルを表示します

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
118
user370305

Android Nougat以降のバージョンAndroidいくつかの作業が必要です。さもないと、アプリは.pdfファイルを開けません。 URIを使用してFileProviderに一時的な許可を設定します

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
   File file=new File(mFilePath);
   Uri uri = FileProvider.getUriForFile(this, getPackageName() + ".provider", file);
   intent = new Intent(Intent.ACTION_VIEW);
   intent.setData(uri);
   intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
   startActivity(intent);
   } else {
   intent = new Intent(Intent.ACTION_VIEW);
   intent.setDataAndType(Uri.parse(mFilePath), "application/pdf");
   intent = Intent.createChooser(intent, "Open File");
   intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   startActivity(intent);
   }
10
Kapil Rajput

ここからソースコードをダウンロードします( sdcardのpdfファイルをAndroidプログラムで で開きます)

この依存関係を追加します。

compile ‘com.github.barteksc:Android-pdf-viewer:2.0.3’

activity_main.xml:

<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:Android=”http://schemas.Android.com/apk/res/Android&#8221;
xmlns:tools=”http://schemas.Android.com/tools&#8221;
Android:id=”@+id/activity_main”
Android:layout_width=”match_parent”
Android:layout_height=”match_parent”
Android:background=”#efefef”>

<ListView
Android:layout_width=”match_parent”
Android:id=”@+id/lv_pdf”
Android:divider=”#efefef”
Android:layout_marginLeft=”10dp”
Android:layout_marginRight=”10dp”
Android:layout_marginTop=”10dp”
Android:layout_marginBottom=”10dp”
Android:dividerHeight=”5dp”
Android:layout_height=”wrap_content”>

</ListView>
</RelativeLayout>

MainActivity.Java:

package com.pdffilefromsdcard;

import Android.Manifest;
import Android.app.ProgressDialog;
import Android.content.Intent;
import Android.content.pm.PackageManager;
import Android.os.Environment;
import Android.support.v4.app.ActivityCompat;
import Android.support.v4.content.ContextCompat;
import Android.support.v7.app.AppCompatActivity;
import Android.os.Bundle;
import Android.util.Log;
import Android.view.View;
import Android.widget.AdapterView;
import Android.widget.ListView;
import Android.widget.Toast;

import Java.io.File;
import Java.util.ArrayList;
import Java.util.HashMap;
import Java.util.List;

public class MainActivity extends AppCompatActivity {

ListView lv_pdf;
public static ArrayList<File> fileList = new ArrayList<File>();
PDFAdapter obj_adapter;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
File dir;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();

}

private void init() {

lv_pdf = (ListView) findViewById(R.id.lv_pdf);
dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
fn_permission();
lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PdfActivity.class);
intent.putExtra(“position”, i);
startActivity(intent);

Log.e(“Position”, i + “”);
}
});
}

public ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {

if (listFile[i].isDirectory()) {
getfile(listFile[i]);

} else {

boolean booleanpdf = false;
if (listFile[i].getName().endsWith(“.pdf”)) {

for (int j = 0; j < fileList.size(); j++) {
if (fileList.get(j).getName().equals(listFile[i].getName())) {
booleanpdf = true;
} else {

}
}

if (booleanpdf) {
booleanpdf = false;
} else {
fileList.add(listFile[i]);

}
}
}
}
}
return fileList;
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {

if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);

}
} else {
boolean_permission = true;

getfile(dir);

obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);

}
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {

if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

boolean_permission = true;
getfile(dir);

obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);

} else {
Toast.makeText(getApplicationContext(), “Please allow the permission”, Toast.LENGTH_LONG).show();

}
}
}

}

activity_pdf.xml:

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:Android=”http://schemas.Android.com/apk/res/Android&#8221;
Android:layout_width=”match_parent”
Android:background=”#ffffff”
Android:layout_height=”match_parent”
Android:orientation=”vertical”>

<com.github.barteksc.pdfviewer.PDFView
Android:id=”@+id/pdfView”
Android:layout_margin=”10dp”
Android:layout_width=”match_parent”
Android:layout_height=”match_parent” />
</LinearLayout>

PdfActivity.Java:

パッケージcom.pdffilefromsdcard;

import Android.os.Bundle;
import Android.support.annotation.Nullable;
import Android.support.v7.app.AppCompatActivity;
import Android.util.Log;

import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;

import Java.io.File;
import Java.util.List;

public class PdfActivity extends AppCompatActivity implements OnPageChangeListener,OnLoadCompleteListener {

PDFView pdfView;
Integer pageNumber = 0;
String pdfFileName;
String TAG=”PdfActivity”;
int position=-1;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
init();
}

private void init(){
pdfView= (PDFView)findViewById(R.id.pdfView);
position = getIntent().getIntExtra(“position”,-1);
displayFromSdcard();
}

private void displayFromSdcard() {
pdfFileName = MainActivity.fileList.get(position).getName();

pdfView.fromFile(MainActivity.fileList.get(position))
.defaultPage(pageNumber)
.enableSwipe(true)

.swipeHorizontal(false)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(new DefaultScrollHandle(this))
.load();
}
@Override
public void onPageChanged(int page, int pageCount) {
pageNumber = page;
setTitle(String.format(“%s %s / %s”, pdfFileName, page + 1, pageCount));
}
@Override
public void loadComplete(int nbPages) {
PdfDocument.Meta meta = pdfView.getDocumentMeta();
printBookmarksTree(pdfView.getTableOfContents(), “-“);

}

public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
for (PdfDocument.Bookmark b : tree) {

Log.e(TAG, String.format(“%s %s, p %d”, sep, b.getTitle(), b.getPageIdx()));

if (b.hasChildren()) {
printBookmarksTree(b.getChildren(), sep + “-“);
}
}
}
}

ありがとう!

3
Deepshikha Puri

受け入れられた答えは今では時代遅れです。 ファイル共有 には FileProvider を使用します。

1
artkoenig

それは、assetsフォルダー内のファイルが圧縮されるという事実と関係があるかもしれません。

res/raw/フォルダーに移動してみてください。

詳細: https://stackoverflow.com/a/4432804/413127

0
Blundell