BÀI 86 - MỞ ẢNH BẰNG INTENT TRONG ANDROID

  • Giả sử bạn có 1 ảnh vừa tạo với đường dẫn như dưới và muốn mở nó tức thì thì làm như sau:

  • Sau khi tạo xong ảnh sẽ có một thông báo xuất hiện và trên thông báo đó có nút "mở". Khi click mở thì ảnh sẽ tự động hiện ra.

try {

String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();

File myDir = new File(root + "/" + getString(R.string.app_name));

myDir.mkdirs();

String fname = "QR_" + tvTenDuAn.getText() + ".png";

File file = new File(myDir, fname);


FileOutputStream out = new FileOutputStream(file);

bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);

out.flush();

out.close();

Log.e("qrcode", "source -> " + file);


Snackbar snackbar = Snackbar.make(rlCreateQRcode, getString(R.string.da_luu_ma_QR), Snackbar.LENGTH_LONG);

snackbar.setAction(getString(R.string.nut_open), v -> {

Intent intent = new Intent(Intent.ACTION_VIEW);

intent.setDataAndType(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ?

FileProvider.getUriForFile(this,getPackageName() + ".provider", file) : Uri.fromFile(file),

"image/*").addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

startActivity(intent);

});

snackbar.show();

} catch (Exception e) {

Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();

}

  • Nội dung chính trong bài này nằm ở chỗ

Intent intent = new Intent(Intent.ACTION_VIEW);

intent.setDataAndType(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ?

FileProvider.getUriForFile(this,getPackageName() + ".provider", file) : Uri.fromFile(file),

"image/*").addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

startActivity(intent);

  • Nhưng trước tiên bạn sẽ quyền hệ thống trong manifest như này.

  • Cái này nó nằm trong thẻ aplication nhé

<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/provider_paths" />

</provider>

  • Tạo một file xml với tên và đường dẫn như sau: res / xml / provider_paths.xml:

<?xml version="1.0" encoding="utf-8"?>

<paths>

<external-path

name="files_root"

path="Android/data/${applicationId}"/>

<external-path

name="external_storage_root"

path="."/>

</paths>