首先咱們要把一張本身喜歡的圖片放到sdcard中,總之,只要咱們能夠獲取這個圖片就能夠了。 java
我這裏是放在sdcard中的,能夠在eclipse中用鼠標點擊導入,比較方便,也能夠在命令行中運行: android
C:\Documents and Settings\Administrator>adb push "C:\Documents and Settings\Administrator\My Documents\My Pictures\MM-320x480.png" /sdcard/MM-320x480.png app
package com.android.test; import java.io.File; import java.io.IOException; import android.app.Activity; import android.app.WallpaperManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Environment; import android.widget.Toast; public class WallPaperActivity extends Activity { public static final String FILE_NAME = "MM-320x480.png"; @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bitmap wall = getWallPaper(); setWallPaper(wall); } //從sdcard中獲取圖片 private Bitmap getWallPaper() { //拿到sdcard的根目錄的路徑 File root = Environment.getExternalStorageDirectory(); //拿到sdcard中指定的圖片 File wall = new File(root, FILE_NAME); //拿到圖片的絕對路徑 String path = wall.getAbsolutePath(); System.out.println("path = " + path); //根據圖片的絕對路徑獲取圖片 return BitmapFactory.decodeFile(path); } //將獲取的圖片設置爲牆紙 private void setWallPaper(Bitmap wall) { //獲取一個牆紙管理器的對象 WallpaperManager wManager = WallpaperManager.getInstance(this); try { //將對應的圖片設置爲牆紙 wManager.setBitmap(wall); } catch (IOException e) { String msg = "設置桌面背景異常:" + e.getLocalizedMessage(); System.out.println("設置桌面背景異常:" + msg); Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); e.printStackTrace(); } } }
代碼註釋比較詳細。 eclipse
首先獲取sdcard的路徑,而後從sdcard中找到那個文件,獲取那個文件的路徑,而後從BitmapFactory中構建這張圖片。 ide
獲取圖片以後,須要將圖片設置爲牆紙。 this
只須要從牆紙管理器中獲取一個對象,而後調用wManager.setBitmap(wall)就ok了 spa
其實設置牆紙很簡單,有木有 命令行
哦,對了,別忘記了在manif.xml文件中加入能夠設置牆紙的權限: code
<uses-permission android:name="android.permission.SET_WALLPAPER"></uses-permission> xml
若是你是圖片比較大,屏幕顯示不徹底,建議你考慮縮放, 在這句代碼前將wall縮放到適應屏幕:wManager.setBitmap(wall);能夠使用:wall = Bitmap.createScaledBitmap(wall, width, height, true); 裏面的width和height分別是屏幕的寬和高。 能夠從這裏面獲取: WindowManager windowManager = getWindowManager(); Display display = windowManager.getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight();