为什么我不能将FrameLayout保存为Bitmap并将其保存在手机中?

时间:2017-01-02 08:45:54

标签: android bitmap android-framelayout

我想将FrameLayout保存为图片并将其保存在手机中。 FrameLayout位于相对布局中。 FrameLayout有一个ImageViewTextView

 public class ImageText extends AppCompatActivity {
private static final String TAG = "   a    ";
FrameLayout frameLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_image_text);
    final FrameLayout frameLayout = (FrameLayout)findViewById(R.id.frame);
    TextView tv1=(TextView)findViewById(R.id.textView1);

    Intent intent=getIntent();
    tv1.setText(intent.getStringExtra("text"));


    Button bt = (Button) findViewById(R.id.button3);
    bt.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            isStoragePermissionGranted();
            saveFrameLayout(frameLayout);
        }

    });
}


         public static void saveFrameLayout(FrameLayout frameLayout) {
        frameLayout.setDrawingCacheEnabled(true);
        frameLayout.buildDrawingCache();
        Bitmap cache = frameLayout.getDrawingCache();
        frameLayout.setDrawingCacheEnabled(false);

        try {
            FileOutputStream fileOutputStream = new FileOutputStream(Environment.getExternalStorageDirectory()+ "file.png");
            cache.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (Exception e) {
           e.printStackTrace();
        } finally {
            frameLayout.destroyDrawingCache();

        }
    }
public  boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG,"Permission is granted");
            return true;
        } else {

            Log.v(TAG,"Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG,"Permission is granted");
        return true;
    }
}

}

布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_image_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.user.notesk1.ImageText">
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
    android:id="@+id/frame"
    >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:src="@drawable/a"
        android:layout_gravity="center"

        />

    <TextView
    android:id="@+id/textView1"
    android:layout_width="250dp"
    android:layout_height="wrap_content"
        android:layout_gravity="center"
    android:text="text"
        android:textColor="#ffffff"
    android:textAppearance="?android:attr/textAppearanceLarge" />

</FrameLayout>

<Button
    android:text="Save"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="16dp"
    android:id="@+id/button3"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true" />

</RelativeLayout>

logcat的:

01-02 12:03:26.941 5166-10018/? W/System.err: remove failed: ENOENT (No such file or directory) : /data/user/0/com.touchtype.swiftkey/files/iris_messages_cache
    01-02 12:03:26.961 8083-8083/? W/System.err: java.io.FileNotFoundException: /storage/emulated/0file.png: open failed: EACCES (Permission denied)
    01-02 12:03:26.971 8083-8083/? W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:452)
    01-02 12:03:26.971 8083-8083/? W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:87)
    01-02 12:03:26.971 8083-8083/? W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:127)
    01-02 12:03:26.971 8083-8083/? W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:116)
    01-02 12:03:26.971 8083-8083/? W/System.err:     at com.example.user.notesk1.ImageText.saveFrameLayout(ImageText.java:58)
    01-02 12:03:26.971 8083-8083/? W/System.err:     at com.example.user.notesk1.ImageText$1.onClick(ImageText.java:44)
    01-02 12:03:26.971 8083-8083/? W/System.err:     at android.view.View.performClick(View.java:5714)
    01-02 12:03:26.971 8083-8083/? W/System.err:     at android.widget.TextView.performClick(TextView.java:10926)
    01-02 12:03:26.971 8083-8083/? W/System.err:     at android.view.View$PerformClick.run(View.java:22589)
01-02 12:03:26.971 8083-8083/? W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
01-02 12:03:26.971 8083-8083/? W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
01-02 12:03:26.971 8083-8083/? W/System.err:     at android.os.Looper.loop(Looper.java:148)
01-02 12:03:26.971 8083-8083/? W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:7325)
01-02 12:03:26.971 8083-8083/? W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
01-02 12:03:26.971 8083-8083/? W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
01-02 12:03:26.971 8083-8083/? W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
01-02 12:03:26.971 8083-8083/? W/System.err: Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
01-02 12:03:26.971 8083-8083/? W/System.err:     at libcore.io.Posix.open(Native Method)
01-02 12:03:26.971 8083-8083/? W/System.err:     at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
01-02 12:03:26.971 8083-8083/? W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:438)
01-02 12:03:26.971 8083-8083/? W/System.err:    ... 15 more

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

更改isStoragePermissionGranted()方法

    private void isStoragePermissionGranted() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (!checkIfAlreadyhavePermission()) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            } else {
                saveFrameLayout(frameLayout);
            }
        } else {
            saveFrameLayout(frameLayout);
        }
    }

private boolean checkIfAlreadyhavePermission() {
    int result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    return result == PackageManager.PERMISSION_GRANTED;
}

抓住许可结果:

public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                saveFrameLayout(frameLayout);

            } else {
                permission_denied();
            }
            break;
        }
        // other 'case' lines to check for other
        // permissions this app might request
    }
}

public void permission_denied() {
    // permission was not granted
    if (ActivityCompat.shouldShowRequestPermissionRationale(ImageText.this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        showDialogOK("Permission is required for register",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case DialogInterface.BUTTON_POSITIVE:
                                showCity();
                                break;
                            case DialogInterface.BUTTON_NEGATIVE:
                                // proceed with logic by disabling the related features or quit the app.
                                break;
                        }
                    }
                });
    } //permission is denied (and never ask again is  checked)
    //shouldShowRequestPermissionRationale will return false
    else {
        Toast.makeText(getApplicationContext(), "Go to settings and enable External storage permissions", Toast.LENGTH_LONG).show();
    }
}

显示权限对话框:

private void showDialogOK(String message, DialogInterface.OnClickListener okListener) {
    new AlertDialog.Builder(getActivity())
            .setMessage(message)
            .setPositiveButton("OK", okListener)
            .setNegativeButton("Cancel", okListener)
            .create()
            .show();
}

希望这能解决您的许可相关问题......