MainActivity:
package com.hyzhou.imagedemo; import java.io.File; import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu; public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//设置当前Activity界面布局
setContentView(R.layout.activity_main);
//SD卡路径
File sd=Environment.getExternalStorageDirectory();
String path=sd.getPath()+"/image/zhizhi.jpg";
//通过BitmapFactory获得Bitmap实例
Bitmap bm=BitmapFactory.decodeFile(path);
try {
//设置桌面
setWallpaper(bm);
} catch (Exception e) {
e.printStackTrace();
}
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
} }
注意:一定要记得在Android Manifest.xml中加入下面语句,声明拥有修改壁纸的权限,不然setWallpaper()方法不起作用
<uses-permission android:name="android.permission.SET_WALLPAPER"/>