Set image as wallpaper from url
Asked Answered
E

3

2

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.

Here is the code:

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

EDIT:

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

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

Eastbourne answered 16/10, 2015 at 19:31 Comment(1)
new SetWallpaperTask(); or new SetWallpaperTask().execute()Cohabit
X
17

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.

Xenogamy answered 16/10, 2015 at 19:39 Comment(4)
Thanks. That's nice to load the image and display it in the layout, but how to set it as wallpaper?Moorman
Thank you for your response. I've placed the code inside doInBackground as I would like to do it via AsyncTask. But I does not do anything. I have edited my answer. Thank you.Moorman
Already got it, just forgot to execute task. Thanks for your help! :)Moorman
@Xenogamy 'Picasso.with(context)' throwing error cannot resolve method withSatisfied
T
2

You need Picasso library to get bitmap from url
To Add Latest Library 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);
Transverse answered 27/8, 2019 at 4:39 Comment(2)
what is BroadcastService.this ?Enlace
that's the activity @FernandoTorresIrita
K
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;
    }
Kerek answered 2/7, 2021 at 7:6 Comment(1)
Need explanation what is going onMausoleum

© 2022 - 2024 — McMap. All rights reserved.