一.什么是动态壁纸
动态壁纸是通过自定义Service继承WallpaperService,实现onCreateEngine方法,在该方法中返回Engine,该Engine中可以绘制图像,视频,Gif动画等来呈现壁纸
二.自定义Service
1.自定义Service继承WallpaperService
public class LiveWallpaperService extends WallpaperService {
private MediaPlayer mediaPlayer;
@Override
public Engine onCreateEngine() {
return new LiveWallpaperEngine();
}
class LiveWallpaperEngine extends Engine{
@Override
public SurfaceHolder getSurfaceHolder() {
return super.getSurfaceHolder();
}
@Override
public void onSurfaceCreated(SurfaceHolder holder) {
super.onSurfaceCreated(holder);
initMediaPlayer(holder);
}
private void initMediaPlayer(SurfaceHolder holder) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
try {
mediaPlayer.setSurface( holder.getSurface());
Uri mUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.splash_screen);
mediaPlayer.setDataSource(LiveWallpaperService.this, mUri);
mediaPlayer.setLooping(true);
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onSurfaceDestroyed(SurfaceHolder holder) {
super.onSurfaceDestroyed(holder);
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
}
}
2.在AndroidManifest文件中注册Service
<service
android:name=".wallpaperservice.LiveWallpaperService"
android:enabled="true"
android:permission="android.permission.BIND_WALLPAPER">
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService" />
</intent-filter>
<meta-data
android:name="android.service.wallpaper"
android:resource="@xml/livewallpaper" />
尤其注意要增加android:permission="android.permission.BIND_WALLPAPER"权限
resource是定义动态壁纸的属性,比如缩略图等,是一个纯xml文件
<?xml version="1.0" encoding="utf-8"?>
<wallpaper xmlns:android="http://schemas.android.com/apk/res/android"
android:settingsActivity="ui.activity.LiveWallPreference"
android:thumbnail="@drawable/ic_send"
android:description="@string/abandoned_clean_this"
/>
3.启动该Service
Intent intent = new Intent(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER);
intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, new ComponentName(this, LiveWallpaperService.class));
startActivity(intent);
这样就实现了定制动态壁纸