문제

I have a custom View that is extending ImageView (called PieView) and since this is one of the allowed views to be included in RemoteViews, this should theoretically work.

I am sending a Notification to the device's notification bar using NotificationCompat.Builder with a custom View, which includes a blank ImageView, which I want to replace with my custom class (which is a descendant of ImageView).

Here's what I use to build the Notification:

    final PieView pie = new PieView(c);

    // My own method that redraws the View using this.invalidate()
    pie.setRam(totalRam, freeRam);

    pie.setDrawingCacheEnabled(true);
    pie.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    pie.layout(0, 0, pie.getMeasuredWidth(), pie.getMeasuredHeight());
    pie.buildDrawingCache(true);

    Bitmap bitmap = Bitmap.createBitmap(pie.getDrawingCache());

    pie.setDrawingCacheEnabled(false);

    remoteViews.setImageViewBitmap(R.id.ivPie, bitmap);

    mBuilder.setContent(remoteViews);

However, this results in java.lang.NullPointerException on the following line:

Bitmap bitmap = Bitmap.createBitmap(pie.getDrawingCache());

I am assuming the View is not drawn yet since it's not placed anywhere in the layout. How to work around this issue? I am familiar that only a portion of Views are supported to be included in the Notification's body, but there must surely be a way to pre-create my custom View as a static image and add it to the (allowed) ImageView using RemoteViews.

도움이 되었습니까?

해결책

I have a custom View that is extending ImageView (called PieView) and since this is one of the allowed views to be included in RemoteViews, this should theoretically work.

Since there is no PieView in Android, it cannot be "one of the allowed views to be included in RemoteViews", and it will not work, in theory or in practice. While ImageView is allowed, subclasses are not.

How to work around this issue?

Draw your pie to a Bitmap, perhaps via a Bitmap-backed Canvas, and apply the Bitmap using setImageViewBitmap() on RemoteViews. However, bear in mind that the overall RemoteViews structure needs to be reasonably small (under 1MB), so do not make your bitmap too big.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top