Search code examples
androidbitmapandroid-canvaslive-wallpaperandroid-wallpaper

Canvas Object is null when app is launched in run mode and object has value when run on debug mode


Im using canvas object to set drawbitmap to set wallpaper change it based > on user selected interval. Canvas object is null when app is launched in run mode and in debug mode its not null. below is my code very strange behaviour

    public MyWallpaperEngine() {
        mImagesArray = new int[] {R.drawable.one,R.drawable.two,R.drawable.three,
                R.drawable.four,R.drawable.five,R.drawable.six,
                R.drawable.seven,R.drawable.eight,R.drawable.nine,
                R.drawable.ten};

        myTimertask = new TimerTask() {
            @Override
            public void run() {
                System.out.println("TIMER SCHEDULED INSIDE RUN");
                drawFrame();
                incrementCounter();
            }
        };
        myTimer.schedule(myTimertask,startInterval,WALLPAPER_DURATION);
    }

    private void incrementCounter() {
        mImagesArrayIndex++;

        if (mImagesArrayIndex >= mImagesArray.length) {
            mImagesArrayIndex = 0;
        }
    }

    private void drawFrame() {
        System.out.println("inside draw frame");
         SurfaceHolder holder = getSurfaceHolder();
        System.out.println("holder Object "+holder);
        Canvas canvas = null;

        try {
            canvas = holder.lockCanvas();
            System.out.println("Canvas Object "+canvas);
            if (canvas != null) {
                System.out.println("inside draw image");
                drawImage(canvas);
            }
        } finally {
            if (canvas != null) {
                holder.unlockCanvasAndPost(canvas);
            }
        }
    }

    private void drawImage(Canvas canvas)
    {
        Bitmap image = BitmapFactory.decodeResource(getResources(),
                mImagesArray[mImagesArrayIndex]);
        Bitmap b=Bitmap.createScaledBitmap(image, canvas.getWidth(), canvas.getHeight(), true);
        canvas.drawBitmap(b, 0,0, null);
    }

Solution

  • When is your drawImage method called ? (From the activity/fragment lifecyle).

    The reason you are not able to receive in run time, might be because your view is not yet completely drawn on the screen, where you canvas object is placed.

    You canvas is not null in debug mode, since debug mode is slower and it gets sufficient time to get drawn.

    Make sure you follow the activity/ fragment lifecycle.