java - 如何以编程方式将图像设置为墙纸?

标签 java android wallpaper

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

代码:

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

我还添加了以下权限:

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

但它不起作用;该文件存在于 SD 卡上。我哪里做错了?

最佳答案

如果您的图像很大,可能会耗尽内存。您可以通过阅读 Logcat 日志来确定它。如果是这种情况,请尝试通过如下方式将图片调整为适合设备大小:

    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);
    }

关于java - 如何以编程方式将图像设置为墙纸?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10160267/

相关文章:

java - 同步您正在修改的静态字段是否会使您的代码线程安全?

java - 顺序运行 Java 线程

java - 如何在 Canvas 上以原始方式绘制更多矩形?

android - 为什么在新版本的build.gradle 3中,apk的大小增加了2倍。

使用 Wallpaper Manager 的 Android AsyncTask

Java-Reflection-Spring如何识别参数是用户定义对象还是Primitive Type

java - eclipse E4 : how to access the MApplication instance (at start)

Android - 如何监听蓝牙暂停/播放

windows-phone-7 - WP7 - 以编程方式更改主屏幕背景

android - Android动态壁纸的最简单示例