Android学习笔记进阶21之设置壁纸

本文介绍了在Android应用中设置壁纸的三种方法:使用WallpaperManager的setBitmap()和setResource()方法,以及通过ContextWrapper的setWallpaper()方法。提供了具体的代码实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

别忘记在ApplicationManifest.xml 中加上权限的设置。

<uses-permission android:name = "android.permission.SET_WALLPAPER"/>

壁纸设置方法有三种:

第一 通过WallpaperManager方法中的 setBitmap()

第二 通过WallpaperManager方法中的 setResource()

第三 通过ContextWrapper 类中提供的setWallpaper()方法

由于 Activity 继承ContextThemeWrapper ,ContextThemeWrapper继承 ContextWrapper.

<1>通过实例化WallpaperManager 类调用单例类中setBitmap()方法。

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()

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()方法

//重写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(); }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值