0

我正在尝试从文件路径设置壁纸。然而,这需要超过 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中所建议,但无法加载壁纸。

谁能指导我?

谢谢

4

1 回答 1

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;
} 
于 2016-05-30T07:58:58.627 回答