Android - 如何设置壁纸图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1964193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:57:08  来源:igfitidea点击:

Android - how to set the wallpaper image

androidimagewallpaper

提问by James Cadd

Is it possible to set the android wallpaper image programatically? I'd like to create a service that downloads an image from the web and updates the home screen wallpaper periodically.

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

采纳答案by ChrisF

From this pageon the developer site:

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

public void setStream (InputStream data)

Change the current system wallpaper to a specific byte stream. The give InputStream is copied into persistent storage and will now be used as the wallpaper. Currently it must be either a JPEG or PNG image.

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

回答by Kishore

If you have image URL then use

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

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

If you have image URI then use

如果您有图像 URI,则使用

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

In your manifest file:

在您的清单文件中:

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

回答by djk

If you have bitmap of image than you will add this function to set as wallpaper:

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

  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();
    }         
}

you should add permission for this

你应该为此添加权限

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

hope it will work

希望它会起作用

回答by Jonah

OK Here's how to do it before api 2.0:

OK 下面是 api 2.0 之前的做法:

You need to call getApplicationContext.setWallpaper() and pass it the bitmap.

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

This method is now deprecated. See ChrisF's answer for details on the new method.

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