如何以编程方式将图像设置为壁纸?
问题描述:
我一直在开发需要设置图像作为壁纸的应用程序。如何以编程方式将图像设置为壁纸?
代码:
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卡上。我在哪里犯了一个错误?
答
File f = new File(Environment.getExternalStorageDirectory(), "1.jpg");
String path = f.getAbsolutePath();
File f1 = new File(path);
if(f1.exists()) {
Bitmap bmp = BitmapFactory.decodeFile(path);
BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp);
WallpaperManager m=WallpaperManager.getInstance(this);
try {
m.setBitmap(bmp);
} catch (IOException e) {
e.printStackTrace();
}
}
打开AndroidManifest.xml文件,并添加权限如..
<uses-permission android:name="android.permission.SET_WALLPAPER" />
试试这个,让我知道发生什么事..
答
可能的话,你耗尽内存,如果你的形象大。你可以通过阅读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);
}
是否有抛出异常? – 2012-04-15 07:24:34