0

我的应用程序在图像视图中显示图像。我希望用户从应用程序本身中选择设置图片作为选项。像这样 设置为选项

如何添加“设置为”弹出菜单,以便用户可以直接将图像设置为墙纸?图像已经存储在 Drawable 文件夹中。

4

1 回答 1

0

您可以将以下代码用于“将图片设置为”。在这里,我正在截取当前活动的屏幕截图。然后我将该活动存储为位图。之后,我将该活动提供给“设置为选项”的意图

在按钮单击:

OnButtonClick(){
ImageProcessing imageProcessing = new ImageProcessing();
            Bitmap bitmap = imageProcessing.takeScreenshot(getWindow().getDecorView().findViewById(R.id.view_thought));
            imageProcessing.saveBitmap(bitmap);
            Intent intent = imageProcessing.setAsOption(this,imageProcessing.getSavedImagePath());
            startActivityForResult(Intent.createChooser(intent, "Set image as"), 200);
}

实现一个新类 ImageProcessing

public class ImageProcessing {
private File imagesPath;
public void saveBitmap(Bitmap bitmap) {
    imagesPath = new File(Environment.getExternalStorageDirectory() + "/screenshot.jpg");
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(imagesPath);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        Log.e("POS", e.getMessage(), e);
    } catch (IOException e) {
        Log.e("POS", e.getMessage(), e);
    }
}
public File getSavedImagePath(){
    imagesPath = new File(Environment.getExternalStorageDirectory() + "/screenshot.jpg");
    return imagesPath;
}

public Bitmap takeScreenshot(View rootView) {
    rootView.setDrawingCacheEnabled(true);
    return rootView.getDrawingCache();
}
public Intent setAsOption(Context cntxt,File imagesPath){
    /*File imagesPath = new File(Environment.getExternalStorageDirectory() + "/screenshot.jpg");*/
    Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
    if(imagesPath.exists()){
        Uri contentUri = FileProvider.getUriForFile(cntxt, BuildConfig.APPLICATION_ID+".Utility.GenericFileProvider",imagesPath);

        intent.setDataAndType(contentUri, "image/jpg");
        intent.putExtra("mimeType", "image/jpg");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }else {
        Toast.makeText(cntxt,"Not a wallpaper",Toast.LENGTH_SHORT).show();
    }
    return intent;
}

}

在清单中添加:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />
于 2017-12-22T22:07:25.647 回答