Android - Copy image to clipboard, anyone got this

2019-06-07 23:34发布

问题:

I am trying to copy a image file from my apk to the clipboard.

Here is how I am approaching it (roughly, i'm using a content provider locally which is out of the scope of the question.

        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, filename.getAbsolutePath());
        ContentResolver theContent = getContentResolver();
        Uri imageUri = theContent.insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
        ClipData theClip = ClipData.newUri(getContentResolver(), "Image", imageUri);
        mClipboard.setPrimaryClip(theClip);

With this code two things can happen:

1) java.lang.IllegalStateException: Unable to create new file 2) When pasting it only pastes the URI itself, not the image (even in compatible apps)

I don't see any example of anyone getting image pasting on android working, and I have searched for an answer extensively, both on google and stack overflow.

Can anyone help with this? I would really appreciate someones assistance here.

PS: If it's just not possible to do I would also like to know that, to save wasting anymore time on this.

Thanks!

回答1:

There is no indication that such functionality is supported in Android.

The behavior is correct and the uri is the copied data not the bitmap.

It depends on whether the place you are pasting in can handle this uri.



回答2:

you can not copy that to clipboard because its impossible; but you can do that by copying that to sdcard and then access that from every where that you want;

here is some code that helped me a lot and can help you too:

Context Context = getApplicationContext();
String DestinationFile = "the place that you want copy image there like sdcard/...";
if (!new File(DestinationFile).exists()) {
  try {
    CopyFromAssetsToStorage(Context, "the pictures name in assets folder of your project", DestinationFile);
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
}

private void CopyFromAssetsToStorage(Context Context, String SourceFile, String DestinationFile) throws IOException {
  InputStream IS = Context.getAssets().open(SourceFile);
  OutputStream OS = new FileOutputStream(DestinationFile);
  CopyStream(IS, OS);
  OS.flush();
  OS.close();
  IS.close();
}
private void CopyStream(InputStream Input, OutputStream Output) throws IOException {
  byte[] buffer = new byte[5120];
  int length = Input.read(buffer);
  while (length > 0) {
    Output.write(buffer, 0, length);
    length = Input.read(buffer);
  }
}