Android设置壁纸的几种方案

来源:互联网 发布:dendi知乎 编辑:程序博客网 时间:2024/05/22 02:01

Android设置壁纸有许多方法,主要思路有两种:

1:通过WallpaperManager设置

2:通过系统程序设置

下文将分开说明:


<1>通过WallpaperManager设置

该方法可以直接将图片置为壁纸,对于所有平台的Android系统都使用,但无法裁剪/调整图片。

try {    WallpaperManager wpm = (WallpaperManager) getActivity().getSystemService(                Context.WALLPAPER_SERVICE);    if (wallpaper != null) {       wpm.setBitmap(bitmap);       Log.i("xzy", "wallpaper not null");    }} catch (IOException e) {    Log.e(TAG, "Failed to set wallpaper: " + e);}

AndroidManifest.xml中需要申明权限:

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

<2>通过系统程序设置

通过系统应用设置的优点是可以裁剪图片,设置后的壁纸效果最好,操作体验和平台保持一致。并且该方法不许要申明权限


可行的方法有两种

1:调用系统裁剪Activity,通过裁剪Activity设置壁纸:

            Intent intent = new Intent("com.android.camera.CropImage");            int width = getActivity().getWallpaperDesiredMinimumWidth();            int height = getActivity().getWallpaperDesiredMinimumHeight();            intent.putExtra("outputX",         width);            intent.putExtra("outputY",         height);            intent.putExtra("aspectX",         width);            intent.putExtra("aspectY",         height);            intent.putExtra("scale",           true);            intent.putExtra("noFaceDetection", true);            intent.putExtra("setWallpaper",    true);            intent.putExtra("data", ((BitmapDrawable) wallpaper).getBitmap());            startActivity(intent);
该方法有一个弊端,com.android.camera.CropImage是一个可选Action,而非标准Action,因此并分所有Android设备都支持该API,许多设备会出现ActivityNotFoundException.


2.调用系统的Intent.ACTION_ATTACH_DATA,该Intent会唤起所有的设置壁纸程序以及设置联系人头像程序,用户可以通过ChooseActivity进行选择:

该Intent是一个标准Intent,因此所有设置都会支持。

                Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);                intent.putExtra("mimeType", "image/*");                Uri uri = Uri.parse(MediaStore.Images.Media                        .insertImage(getActivity().getContentResolver(),                                ((BitmapDrawable) wallpaper).getBitmap(), null, null));                intent.setData(uri);                startActivityForResult(intent, SET_WALLPAPER);


以上这些方法推荐只用最后一种,原因很简单:体验好,适配成本低。


作者:xzy2046,转载需注明。博客主页:http://blog.csdn.net/xzy2046



2 0