效果图,图中桌面背景为一段视频
对动态壁纸进行一些设置
在res下创建一个xml文件夹,在创建一个wallpager标签文件
<?xml version="1.0" encoding="utf-8"?>
<wallpaper xmlns:android="http://schemas.android.com/apk/res/android"
android:thumbnail="@mipmap/ic_launcher"
android:description="@string/wallpager"
>
</wallpaper>
两个属性分别对应动态壁纸列表的显示
播放视频的话需要一个Service,这里的用到一个WallpaperService,需要我们去继承。
public class VideoLiveWallpaper extends WallpaperService {
@Override
public Engine onCreateEngine() {
return new VideoEngine();
}
}
VideoEngine类为内部类,继承自Engine类。在Engine类中,有各种SurfaceView的监听方法,接下来就是正常的视频播放过程了
class VideoEngine extends Engine {
private MediaPlayer mMediaPlayer;
@Override
public void onSurfaceCreated(SurfaceHolder holder) {
Log.d("VideoEngine", "onSurfaceCreated ");
super.onSurfaceCreated(holder);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setSurface(holder.getSurface());
try {
AssetManager assetMg = getApplicationContext().getAssets();
AssetFileDescriptor fileDescriptor = assetMg.openFd("welcome.mp4");
mMediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),
fileDescriptor.getStartOffset(), fileDescriptor.getLength());
mMediaPlayer.setLooping(true);
mMediaPlayer.setVolume(0, 0);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onVisibilityChanged(boolean visible) {
Log.d("VideoEngine", "onVisibilityChanged visible = " + visible);
if (visible) {
mMediaPlayer.start();
} else {
mMediaPlayer.pause();
}
}
@Override
public void onSurfaceDestroyed(SurfaceHolder holder) {
Log.d("VideoEngine", "onSurfaceDestroyed ");
super.onSurfaceDestroyed(holder);
mMediaPlayer.release();
mMediaPlayer = null;
}
}
这样视频播放的壁纸service就编写还代码了,接下来需要进行清单文件注册
<service
android:name=".VideoLiveWallpaper"
android:permission="android.permission.BIND_WALLPAPER"
android:process=":wallpaper">
<!-- 配置intent-filter -->
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService" />
</intent-filter>
<!-- 配置meta-data -->
<meta-data
android:name="android.service.wallpaper"
android:resource="@xml/wallpaper" />
</service>
我们需要添加android.permission.BIND_WALLPAPER权限,添加一个作为壁纸的action,添加配置文件
然后就是去启动
public static void setToWallPaper(Context context) {
//唤醒设置壁纸的界面
final Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
//设置动态壁纸服务的信息
//上下文和服务类
intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT,
new ComponentName(context, VideoLiveWallpaper.class));
//启动
context.startActivity(intent);
}
然后在主界面中去调用这个点击事件方法就好了