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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s