Skip to content
Advertisement

How to use PixelCopy API in android java to get bitmap from View

Currently I am using view.getDrawingCache() now get drawing cache is deprecated

view.setDrawingCacheEnabled(true);
Bitmap bitamp = Bitmap.createBitmap(view.getDrawingCache())
view.setDrawingCacheEnabled(false);

view.getDrawingCache() is deprecated in Android API 28

Solution in java code is have getting error Callback

@RequiresApi(api = Build.VERSION_CODES.O)
    public static void getBitmapFormView(View view, Activity activity, Callback callback) {
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);

        int[] locations = new int[2];
        view.getLocationInWindow(locations);
        Rect rect = new Rect(locations[0], locations[1], locations[0] + view.getWidth(), locations[1] + view.getHeight());

        PixelCopy.request(activity.getWindow(), rect, bitmap, copyResult -> {
            if (copyResult == PixelCopy.SUCCESS) {
                callback.onResult(bitmap);
            }
        }, new Handler(Looper.getMainLooper()));
    }

Can not resolve Callback

  • Activity
  • Window
  • Handler

which is supper class of callback ?

Advertisement

Answer

Check this article CallBack interface is OnPixelCopyFinishedListener is available in PixalCopy.java file

/**
 * Listener for observing the completion of a PixelCopy request.
 */
public interface OnPixelCopyFinishedListener {
    /**
     * Callback for when a pixel copy request has completed. This will be called
     * regardless of whether the copy succeeded or failed.
     *
     * @param copyResult Contains the resulting status of the copy request.
     * This will either be {@link PixelCopy#SUCCESS} or one of the
     * <code>PixelCopy.ERROR_*</code> values.
     */
    void onPixelCopyFinished(@CopyResultStatus int copyResult);
}

https://medium.com/@shiveshmehta09/taking-screenshot-programmatically-using-pixelcopy-api-83c84643b02a

Android docs for PixelCopy doc

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement