别忘记在ApplicationManifest.xml 中加上权限的设置。
<uses-permission Android:name = "android.permission.SET_WALLPAPER"/>
壁纸设置方法有三种:
第一 通过WallpaperManager方法中的 setBitmap()
第二 通过WallpaperManager方法中的 setResource()
第三 通过ContextWrapper 类中提供的setWallpaper()方法
由于 Activity 继承ContextThemeWrapper ,ContextThemeWrapper继承 ContextWrapper.
<1>通过实例化WallpaperManager 类调用单例类中setBitmap()方法。
[java] view plain copy
- package xiaosi.Wallpaper;
- import java.io.IOException;
- import android.app.Activity;
- import android.app.WallpaperManager;
- import android.content.res.Resources;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.os.Bundle;
- import android.widget.Toast;
- public class WallpaperActivity extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
- Resources res = getResources();
- Bitmap bitmap=BitmapFactory.decodeResource(res,R.drawable.h);
- try
- {
- wallpaperManager.setBitmap(bitmap);
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- }
第二种方法:通过WallpaperManager方法中的 setResource()
[java] view plain copy
- WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
- try {
- wallpaperManager.setResource(getResources().getIdentifier("wallpaper" + imagePosition, "drawable", "com.ch"));
- Toast.makeText(this, "设置成功", Toast.LENGTH_SHORT).show();
- } catch (IOException e) {
- e.printStackTrace();
- }
第三种方法:通过ContextWrapper 类中提供的setWallpaper()方法
[java] view plain copy
- //重写ContextWrapper中setWallpaper()方法
- public void setWallpaper(InputStream paramInputStream) throws IOException {
- super.setWallpaper(paramInputStream);
- Toast.makeText(this, "设置成功", 1).show();
- }
- //设置壁纸代码
- Resources localResources = getBaseContext().getResources();
- InputStream localInputStream2 = localResources
- .openRawResource(getResources().getIdentifier(
- "wallpaper" + imagePosition, "drawable", "com.ch"));
- try {
- setWallpaper(localInputStream2);
- } catch (IOException e) {
- e.printStackTrace();
- }
时间: 2024-10-10 11:14:11