2

我想创建一个应用程序,允许用户通过单击按钮将图像设置为墙纸。该图像将位于 url 中,墙纸的设置是通过 AsyncTask 执行的。我已按照此视频中所示的步骤操作:https ://www.youtube.com/watch?v=JeA8Z8dtD10但它对我不起作用。该应用程序显示了该按钮,但是当我单击它时,会发生任何事情。

这是代码:

package com.example.myapplication4;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.WallpaperManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.net.ssl.HttpsURLConnection;

public class MainActivity extends Activity {

public ProgressDialog progressDialog;

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

    Button btnSetWallpaper = (Button) findViewById(R.id.button);

    btnSetWallpaper.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String urlImage ="https://www.geektopia.es/storage/geek/posts/2015/08/17/marshmallow.jpg";
            new SetWallpaperTask().equals(urlImage);

        }
    });
}

public InputStream OpenHttpConnection (String urlString)
throws IOException
{
    InputStream in = null;
    int response = -1;
    URL url = new URL (urlString);
    URLConnection conn = url.openConnection();

    if (!(conn instanceof HttpsURLConnection)) {
        throw new IOException("Not an HTTP connection");
    }

    try {
        HttpsURLConnection httpCon = (HttpsURLConnection)conn;
        httpCon.setInstanceFollowRedirects(true);
        httpCon.setRequestMethod("Get");
        httpCon.connect();
        response = httpCon.getResponseCode();
        if (response == HttpsURLConnection.HTTP_OK) {
            in = httpCon.getInputStream();
        }
    }catch (Exception ex) {
        throw new IOException("Error connecting...");
    }
    return in;
}

public Bitmap DecodeStream (String url) {
    Bitmap bitmap = null;
    InputStream in = null;
    try {
        in = OpenHttpConnection(url);
        bitmap = BitmapFactory.decodeStream(in);
        in.close();
    }
    catch (IOException e) {
        Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
    }
    return bitmap;
}

public class SetWallpaperTask extends AsyncTask <String, Void, Bitmap> {

    @Override
    protected Bitmap doInBackground(String... params) {

        Bitmap bitmap = DecodeStream(params[0]);
        return bitmap;
    }

    @Override
    protected void onPostExecute (Bitmap result) {
        super.onPostExecute(result);

        WallpaperManager wallpaperManager = WallpaperManager.getInstance(getBaseContext());
        try {
            wallpaperManager.setBitmap(result);
            progressDialog.dismiss();
            Toast.makeText(getApplicationContext(), "Set wallpaper successfully", Toast.LENGTH_SHORT).show();


        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    protected void onPreExecute () {
        super.onPreExecute();

        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Please wait...");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return super.onCreateOptionsMenu(menu);
}
}

编辑:

public class MainActivity extends Activity {

public ProgressDialog progressDialog;

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

    Button btnSetWallpaper = (Button) findViewById(R.id.button);

    btnSetWallpaper.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new SetWallpaperTask();
        }
    });
}

public class SetWallpaperTask extends AsyncTask <String, Void, Bitmap> {

    @Override
    protected Bitmap doInBackground(String... params) {
        Bitmap result= null;
        try {
            result = Picasso.with(getApplicationContext())
                    .load("https://www.geektopia.es/storage/geek/posts/2015/08/17/marshmallow.jpg")
                    .get();
        } catch (IOException e) {
            e.printStackTrace();
        }

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

    @Override
    protected void onPostExecute (Bitmap result) {
        super.onPostExecute(result);

        WallpaperManager wallpaperManager = WallpaperManager.getInstance(getBaseContext());
        try {
            wallpaperManager.setBitmap(result);
            progressDialog.dismiss();
            Toast.makeText(getApplicationContext(), "Set wallpaper successfully", Toast.LENGTH_SHORT).show();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    protected void onPreExecute () {
        super.onPreExecute();

        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Please wait...");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return super.onCreateOptionsMenu(menu);
}
}

我还向 Manifest 添加了 INTERNET 和 SET_WALLPAPER 权限。你知道错误在哪里吗?太感谢了 :)

4

3 回答 3

16

而不是尝试自己下载图像然后必须处理它。而是使用像 Picasso 这样的图像加载库。使用毕加索,您需要在点击监听器中添加以下内容:

Bitmap result=Picasso.with(context)
          .load(imageURL)
          .get();

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

无需处理线程即可轻松轻松。

于 2015-10-16T19:39:39.413 回答
2

您需要 Picasso 库从 url 获取位图
以添加最新库https://github.com/square/picasso

String url ="https://..."
Target target = new Target() {
    @Override
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
        Log.e(TAG, "OnBitmapLoaded");
        WallpaperManager wallpaperManager = WallpaperManager.getInstance(BroadcastService.this);
        try {
            wallpaperManager.setBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "IOException->" + e.getMessage());
        }
    }

    @Override
    public void onBitmapFailed(Exception e, Drawable errorDrawable) {
        Log.e(TAG, "" + e.getMessage());
    }

    @Override
    public void onPrepareLoad(Drawable placeHolderDrawable) {
        Log.e(TAG, "OnPrepareLoad");
    }
};
Picasso.get().load(url).into(target);
于 2019-08-27T04:39:57.960 回答
0
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
                Bitmap bitmap=((BitmapDrawable)wallpaper.getDrawable()).getBitmap();
                wallpaperManager.setBitmap(bitmap);
                Toast.makeText(getApplicationContext(),"Wallpaper set Successfully",
                            Toast.LENGTH_LONG).show();


public static Bitmap viewToBitmap(View view,int width,int height){
        Bitmap bitmap=Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
        Canvas canvas=new Canvas(bitmap);
        view.draw(canvas);
        return bitmap;
    }
于 2021-07-02T07:06:07.227 回答