1.需求
Three entrance for this feature. one is in Home screen, the second is in Settings>Display screen, the third one is in Gallery>single view a picture>Set picture as>Wallaper screen.
2.方案
思路:
通过对WallpaperManager和SystemUI中添加对应的方法,来实现对外提供设置锁屏壁纸的接口。
步骤:
1.设置锁屏壁纸,将选好的壁纸存入SystemUI对应目录下;
2.读取锁屏壁纸,当屏幕点亮后从SystemUI对应目录下读取图片对当前锁屏界面进行背景的设置,达到效果。
代码路径:
frameworks/base/core/java/android/app/WallpaperManager.java
frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
具体实现代码:
/**
* Provides access to the system wallpaper. With WallpaperManager, you can
* get the current wallpaper, get the desired dimensions for the wallpaper, set
* the wallpaper, and more. Get an instance of WallpaperManager with
* {@link #getInstance(android.content.Context) getInstance()}.
*
* <p> An app can check whether wallpapers are supported for the current user, by calling
* {@link #isWallpaperSupported()}.
*/
public class WallpaperManager {
private static String TAG = "WallpaperManager";
private static boolean DEBUG = true;
private static final String WALLPAPERDIR = "/data/data/com.android.systemui/";
static final String MENUWALLPAPERNAME = "menuwallpaper.png";
static final String LOCKWALLPAPERNAME = "lockwallpaper.png";
/** {@hide} */
public static final int SCREEN_WP_MODE = 0;
/** {@hide} */
public static final int LOCK_WP_MODE = 1;
/** {@hide} */
public static final int ALL_WP_MODE = 2;
private final Context mContext;
<中间部分省略>...
//默认设置壁纸的方法
public void setStream(InputStream data) throws IOException {
if (sGlobals.mService == null) {
Log.w(TAG, "WallpaperService not running");
return;
}
try {
ParcelFileDescriptor fd = sGlobals.mService.setWallpaper(null,
mContext.getOpPackageName());
if (fd == null) {
return;
}
FileOutputStream fos = null;
try {
fos = new ParcelFileDescriptor.AutoCloseOutputStream(fd);
setWallpaper(data, fos);
} finally {
if (fos != null) {
fos.close();
}
}
} catch (RemoteException e) {
// Ignore
}
}
//将选好的图片流写到指定路径
private void setWallpaper(InputStream data, FileOutputStream fos)
throws IOException {
byte[] buffer = new byte[32768];
int amt;
while ((amt=data.read(buffer)) > 0) {
fos.write(buffer, 0, amt);
}
}
//通过指定图片文件路径,得到一个文件描述符对象
private ParcelFileDescriptor getLockWallpaperPath() {
File dir = new File(WALLPAPERDIR);
if(!dir.exists()){
dir.mkdirs();
}
FileUtils.setPermissions(WALLPAPERDIR,0777,-1,-1);
File file = null;
file = new File(dir, LOCKWALLPAPERNAME);
try {
file.createNewFile();
} catch (IOException io) {
io.printStackTrace();
}
ParcelFileDescriptor fd=null;
try{
fd = ParcelFileDescriptor.open(file,ParcelFileDescriptor.MODE_CREATE|ParcelFileDescriptor.MODE_READ_WRITE);
}catch(Exception e) {
e.printStackTrace();
}
return fd;
}
//设置锁屏壁纸,将图片存入到指定路径下
public void setLockStream(InputStream data) throws IOException {
Log.w(TAG, "setLockStream...");
if (sGlobals.mService == null) {
return;
}
if(data==null)
{
//如果图片不存在,就以默认壁纸作为锁屏壁纸来设置