web-dev-qa-db-fra.com

Ouvrir un fichier sélectionné (image, pdf, ...) par programme à partir de mon application Android?

Je travaille sur une application Android qui devrait pouvoir ouvrir un fichier sélectionné à partir d'un dossier spécifique.

J'ai déjà essayé cela, mais après avoir sélectionné l'application que je veux ouvrir, j'ai reçu le message suivant:

Chargement impossible

Après avoir essayé beaucoup de thread 1 et thread 2 , j'utilise ces lignes de code pour le faire:

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("/mnt/sdcard/xxx/xxx/Pictures/xxx.jpg"), "image/*");
myContext.startActivity(intent);

Comment puis-je comprendre cela?

15
13KZ

Essayez le code ci-dessous. J'utilise ce code pour ouvrir un fichier PDF. Vous pouvez également l'utiliser pour d'autres fichiers.

File file = new File(Environment.getExternalStorageDirectory(),
                     "Report.pdf");
Uri path = Uri.fromFile(file);
Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW);
pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfOpenintent.setDataAndType(path, "application/pdf");
try {
    startActivity(pdfOpenintent);
}
catch (ActivityNotFoundException e) {

}

Si vous souhaitez ouvrir des fichiers, vous pouvez modifier la setDataAndType(path, "application/pdf"). Si vous souhaitez ouvrir différents fichiers avec la même intention, vous pouvez utiliser Intent.createChooser(intent, "Open in...");. Pour plus d'informations, consultez Comment créer une intention avec plusieurs actions.

26
Ameer

Utilisez ce code, ce qui m'a aidé à ouvrir tous les types de fichiers ... 

 private void openFile(File url) {

    try {

        Uri uri = Uri.fromFile(url);

        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (url.toString().contains(".doc") || url.toString().contains(".docx")) {
            // Word document
            intent.setDataAndType(uri, "application/msword");
        } else if (url.toString().contains(".pdf")) {
            // PDF file
            intent.setDataAndType(uri, "application/pdf");
        } else if (url.toString().contains(".ppt") || url.toString().contains(".pptx")) {
            // PowerPoint file
            intent.setDataAndType(uri, "application/vnd.ms-PowerPoint");
        } else if (url.toString().contains(".xls") || url.toString().contains(".xlsx")) {
            // Excel file
            intent.setDataAndType(uri, "application/vnd.ms-Excel");
        } else if (url.toString().contains(".Zip") || url.toString().contains(".rar")) {
            // WAV audio file
            intent.setDataAndType(uri, "application/x-wav");
        } else if (url.toString().contains(".rtf")) {
            // RTF file
            intent.setDataAndType(uri, "application/rtf");
        } else if (url.toString().contains(".wav") || url.toString().contains(".mp3")) {
            // WAV audio file
            intent.setDataAndType(uri, "audio/x-wav");
        } else if (url.toString().contains(".gif")) {
            // GIF file
            intent.setDataAndType(uri, "image/gif");
        } else if (url.toString().contains(".jpg") || url.toString().contains(".jpeg") || url.toString().contains(".png")) {
            // JPG file
            intent.setDataAndType(uri, "image/jpeg");
        } else if (url.toString().contains(".txt")) {
            // Text file
            intent.setDataAndType(uri, "text/plain");
        } else if (url.toString().contains(".3gp") || url.toString().contains(".mpg") ||
                url.toString().contains(".mpeg") || url.toString().contains(".mpe") || url.toString().contains(".mp4") || url.toString().contains(".avi")) {
            // Video files
            intent.setDataAndType(uri, "video/*");
        } else {
            intent.setDataAndType(uri, "*/*");
        }

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(context, "No application found which can open the file", Toast.LENGTH_SHORT).show();
    }
}
6
Ameen Maheen

Télécharger le code source ici ( https://deepshikhapuri.wordpress.com/2017/04/24/open-pdf-file-from-sdcard-in-Android-programmatically/ )

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:

package 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 + “-“);
}
}
}
}

Merci!

2
Deepshikha Puri

Essayez le code suivant.

File file = new File(path); // path = your file path
lastSlash = file.toString().lastIndexOf('/');

if (lastSlash >= 0)
{
    fileName = url.toString().substring(lastSlash + 1);
}


if (fileName.endsWith("pdf"))
{
    mimeType = "application/pdf";
}
else
{
    mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension
    (MimeTypeMap.getFileExtensionFromUrl(path));
}

Uri uri_path = Uri.fromFile(file);

Intent intent = new Intent(Android.content.Intent.ACTION_VIEW);
intent.putExtra(PATH, path);
intent.putExtra(MIMETYPE, mimeType);
intent.setType(mimeType);
intent.setDataAndType(uri_path, mimeType);

startActivity(intent);
1
Andrain

directement, vous pouvez utiliser ce code, il ouvrira tout type de fichier 

Intent sharingIntent = new Intent(Intent.ACTION_VIEW);
    Uri screenshotUri = Uri.fromFile(your_file);
    sharingIntent.setType("image/png");
    sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
    String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(screenshotUri.toString()));
    sharingIntent.setDataAndType(screenshotUri, type == null ? "text/plain" : type);
    startActivity(Intent.createChooser(sharingIntent, "Share using"));
0
balu

Tu peux essayer ça 

File file = new File(filePath);
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());
String type = map.getMimeTypeFromExtension(ext);

if (type == null)
    type = "*/*";

Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.fromFile(file);

intent.setDataAndType(data, type);

startActivity(intent);
0
Anish Bhandari