我正在创建动态壁纸,并以本教程为起点:
我正在尝试添加一个设置菜单,让用户选择四种背景之一。我使用SharedPreferences
. 唯一的问题是在设置菜单中更改设置后壁纸不会更新。如果您重新启动应用程序,背景将更新为上次选择的背景,但它仅在壁纸重新启动后才有效(即选择不同的壁纸,然后重新选择此壁纸)。
我已将问题缩小到SharedPreference
仅在onCreateEngine()
方法中更新的值。壁纸服务运行后,该onCreateEngine()
方法不会被调用,因此即使 的值SharedPreference
已更改,它也不会在壁纸服务中更新。
我的问题是如何重新启动墙纸,以便onCreateEngine()
在更改设置后调用该方法?同样,它们SharedPreferences
正在工作,因为重启后一切正常。我知道我需要使用该onsharedPreferenceChanged
方法,但我不确定应该在哪里发生,或者该方法中应该包含哪些代码来重新启动墙纸引擎。
这是示例代码。我的情况是一样的,除非评论指出:
import android.graphics.Canvas;
import android.graphics.Movie;
import android.os.Handler;
import android.service.wallpaper.WallpaperService;
import android.util.Log;
import android.view.SurfaceHolder;
import java.io.IOException;
public class GIFWallpaperService extends WallpaperService implements onsharedpreferencechangelistener {
// Variable I added to change background
String mBackgroundImage = null;
// Method I added to update background image
public void updatedBackgroundImage(){
// code that sets mBackgroundImage based upon value of shared preference file.
}
@Override
public WallpaperService.Engine onCreateEngine() {
// I call this method to change the value of mBackgroundImage
updateBackgroundImage();
try {
Movie movie = Movie.decodeStream(
getResources().getAssets().open("mBackgroundImage"));
return new GIFWallpaperEngine(movie);
}catch(IOException e){
Log.d("GIF", "Could not load asset");
return null;
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
// What do I do? How do I make the wallpaper engine restart when settings are changed?
}
private class GIFWallpaperEngine extends WallpaperService.Engine {
private final int frameDuration = 20;
private SurfaceHolder holder;
private Movie movie;
private boolean visible;
private Handler handler;
public GIFWallpaperEngine(Movie movie) {
this.movie = movie;
handler = new Handler();
}
@Override
public void onCreate(SurfaceHolder surfaceHolder) {
super.onCreate(surfaceHolder);
this.holder = surfaceHolder;
}
private Runnable drawGIF = new Runnable() {
public void run() {
draw();
}
};
private void draw() {
if (visible) {
Canvas canvas = holder.lockCanvas();
canvas.save();
// Adjust size and position so that
// the image looks good on your screen
canvas.scale(3f, 3f);
movie.draw(canvas, -100, 0);
canvas.restore();
holder.unlockCanvasAndPost(canvas);
movie.setTime((int) (System.currentTimeMillis() % movie.duration()));
handler.removeCallbacks(drawGIF);
handler.postDelayed(drawGIF, frameDuration);
}
}
@Override
public void onVisibilityChanged(boolean visible) {
this.visible = visible;
if (visible) {
handler.post(drawGIF);
} else {
handler.removeCallbacks(drawGIF);
}
}
@Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(drawGIF);
}
}
}