我制作了移动壁纸的代码,但是按下按钮时,壁纸会添加到手机壁纸中,但它不会作为活动壁纸应用,我必须手动添加它 我的服务代码是
public class LiveWallpaperService extends WallpaperService {
int x, y;
public void onCreate() {
super.onCreate();
}
public void onDestroy() {
super.onDestroy();
}
public Engine onCreateEngine() {
return new MyWallpaperEngine();
}
class MyWallpaperEngine extends Engine {
private final Handler handler = new Handler();
private final Runnable drawRunner = new Runnable() {
@Override
public void run() {
draw();
}
};
private boolean visible = true;
public Bitmap image1, backgroundImage;
MyWallpaperEngine() {
// get the fish and background image references
image1 = BitmapFactory.decodeResource(getResources(), R.drawable.fish);
backgroundImage = BitmapFactory.decodeResource(getResources(), R.drawable.background);
x = 200; // initialize x position
y = -200; // initialize y position
}
public void onCreate(SurfaceHolder surfaceHolder) {
super.onCreate(surfaceHolder);
}
@Override
public void onVisibilityChanged(boolean visible) {
this.visible = visible;
// if screen wallpaper is visible then draw the image otherwise do not draw
if (visible) {
handler.post(drawRunner);
} else {
handler.removeCallbacks(drawRunner);
}
}
@Override
public void onSurfaceDestroyed(SurfaceHolder holder) {
super.onSurfaceDestroyed(holder);
this.visible = false;
handler.removeCallbacks(drawRunner);
}
public void onOffsetsChanged(float xOffset, float yOffset, float xStep, float yStep, int xPixels, int yPixels) {
draw();
}
void draw() {
final SurfaceHolder holder = getSurfaceHolder();
Canvas c = null;
try {
c = holder.lockCanvas();
// clear the canvas
c.drawColor(Color.BLACK);
if (c != null) {
// draw the background image
c.drawBitmap(backgroundImage, 0, 0, null);
// draw the fish
c.drawBitmap(image1, x, y, null);
// get the width of canvas
int height = c.getHeight();
int width = c.getWidth();
// if x crosses the width means x has reached to right edge
if (y > height + 100) {
// assign initial value to start with
y = 200;
}
// change the x position/value by 1 pixel
y = y + 1;
if (x > width + 100) {
x = -50;
x = x + 3;
}
}
} finally {
if (c != null)
holder.unlockCanvasAndPost(c);
}
handler.removeCallbacks(drawRunner);
if (visible) {
handler.postDelayed(drawRunner, 10); // delay 10 mileseconds
}
}
}
}
以及启动该服务的主要活动代码是
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startClicked(View view) {
Intent intent = new Intent(this, LiveWallpaperService.class);
startService(intent);
}