private void cw() {
try {
WallpaperManager localWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
try {
if (VERSION.SDK_INT >= 11) {
display.getSize(size);
this.mW = size.x;
this.mH = size.y;
} else {
this.mW = display.getWidth();
this.mH = display.getHeight();
}
} catch (Exception e) {
Toast.makeText(this, "Wallpaper has been set not1.", Toast.LENGTH_SHORT).show();
}
Bitmap localBitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), this.cW[this.i]), this.mW, this.mH, true);
localWallpaperManager.setWallpaperOffsetSteps(1.0f, 1.0f);
localWallpaperManager.suggestDesiredDimensions(this.mW, this.mH);
try {
localWallpaperManager.setBitmap(localBitmap);
Toast.makeText(this, "Wallpaper has been set successfully.",0).show();
} catch (IOException e2) {
Toast.makeText(this, "Wallpaper has been set not2.", Toast.LENGTH_SHORT).show();
}
} catch (Exception e3) {
Toast.makeText(this, "Wallpaper has been set not3.", Toast.LENGTH_SHORT).show();
}
}
答案 0 :(得分:0)
试试这段代码。
bitmap1 = BitmapFactory.decodeFile(ImgPath.getAbsolutePath());
displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
width = displayMetrics.widthPixels;
height = displayMetrics.heightPixels;
bitmap2 = Bitmap.createScaledBitmap(bitmap1, width, height, false);
wallpaperManager = WallpaperManager.getInstance(PagerActivity.this);
try {
wallpaperManager.setBitmap(bitmap2);
wallpaperManager.suggestDesiredDimensions(width, height);
Utils.showToastShort("WallPaper Set !", PagerActivity.this);
} catch (IOException e) {
e.printStackTrace();
}
答案 1 :(得分:0)
您必须在清单文件中设置权限,如下所示:
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
使用以下代码设置背景:
Button buttonSetWallpaper = (Button)findViewById(R.id.set);
ImageView imagePreview = (ImageView)findViewById(R.id.preview);
imagePreview.setImageResource(R.drawable.five);
buttonSetWallpaper.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(R.drawable.five);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});