该代码仅适用于某些Android版本

时间:2017-07-16 23:22:16

标签: android

我想从drawable中保存一张图片。该应用程序有效,但仅适用于API 22以下的Android版本。在较新版本中,图像不会保存在图库中。

我的代码:

public class MainActivity extends AppCompatActivity {

    Bitmap anImage;

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

        Drawable myDrawable = getResources().getDrawable(R.drawable.tapeta1, null);
        anImage = ((BitmapDrawable) myDrawable).getBitmap();
    }

    public void addImageToGallery(View view) {
        int e = view.getId();

        switch (e) {
            case R.id.button:
                saveImageToExternalStorage(anImage);
                Toast.makeText(getApplicationContext(), "Saved successfully, Check gallery", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    private void saveImageToExternalStorage(Bitmap finalBitmap) {
        String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
        File myDir = new File(root + "/saved_images_1");
        myDir.mkdirs();
        Random generator = new Random();
        int n = 10000;
        n = generator.nextInt(n);
        String fname = "Image-" + n + ".jpg";
        File file = new File(myDir, fname);
        if (file.exists())
            file.delete();
        try {
            FileOutputStream out = new FileOutputStream(file);
            finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {
                        Log.i("ExternalStorage", "Scanned " + path + ":");
                        Log.i("ExternalStorage", "-> uri=" + uri);
                    }
                });

    }

}

3 个答案:

答案 0 :(得分:0)

检查您是否已从

授予应用存储权限
  

设置 - >应用 - >您的应用名称 - >权限

如果此解决方案可以解决您的问题,请阅读 - https://developer.android.com/training/permissions/requesting.html

答案 1 :(得分:0)

在通过写入外部存储权限传递oncreate方法调用requestpermissions之前的其他内容之前。这将显示用户授予权限。您可以覆盖活动中的onpermissionsresult以查看权限结果(如果已授予您可以继续保存文件)。如果您不想要所有内容,那么请保存在内部存储中。 getfilesdir方法将为您提供应用程序内部目录的路径,并且不需要运行时权限。

答案 2 :(得分:0)

您需要从应用

请求RunTime permission
if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_READ_CONTACTS);

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    }