在AsyncTask中使用Picasso从URL获取位图

时间:2016-06-02 19:01:49

标签: java android bitmap android-asynctask picasso

编辑:我有"方法调用..."错误已修复。现在我的主要问题实际上是从我的URL加载位图。我显然没有正确处理它,当我尝试使用PIcasso中的java.lang.OutOfMemoryError方法时,我得到了.get()

最好的方法是什么?我甚至不需要整个图像,只需要一个中心裁剪来填充我的设备上的壁纸。但是我无法在不加载它的情况下裁剪它,这是我的问题。

所以我尝试使用Picasso从给定的URL获取位图,然后在其上面绘制文本并将其设置为我的壁纸背景。我目前正在尝试从AsyncTask中的onPostExecute执行此操作。我得到的错误是:

java.lang.IllegalStateException: Method call should not happen from the main thread.

导致问题的代码行是:

Bitmap bitmap = Picasso.with(myContext)
                .load(url + ".jpg")
                .fit()
                .centerCrop()
                .get();

和整个onPostExcute函数:

protected void onPostExecute(String url) {

    ImageView imageView = (ImageView) rootView.findViewById(R.id.preview);
    try {
        Bitmap bitmap = Picasso.with(myContext)
                .load(url + ".jpg")
                .fit()
                .centerCrop().get();

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setColor(Color.RED); //Text Color
        paint.setStrokeWidth(72); //Text Size
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER)); //Text Overlapping Pattern

        canvas.drawBitmap(bitmap, 0, 0, paint);
        canvas.drawText("Test...", 10, 10, paint);

        ((ImageView) rootView.findViewById(R.id.preview)).setImageBitmap(bitmap);
        WallpaperManager wallpaperManager = WallpaperManager.getInstance(myContext);
        //wallpaperManager.suggestDesiredDimensions(width, height);
        wallpaperManager.setBitmap(bitmap);

        Toast.makeText(myContext, "Wallpaper set successfully.", Toast.LENGTH_SHORT).show();
    }
    catch (Exception e) {
        android.util.Log.e(TAG, "Failed to set wallpaper", e);
    }
}

我甚至无法测试所有画布/油漆代码以查看它是否有效。如果你在那里看到任何错误,请告诉我。任何和所有提示都非常感谢。感谢。

1 个答案:

答案 0 :(得分:0)

将@ jayeshsolanki93和@zapl评论放在一起。您收到该错误是因为您在主线程上从get()调用方法Picassoget()是同步方法,因此是错误。您有两种选择:

  1. get()的{​​{1}}调用方法移至doInBackground的{​​{1}}方法,然后在AsyncTask上执行所有画布操作。
  2. 充分利用Picasso并使用已有的异步方法并执行以下操作:

    onPostExecute