Set the wallpaper from code in Android

During android application you may need to set wallpaper using code, then you have to use following method.

public void setStream (InputStream data)

For that you need to include the following permission to your menifest file.

<uses-permission android:name="android.permission.SET_WALLPAPER"></uses-permission>

I’ve made the method that will directly set the wallpaper image specified in argument.

public void setWallpaper(String pathToImage)    {
    try {
        WallpaperManager wpm = WallpaperManager.getInstance(getApplicationContext());
	    InputStream ins = new URL("file://" + pathToImage).openStream();
	    wpm.setStream(ins);
	    Toast.makeText(getApplicationContext(), "Wallpaper has been set", Toast.LENGTH_SHORT).show();            
    } 
    catch (MalformedURLException e) {
        e.printStackTrace();
    } 
    catch (IOException e) {
        e.printStackTrace();
    }     
}

Here we have to specify “file://” which specify the protocol which we use here. We can also use http, ftp, etc. Otherwise it throws “java.net.MalformedURLException: Protocol not found: ” exception.