Do not forget to add permission settings in applicationmanifest. xml.
<Uses-Permission Android: Name = "android. Permission. set_wallpaper"/>
There are three wallpaper setting methods:
First, use setbitmap () in the wallpapermanager method ()
Second, use setresource () in the wallpapermanager method ()
Third, use the setwallpaper () method provided in the contextwrapper class.
Because activity inherits contextthemewrapper, contextthemewrapper inherits contextwrapper.
<1> call the setbitmap () method in the singleton class by instantiating the wallpapermanager class.
Package xiaosi. wallpaper; </P> <p> Import Java. io. ioexception; </P> <p> Import android. app. activity; <br/> Import android. app. wallpapermanager; <br/> Import android. content. res. resources; <br/> Import android. graphics. bitmap; <br/> Import android. graphics. bitmapfactory; <br/> Import android. OS. bundle; <br/> Import android. widget. toast; </P> <p> public class wallpaperactivity extends activity {<br/>/** called when the activity is first created. */<br/> @ override <br/> Public void oncreate (bundle savedinstancestate) {<br/> super. oncreate (savedinstancestate); <br/> setcontentview (R. layout. main); </P> <p> wallpapermanager = wallpapermanager. getinstance (this); <br/> resources res = getresources (); <br/> Bitmap bitmap = bitmapfactory. decoderesource (Res, R. drawable. h); <br/> try <br/> {<br/> wallpapermanager. setbitmap (Bitmap); <br/>}< br/> catch (ioexception e) <br/>{< br/> E. printstacktrace (); <br/>}< br/>
Method 2: Use setresource () in the wallpapermanager Method ()
Wallpapermanager = wallpapermanager. getinstance (this); <br/> try {<br/> wallpapermanager. setresource (getresources (). getidentifier ("Wallpaper" + imageposition, "drawable", "com. ch "); <br/> toast. maketext (this, "set successfully", toast. length_short ). show (); <br/>}catch (ioexception e) {<br/> E. printstacktrace (); <br/>}< br/>
Method 3: Use the setwallpaper () method provided in the contextwrapper class
// Override the setwallpaper () method in contextwrapper <br/> Public void setwallpaper (inputstream paraminputstream) throws ioexception {<br/> super. setwallpaper (paraminputstream); <br/> toast. maketext (this, "set successfully", 1 ). show (); <br/>}</P> <p> // set the wallpaper <SPAN class = 'wp _ keywordlink '> Code </span> <br/> resources localresources = getbasecontext (). getresources (); <br/> inputstream localinputstream2 = localresources <br/>. openrawresource (getresources (). getidentifier (<br/> "Wallpaper" + imageposition, "drawable", "com. ch "); <br/> try {<br/> setwallpaper (localinputstream2); <br/>} catch (ioexception e) {<br/> E. printstacktrace (); <br/>}