liweiyap / xkcdbrowser-android

Simple browser app on Android for the XKCD comic. Comic-strip metadata is retrieved from the XKCD website in JSON format.
https://xkcd.com/
MIT License
0 stars 0 forks source link

`MediaStore.Images.Media.insertImage()` is deprecated from API 28, but in my alternative code, the saved image is deleted as soon as the OutputStream is closed. #1

Open liweiyap opened 3 years ago

liweiyap commented 3 years ago
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
{
    ContentResolver contentResolver = getContentResolver();
    ContentValues contentValues = new ContentValues();
    contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
    contentValues.put(MediaStore.Images.Media.IS_PENDING, true);
    contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, mComicTitleTextView.getText().toString());
    contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");

    Uri imageUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
    Bitmap bitmap = ((BitmapDrawable) mComicPhotoView.getDrawable()).getBitmap();
    try {
        OutputStream fos = contentResolver.openOutputStream(imageUri);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();

        contentValues.put(MediaStore.MediaColumns.IS_PENDING, false);
        contentValues.clear();
        contentResolver.update(imageUri, contentValues, null, null);

        fos.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}
liweiyap commented 3 years ago

Need to open a new FileInputStream and copy from the FileOutputStream to the FileInputStream. For reference, see equivalent function in the BigImageViewer library.