On an Android device we can add an image as a wallpaper ("Wallpaper"),
What are the methods to programmatically add an image as background on an Android device?.
Add an image as Wallpaper on Android .
You must first register the permission:
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
To add assign an image as a wallpaper, you can add an image stored in the project resources as Wallpaper or an image from an internet url:
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(R.drawable.androide); //*Agrega imagen de recursos como Wallpaper
} catch (IOException e) {
e.printStackTrace();
}
You can also add an image from a url, and assign it as a Wallpaper, in this second option you must perform the download process on a thread different from the main one to avoid the error NetworkonMainThreadException , to avoid this you must use a Thread, Asynctask , Handler, etc.
This is an example of a method which we call this way:
setWallpaper(" Url imagen ");
This is the complete method:
private void setWallpaper(final String urlImage) {
try {
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
URL url = new URL(urlImage);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myImage = BitmapFactory.decodeStream(input);
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
wallpaperManager.setBitmap(myImage);
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
} catch (Exception error) {
Log.e("Loading Image", "Error : " + error.getMessage());
}
}
The way to change the wallpaper of a phone programmatically is through the WallpaperManager class .
This class has several methods to change the background, get the current wallpaper, delete the wallpaper, etc.
In this other answer that I gave, I mentioned how to do it, change the wallpaper of the home and lock screen, resize according to the density of the screen, put it fixed, etc. See it from here .
The other way to change the wallpaper is based on an Intent. An example:
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA)
.setDataAndType(mUri, "image/*")
.putExtra("mimeType", "image/*")
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(Intent.createChooser(intent, null),
REQUEST_CODE_CROPANDSETWALLPAPER);
Here what it does is to request a selector of the applications that agree with the action of the intent. Based on this the user can choose which application to change the wallpaper.
If you have any questions, let me know.