将图片设置为来自url的墙纸 [英] Set image as wallpaper from url

查看:989
本文介绍了将图片设置为来自url的墙纸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create an app which allows the user set an image as wallpaper by clicking a button. This image would be located in an url, and the setting of wallpaper is performed via AsyncTask. I've followed the steps as shown in this video: https://www.youtube.com/watch?v=JeA8Z8dtD10 but it doesn't work for me. The app shows the button, but when I click it anything happens.

这是代码:

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


我还向清单添加了INTERNET和SET_WALLPAPER权限.您知道错误在哪里吗?非常感谢:)


I have also added INTERNET and SET_WALLPAPER permissions to the Manifest. Do you know where the error is? Thank you so much :)

推荐答案

而不是尝试自己下载图像然后进行处理.而是使用像Picasso这样的图像加载库.使用毕加索,您需要放入点击侦听器的所有内容是:

Rather than trying to download the image yourself and then having to process it. Instead use an image loading library like Picasso. With Picasso all you need to put into your click listener is:

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

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

好又容易,无需处理线程.

Nice and easy without having to deal with threading.

这篇关于将图片设置为来自url的墙纸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆