Canvas 在 运行 模式下启动应用程序时对象为空,在调试模式下 运行 时对象具有值

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);
    }

你的 drawImage 方法是什么时候调用的? (来自 activity/fragment 生命周期)。

您无法在 运行 时间内收到的原因,可能是因为您的视图尚未完全绘制在屏幕上,您 canvas 对象所在的位置。

您 canvas 在调试模式下不为空,因为调试模式速度较慢并且有足够的时间进行绘制。

确保您遵循 activity/ 片段生命周期。