/** * 设置壁纸 * * @param context context * @param resources 如果是主题包,必须用主题包的resource * @param resId 图片资源id */ private void setWallpaper(Context context, Resources resources, int resId) { OutOfMemoryHandler.handle(); if (context == null || resources == null || resId < 0) { return; } boolean bSetOk = false; WallpaperManager wpm = null; Drawable drb = null; BitmapDrawable bdrb = null; // InputStream in = null; ByteArrayOutputStream out = null; try { // 获取宽高 // 竖屏状态 int screenW = 0; int screenH = 0; if (resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { screenW = resources.getDisplayMetrics().widthPixels; screenH = resources.getDisplayMetrics().heightPixels; } else { screenW = resources.getDisplayMetrics().heightPixels; screenH = resources.getDisplayMetrics().widthPixels; } wpm = (WallpaperManager) context.getSystemService(Context.WALLPAPER_SERVICE); drb = resources.getDrawable(resId); { // 图片处理 // 对Lephone的特殊处理 if (Machine.isLephone()) { bdrb = WindowControl.prepareWallpaper((BitmapDrawable) drb, screenH, screenH, resources); } else { bdrb = WindowControl.prepareWallpaper( (BitmapDrawable) drb, screenW * WindowControl.WALLPAPER_SCREENS_SPAN, screenH, resources); } out = new ByteArrayOutputStream(); boolean b = bdrb.getBitmap().compress(CompressFormat.JPEG, 100, out); if (b) { mInputStream = new BufferedInputStream(new ByteArrayInputStream(out.toByteArray())); out.close(); out = null; } else { mInputStream = resources.openRawResource(resId); } bSetOk = true; mHandler.sendEmptyMessage(MSG_SET_WALLPAPER_INPUTSTREAM); } } catch (OutOfMemoryError e) { // 内存爆掉,不进行图片处理 OutOfMemoryHandler.handle(); try { if (wpm != null) { mInputStream = resources.openRawResource(resId); mHandler.sendEmptyMessage(MSG_SET_WALLPAPER_INPUTSTREAM); } bSetOk = true; } catch (Throwable e2) { Log.i(LogConstants.HEART_TAG, "fail to re-change wallpaper " + e2); } } catch (IOException e) { Log.i(LogConstants.HEART_TAG, "fail to change wallpaper " + e); } catch (Exception e) { Log.i(LogConstants.HEART_TAG, "fail to change wallpaper " + e); } finally { if (null != out) { try { out.close(); } catch (Exception e2) { e2.printStackTrace(); } } } }