在网页或其他地方长按图片可以给我把图片复制到设备剪贴板的机会。请看下面:
现在我想把这个功能实现到我的应用程序中。目前为止,我已经做了以下工作:
代码
Bitmap bitmap = getBitmap();
File file = storeImage(bitmap, name);
//Share
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
Uri uri = Uri.fromFile(file);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
//Add Copy to Clipboard to choosers
Intent clipboard = new Intent(this, CopyToClipboardImageActivity.class);
clipboard.setData(uri);
Intent chooserIntent = Intent.createChooser(shareIntent, getString(R.string.shareScreenshot));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{clipboard});
startActivity(chooserIntent);
CopyToClipboardImageActivity
public class CopyToClipboardImageActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Uri uri = getIntent().getData();
if (uri != null) {
copyImageToClipboard(uri);
Toast.makeText(this, getString(R.string.hinweisInZwischenablageKopiert), Toast.LENGTH_SHORT).show();
}
// Finish right away. We don't want to actually display a UI.
finish();
}
private void copyImageToClipboard(Uri uri) {
ClipboardManager mClipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ContentValues values = new ContentValues(2);
values.put(MediaStore.Images.Media.MIME_TYPE, "Image/jpg");
values.put(MediaStore.Images.Media.DATA, "file://"+uri.getPath());
ContentResolver theContent = getContentResolver();
Uri imageUri = theContent.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
ClipData theClip = ClipData.newUri(getContentResolver(), "Image", imageUri);
mClipboard.setPrimaryClip(theClip);
}
}
但是目前还无法实现。要么只会将奇怪的路径复制到剪贴板中(见上图^^),要么会出现以下NullpointerException:
尝试在空对象引用上调用虚拟方法“java.lang.String android.net.Uri.getScheme()”
这个错误发生在这一行:
ClipData theClip = ClipData.newUri(getContentResolver(), "Image", imageUri);