如何设置图片作为墙纸编程? [英] How to set image as wallpaper programmatically?

查看:113
本文介绍了如何设置图片作为墙纸编程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在开发这就需要将图像设置为墙纸应用程序。

I have been developing the application which need to set an image as wallpaper.

code:

WallpaperManager m=WallpaperManager.getInstance(this);

String s=Environment.getExternalStorageDirectory().getAbsolutePath()+"/1.jpg";
File f=new File(s);
Log.e("exist", String.valueOf(f.exists()));
try {
        InputStream is=new BufferedInputStream(new FileInputStream(s));
        m.setBitmap(BitmapFactory.decodeFile(s));

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.e("File", e.getMessage());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.e("IO", e.getMessage());
    }

此外,我已经添加了以下权限:

Also I have added the following permission:

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

但它不工作;该文件存在于SD卡。我在哪里犯了一个错误?

But it doesn't works; the file exists on sdcard. Where have I made a mistake?

推荐答案

也许,你耗尽内存,如果你的形象是很大的。您可以确保它通过阅读logcat的日志。如果是这种情况,尝试通过调整图片大小的设备有点像这样的:

Possibly, you run out of memory if your image is big. You can make sure of it by reading Logcat logs. If this is the case, try to adjust your picture to device size by somewhat like this:

    DisplayMetrics displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    int height = displayMetrics.heightPixels;
    int width = displayMetrics.widthPixels << 1; // best wallpaper width is twice screen width

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, width, height);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    Bitmap decodedSampleBitmap = BitmapFactory.decodeFile(path, options);

    WallpaperManager wm = WallpaperManager.getInstance(this);
    try {
        wm.setBitmap(decodedSampleBitmap);
    } catch (IOException e) {
        Log.e(TAG, "Cannot set image as wallpaper", e);
    }

这篇关于如何设置图片作为墙纸编程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆