There are multiple ways to achieve the goal of displaying the current system wallpaper as the application background. All are mentioned below :
1. By Using Windowmanager class
It is the easiest way to use system wallpaper in which we can get a drawable object of system wallpaper image using WindowManager class of Android and set it as the activity’s main view background.
WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
Drawable wallpaperDrawable = wallpaperManager.getDrawable();
LinearLayout linearMain = findViewById(R.id.linearMain);
linearMain.setBackground(wallpaperDrawable);
2. By Setting Activity theme
Another method is to set Activity’s theme as system wallpaper. To do that, we need to style the theme in the styles.xml file and use it in overriding the getTheme() method of the Activity.
<style name="Theme_Wallpaper">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowShowWallpaper">true</item>
</style>
@Override
public Resources.Theme getTheme() {
Resources.Theme theme = super.getTheme();
theme.applyStyle(R.style.Theme_Wallpaper, true);
return theme;
}
3. When working with WebView
For WebView, we need to use WallpaperManager as used in solution 1 but need to store that image in device storage or asset folder of the app and use that image file as a background in the HTML code. Also, we need to get storage permission to save image. In the below example, we are storing it in the asset folder :
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getBaseContext());
Drawable wallpaperDrawable = wallpaperManager.getDrawable();
Bitmap img = ((BitmapDrawable)wallpaperDrawable).getBitmap();
//store bitmap in the asset folder
ContextWrapper cw = new ContextWrapper(getBaseContext());
File directory = cw.getDir("assets", Context.MODE_PRIVATE);
File mypath = new File(directory, "system_wallpaper.jpeg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
img.compress(Bitmap.CompressFormat.PNG, 0, fos);
fos.close();
} catch (Exception e) {
Logger.logError(e);
}