Android学习笔记进阶21之设置壁纸

别忘记在ApplicationManifest.xml 中加上权限的设置。

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

壁纸设置方法有三种:

        第一 通过WallpaperManager方法中的 setBitmap()

第二 通过WallpaperManager方法中的 setResource()

第三 通过ContextWrapper 类中提供的setWallpaper()方法

       由于 Activity 继承ContextThemeWrapper ,ContextThemeWrapper继承 ContextWrapper.

<1>通过实例化WallpaperManager 类调用单例类中setBitmap()方法。

  1. package xiaosi.Wallpaper;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import android.app.Activity;  
  6. import android.app.WallpaperManager;  
  7. import android.content.res.Resources;  
  8. import android.graphics.Bitmap;  
  9. import android.graphics.BitmapFactory;  
  10. import android.os.Bundle;  
  11. import android.widget.Toast;  
  12.   
  13. public class WallpaperActivity extends Activity {  
  14.     /** Called when the activity is first created. */  
  15.     @Override  
  16.     public void onCreate(Bundle savedInstanceState) {  
  17.         super.onCreate(savedInstanceState);  
  18.         setContentView(R.layout.main);  
  19.           
  20.         WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);  
  21.         Resources res = getResources();  
  22.         Bitmap bitmap=BitmapFactory.decodeResource(res,R.drawable.h);   
  23.         try  
  24.         {  
  25.             wallpaperManager.setBitmap(bitmap);  
  26.         }  
  27.         catch (IOException e)  
  28.         {  
  29.             e.printStackTrace();  
  30.         }  
  31.     }  

 

 第二种方法:通过WallpaperManager方法中的 setResource()

  1. WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);  
  2.     try {  
  3.         wallpaperManager.setResource(getResources().getIdentifier("wallpaper" + imagePosition, "drawable", "com.ch"));  
  4. Toast.makeText(this, "设置成功", Toast.LENGTH_SHORT).show();  
  5.     } catch (IOException e) {  
  6.         e.printStackTrace();  
  7. }  

第三种方法:通过ContextWrapper 类中提供的setWallpaper()方法

  1. //重写ContextWrapper中setWallpaper()方法  
  2. public void setWallpaper(InputStream paramInputStream) throws IOException {  
  3.         super.setWallpaper(paramInputStream);  
  4.         Toast.makeText(this, "设置成功", 1).show();  
  5. }  
  6.   
  7. //设置壁纸代码  
  8.                         Resources localResources = getBaseContext().getResources();  
  9.             InputStream localInputStream2 = localResources  
  10.                     .openRawResource(getResources().getIdentifier(  
  11.                             "wallpaper" + imagePosition, "drawable", "com.ch"));  
  12.             try {  
  13.                 setWallpaper(localInputStream2);  
  14.             } catch (IOException e) {  
  15.                 e.printStackTrace();  
  16.             }  
原文地址:https://www.cnblogs.com/Free-Thinker/p/6722167.html