一行程式碼完成Android 7 FileProvider適配~
阿新 • • 發佈:2019-01-23
適配FileProvide需要宣告provider,編寫xml,以及在程式碼中做版本適配等…
可以抽取一個小庫簡化這些重複性操作,避免重複宣告provider,編寫xml,以及在程式碼中做版本適配…
使用
compile 'com.zhy.base:fileprovider:1.0.0'
通過FileProvider7這個類完成uri的獲取即可,例如:
FileProvider7.getUriForFile
FileProvider7.setIntentDataAndType
FileProvider7.setIntentData
示例一 拍照
private static final int REQUEST_CODE_TAKE_PHOTO = 0x110;
private String mCurrentPhotoPath;
public void takePhotoNoCompress(View view) { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) { String filename = new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.CHINA) .format(new Date()) + ".png"; File file = new File(Environment.getExternalStorageDirectory(), filename); mCurrentPhotoPath = file.getAbsolutePath(); // 僅需改變這一行 Uri fileUri = FileProvider7.getUriForFile(this, file); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); startActivityForResult(takePictureIntent, REQUEST_CODE_TAKE_PHOTO); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_TAKE_PHOTO) { mIvPhoto.setImageBitmap(BitmapFactory.decodeFile(mCurrentPhotoPath)); } // else tip? }
示例二 安裝apk
public void installApk(View view) { File file = new File(Environment.getExternalStorageDirectory(), "testandroid7-debug.apk"); Intent intent = new Intent(Intent.ACTION_VIEW); // 僅需改變這一行 FileProvider7.setIntentDataAndType(this, intent, "application/vnd.android.package-archive", file, true); startActivity(intent); }