如何从Picasso库加载图像并将其设置为墙纸

时间:2017-08-06 04:26:11

标签: java android picasso

我从毕加索图书馆收到了互联网上的照片。 然后我把它设置在壁纸上。 但在我的手机上运行后,我接近了原力。 如果您在编码时出错,请帮助我,或者如果建议您工作,请提供帮助。

  Bitmap result= null;
    try {
        result = Picasso.with(getApplicationContext())
                .load("http://wallpaperswide.com/download/the_amazing_spider_man_2012_film-wallpaper-1600x900.jpg")
                .get();
    } catch (IOException e) {
        e.printStackTrace();
    }

    WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
    try {
        wallpaperManager.setBitmap(result);
    } catch (IOException ex) {
        ex.printStackTrace();
    }

1 个答案:

答案 0 :(得分:1)

假设您在MainActivity中:

package com.example.myapplication;

import android.app.WallpaperManager;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Picasso.with(this).load("http://wallpaperswide.com/download/the_amazing_spider_man_2012_film-wallpaper-1600x900.jpg").into(new Target(){

            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                WallpaperManager wallpaperManager = WallpaperManager.getInstance(MainActivity.this);
                try {
                    wallpaperManager.setBitmap(bitmap);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                Log.d("TAG", "onBitmapLoaded: ");
                Toast.makeText(MainActivity.this, "Wallpaper Changed", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onBitmapFailed(final Drawable errorDrawable) {
                Log.d("TAG", "FAILED");
                Toast.makeText(MainActivity.this, "Loading image failed", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onPrepareLoad(final Drawable placeHolderDrawable) {
                Log.d("TAG", "Prepare Load");
                Toast.makeText(MainActivity.this, "Downloading image", Toast.LENGTH_SHORT).show();
            }
        });

    }

}

确保:

  • 您使用此导入import com.squareup.picasso.Target;代替import java.lang.annotation.Target;
  • 您在AndroidManifest.xml中授予INTERNET权限和SET_WALLPAPER权限。 <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.SET_WALLPAPER" />

最后:  等待图像下载然后检查你的设备主屏幕瞧!!!“