Android - 从文件路径设置壁纸需要比预期更长的时间

时间:2016-05-30 07:43:23

标签: android android-wallpaper

我正在尝试从文件路径设置壁纸。然而,它需要超过10秒,并导致我的应用程序冻结。

这是我正在使用的代码:

public void SET_WALLPAPER_FROM_FILE_PATH (String file_path)
{
    Bitmap image_bitmap;
    File   image_file;
    FileInputStream fis;

    try {
        WallpaperManager wallpaper_manager = WallpaperManager.getInstance(m_context);
        image_file                         = new File(file_path);
        fis                                = new FileInputStream(image_file);
        image_bitmap                       = BitmapFactory.decodeStream(fis);

        wallpaper_manager.setBitmap(image_bitmap);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

我试过用:

wallpaper_manager.setStream(fis)

而不是:

wallpaper_manager.setBitmap(image_bitmap);

this answer中所述,但无法加载壁纸。

任何人都可以指导我吗?

由于

1 个答案:

答案 0 :(得分:1)

尝试使用AsyncTask, 在doInBackground方法中写这样的东西

public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
    try {
        //Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(f),null,o);

        //The new size we want to scale to
        final int REQUIRED_WIDTH=WIDTH;
        final int REQUIRED_HIGHT=HIGHT;
        //Find the correct scale value. It should be the power of 2.
        int scale=1;
        while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
            scale*=2;

        //Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize=scale;
        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    }
        catch (FileNotFoundException e) {}
    return null;
}