Set Wallpaper using WallpaperManager

In this exercise, a picture (packed inside our app) will be set as system wallpaper, using WallpaperManager.

* Please note that in order to use WallpaperManager, minimum API level have to be set to 5.

Set Wallpaper using WallpaperManager
Set Wallpaper using WallpaperManager

First of all, prepare a picture (wallpaper.png in my case) and save it in /res/drawable/ folder of your project.

main code
package com.exercise.AndroidWallpaper;

import java.io.IOException;

import android.app.Activity;
import android.app.WallpaperManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class AndroidWallpaper extends Activity {

Bitmap bitmap;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button buttonSetWallpaper = (Button)findViewById(R.id.set);
ImageView imagePreview = (ImageView)findViewById(R.id.preview);

imagePreview.setImageResource(R.drawable.wallpaper);

buttonSetWallpaper.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(R.drawable.wallpaper);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}});

}
}


main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/set"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Set Wallpaper"
/>
<ImageView
android:id="@+id/preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>


Finally, you have to modify AndroidManifest.xml to grant permission of "android.permission.SET_WALLPAPER".
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.exercise.AndroidWallpaper"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="5" />
<uses-permission android:name="android.permission.SET_WALLPAPER"></uses-permission>

<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AndroidWallpaper"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

</application>
</manifest>


Download the files.