27

是否可以以编程方式设置 android 壁纸图像?我想创建一个从网络下载图像并定期更新主屏幕壁纸的服务。

4

4 回答 4

32

如果您有图片网址,请使用

WallpaperManager wpm = WallpaperManager.getInstance(context);
InputStream ins = new URL("absolute/path/of/image").openStream();
wpm.setStream(ins);

如果您有图像 URI,则使用

WallpaperManager wpm = WallpaperManager.getInstance(context);
wpm.setResource(Uri.of.image);

在您的清单文件中:

<uses-permission android:name="android.permission.SET_WALLPAPER"></uses-permission>
于 2012-10-18T10:06:55.843 回答
22

从开发者网站上的这个页面

public void setStream (InputStream data)

将当前系统壁纸更改为特定字节流。给出的 InputStream 被复制到持久存储中,现在将用作墙纸。目前它必须是 JPEG 或 PNG 图像。

于 2009-12-26T19:54:39.377 回答
5

如果您有图像位图,则将添加此功能以设置为墙纸:

  public void SetBackground(int Url) {

    try {
        File file = new File("/sdcard/sampleimage");
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), Url);
        bitmap.compress(CompressFormat.JPEG, 80, new FileOutputStream(file));
        Context context = this.getBaseContext();
        context.setWallpaper(bitmap);            
        Toast.makeText(getApplicationContext(), "Wallpaper has been set",             Toast.LENGTH_SHORT).show();            
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }         
}

您应该为此添加权限

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

希望它会工作

于 2012-04-17T05:41:37.097 回答
4

好的,这是在 api 2.0 之前的操作方法:

您需要调用 getApplicationContext.setWallpaper() 并将位图传递给它。

此方法现已弃用。有关新方法的详细信息,请参阅 ChrisF 的回答。

于 2010-04-20T00:12:51.413 回答