Wallpaper を替えてみた

壁紙を替えるには WallpaperManager を使用します

替え方は
  • setBitmap(Bitmap bitmap)
  • setResource(int resid)
  • setStream(InputStream data)
の三つから指定します

まず AndroidManifest でパーミッションを設定する必要があります

AndroidManifest.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.   ... >  
  4.     ・  
  5.     ・  
  6.     ・  
  7.   <uses-permission   
  8.     android:name="android.permission.SET_WALLPAPER" />  
  9. </manifest>  

サンプルコード
  1. public class WallpaperSample extends Activity implements OnClickListener {  
  2.   WallpaperManager mWM;  
  3.   
  4.   @Override  
  5.   public void onCreate(Bundle savedInstanceState) {  
  6.     super.onCreate(savedInstanceState);  
  7.     setContentView(R.layout.wallpaper_sample);  
  8.   
  9.     Button button;  
  10.     button = (Button) findViewById(R.id.Button_Set);  
  11.     button.setOnClickListener(this);  
  12.     button = (Button) findViewById(R.id.Button_Clear);  
  13.     button.setOnClickListener(this);  
  14.   
  15.     // WindowManager の取得  
  16.     mWM = WallpaperManager.getInstance(this);  
  17.   
  18.     // 壁紙の最小の幅,最小の高さの取得  
  19.     int width = mWM.getDesiredMinimumWidth();  
  20.     int height = mWM.getDesiredMinimumHeight();  
  21.   }  
  22.   
  23.   @Override  
  24.   public void onClick(View v) {  
  25.     switch(v.getId()) {  
  26.     case R.id.Button_Set:  
  27.       try {  
  28.         // 壁紙をリソースから設定  
  29.         mWM.setResource(R.drawable.icon);  
  30.       } catch (IOException e) {  
  31.         e.printStackTrace();  
  32.       }  
  33.       break;  
  34.     case R.id.Button_Clear:  
  35.       try {  
  36.         // 壁紙をデフォルトに戻す  
  37.         mWM.clear();  
  38.       } catch (IOException e) {  
  39.         e.printStackTrace();  
  40.       }  
  41.       break;  
  42.     }  
  43.   }  
  44. }  

プログラムを実行すると...

変更前
変更後

こんな感じ!

Activity の背景を壁紙にしたいときは
  1. <activity   
  2.   android:name=".activity.WallpaperSample"  
  3.   android:theme="@android:style/Theme.Wallpaper">  
とテーマを指定すればOK

ちなみに
API 2.0以前ではできないので注意!
下記の方法で設定するようです
int width = getWallpaperDesiredMinimumWidth();
int height = getWallpaperDesiredMinimumHeight();
setWallpaper(Bitmap or InputStream);
clearWallpaper();


参考サイト
http://developer.android.com/intl/ja/reference/android/app/WallpaperManager.html

0 件のコメント:

コメントを投稿