WallpaperService.java revision 3b723ace405305e61ab25f96cb8ee1a321edcf9b
1/* 2 * Copyright (C) 2009 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.service.wallpaper; 18 19import com.android.internal.os.HandlerCaller; 20import com.android.internal.view.BaseIWindow; 21import com.android.internal.view.BaseInputHandler; 22import com.android.internal.view.BaseSurfaceHolder; 23 24import android.annotation.SdkConstant; 25import android.annotation.SdkConstant.SdkConstantType; 26import android.app.Service; 27import android.app.WallpaperManager; 28import android.content.BroadcastReceiver; 29import android.content.Context; 30import android.content.Intent; 31import android.content.IntentFilter; 32import android.content.res.Configuration; 33import android.graphics.PixelFormat; 34import android.graphics.Rect; 35import android.os.Bundle; 36import android.os.IBinder; 37import android.os.Looper; 38import android.os.Message; 39import android.os.Process; 40import android.os.RemoteException; 41import android.util.Log; 42import android.util.LogPrinter; 43import android.view.Gravity; 44import android.view.IWindowSession; 45import android.view.InputChannel; 46import android.view.InputDevice; 47import android.view.InputHandler; 48import android.view.InputQueue; 49import android.view.KeyEvent; 50import android.view.MotionEvent; 51import android.view.SurfaceHolder; 52import android.view.View; 53import android.view.ViewGroup; 54import android.view.ViewRoot; 55import android.view.WindowManager; 56import android.view.WindowManagerImpl; 57import android.view.WindowManagerPolicy; 58 59import java.util.ArrayList; 60 61/** 62 * A wallpaper service is responsible for showing a live wallpaper behind 63 * applications that would like to sit on top of it. This service object 64 * itself does very little -- its only purpose is to generate instances of 65 * {@link Engine} as needed. Implementing a wallpaper thus 66 * involves subclassing from this, subclassing an Engine implementation, 67 * and implementing {@link #onCreateEngine()} to return a new instance of 68 * your engine. 69 */ 70public abstract class WallpaperService extends Service { 71 /** 72 * The {@link Intent} that must be declared as handled by the service. 73 * To be supported, the service must also require the 74 * {@link android.Manifest.permission#BIND_WALLPAPER} permission so 75 * that other applications can not abuse it. 76 */ 77 @SdkConstant(SdkConstantType.SERVICE_ACTION) 78 public static final String SERVICE_INTERFACE = 79 "android.service.wallpaper.WallpaperService"; 80 81 /** 82 * Name under which a WallpaperService component publishes information 83 * about itself. This meta-data must reference an XML resource containing 84 * a <code><{@link android.R.styleable#Wallpaper wallpaper}></code> 85 * tag. 86 */ 87 public static final String SERVICE_META_DATA = "android.service.wallpaper"; 88 89 static final String TAG = "WallpaperService"; 90 static final boolean DEBUG = false; 91 92 private static final int DO_ATTACH = 10; 93 private static final int DO_DETACH = 20; 94 private static final int DO_SET_DESIRED_SIZE = 30; 95 96 private static final int MSG_UPDATE_SURFACE = 10000; 97 private static final int MSG_VISIBILITY_CHANGED = 10010; 98 private static final int MSG_WALLPAPER_OFFSETS = 10020; 99 private static final int MSG_WALLPAPER_COMMAND = 10025; 100 private static final int MSG_WINDOW_RESIZED = 10030; 101 private static final int MSG_TOUCH_EVENT = 10040; 102 103 private Looper mCallbackLooper; 104 private final ArrayList<Engine> mActiveEngines 105 = new ArrayList<Engine>(); 106 107 static final class WallpaperCommand { 108 String action; 109 int x; 110 int y; 111 int z; 112 Bundle extras; 113 boolean sync; 114 } 115 116 /** 117 * The actual implementation of a wallpaper. A wallpaper service may 118 * have multiple instances running (for example as a real wallpaper 119 * and as a preview), each of which is represented by its own Engine 120 * instance. You must implement {@link WallpaperService#onCreateEngine()} 121 * to return your concrete Engine implementation. 122 */ 123 public class Engine { 124 IWallpaperEngineWrapper mIWallpaperEngine; 125 126 // Copies from mIWallpaperEngine. 127 HandlerCaller mCaller; 128 IWallpaperConnection mConnection; 129 IBinder mWindowToken; 130 131 boolean mInitializing = true; 132 boolean mVisible; 133 boolean mScreenOn = true; 134 boolean mReportedVisible; 135 boolean mDestroyed; 136 137 // Current window state. 138 boolean mCreated; 139 boolean mSurfaceCreated; 140 boolean mIsCreating; 141 boolean mDrawingAllowed; 142 int mWidth; 143 int mHeight; 144 int mFormat; 145 int mType; 146 int mCurWidth; 147 int mCurHeight; 148 int mWindowFlags = WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; 149 int mCurWindowFlags = mWindowFlags; 150 final Rect mVisibleInsets = new Rect(); 151 final Rect mWinFrame = new Rect(); 152 final Rect mContentInsets = new Rect(); 153 final Configuration mConfiguration = new Configuration(); 154 155 final WindowManager.LayoutParams mLayout 156 = new WindowManager.LayoutParams(); 157 IWindowSession mSession; 158 InputChannel mInputChannel; 159 160 final Object mLock = new Object(); 161 boolean mOffsetMessageEnqueued; 162 float mPendingXOffset; 163 float mPendingYOffset; 164 float mPendingXOffsetStep; 165 float mPendingYOffsetStep; 166 boolean mPendingSync; 167 MotionEvent mPendingMove; 168 169 final BroadcastReceiver mReceiver = new BroadcastReceiver() { 170 @Override 171 public void onReceive(Context context, Intent intent) { 172 if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) { 173 mScreenOn = true; 174 reportVisibility(); 175 } else if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) { 176 mScreenOn = false; 177 reportVisibility(); 178 } 179 } 180 }; 181 182 final BaseSurfaceHolder mSurfaceHolder = new BaseSurfaceHolder() { 183 { 184 mRequestedFormat = PixelFormat.RGB_565; 185 } 186 187 @Override 188 public boolean onAllowLockCanvas() { 189 return mDrawingAllowed; 190 } 191 192 @Override 193 public void onRelayoutContainer() { 194 Message msg = mCaller.obtainMessage(MSG_UPDATE_SURFACE); 195 mCaller.sendMessage(msg); 196 } 197 198 @Override 199 public void onUpdateSurface() { 200 Message msg = mCaller.obtainMessage(MSG_UPDATE_SURFACE); 201 mCaller.sendMessage(msg); 202 } 203 204 public boolean isCreating() { 205 return mIsCreating; 206 } 207 208 @Override 209 public void setFixedSize(int width, int height) { 210 if (Process.myUid() != Process.SYSTEM_UID) { 211 // Regular apps can't do this. It can only work for 212 // certain designs of window animations, so you can't 213 // rely on it. 214 throw new UnsupportedOperationException( 215 "Wallpapers currently only support sizing from layout"); 216 } 217 super.setFixedSize(width, height); 218 } 219 220 public void setKeepScreenOn(boolean screenOn) { 221 throw new UnsupportedOperationException( 222 "Wallpapers do not support keep screen on"); 223 } 224 225 }; 226 227 final InputHandler mInputHandler = new BaseInputHandler() { 228 @Override 229 public void handleMotion(MotionEvent event, 230 InputQueue.FinishedCallback finishedCallback) { 231 boolean handled = false; 232 try { 233 int source = event.getSource(); 234 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 235 dispatchPointer(event); 236 handled = true; 237 } 238 } finally { 239 finishedCallback.finished(handled); 240 } 241 } 242 }; 243 244 final BaseIWindow mWindow = new BaseIWindow() { 245 @Override 246 public void resized(int w, int h, Rect coveredInsets, 247 Rect visibleInsets, boolean reportDraw, Configuration newConfig) { 248 Message msg = mCaller.obtainMessageI(MSG_WINDOW_RESIZED, 249 reportDraw ? 1 : 0); 250 mCaller.sendMessage(msg); 251 } 252 253 @Override 254 public void dispatchAppVisibility(boolean visible) { 255 // We don't do this in preview mode; we'll let the preview 256 // activity tell us when to run. 257 if (!mIWallpaperEngine.mIsPreview) { 258 Message msg = mCaller.obtainMessageI(MSG_VISIBILITY_CHANGED, 259 visible ? 1 : 0); 260 mCaller.sendMessage(msg); 261 } 262 } 263 264 @Override 265 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep, 266 boolean sync) { 267 synchronized (mLock) { 268 if (DEBUG) Log.v(TAG, "Dispatch wallpaper offsets: " + x + ", " + y); 269 mPendingXOffset = x; 270 mPendingYOffset = y; 271 mPendingXOffsetStep = xStep; 272 mPendingYOffsetStep = yStep; 273 if (sync) { 274 mPendingSync = true; 275 } 276 if (!mOffsetMessageEnqueued) { 277 mOffsetMessageEnqueued = true; 278 Message msg = mCaller.obtainMessage(MSG_WALLPAPER_OFFSETS); 279 mCaller.sendMessage(msg); 280 } 281 } 282 } 283 284 public void dispatchWallpaperCommand(String action, int x, int y, 285 int z, Bundle extras, boolean sync) { 286 synchronized (mLock) { 287 if (DEBUG) Log.v(TAG, "Dispatch wallpaper command: " + x + ", " + y); 288 WallpaperCommand cmd = new WallpaperCommand(); 289 cmd.action = action; 290 cmd.x = x; 291 cmd.y = y; 292 cmd.z = z; 293 cmd.extras = extras; 294 cmd.sync = sync; 295 Message msg = mCaller.obtainMessage(MSG_WALLPAPER_COMMAND); 296 msg.obj = cmd; 297 mCaller.sendMessage(msg); 298 } 299 } 300 }; 301 302 /** 303 * Provides access to the surface in which this wallpaper is drawn. 304 */ 305 public SurfaceHolder getSurfaceHolder() { 306 return mSurfaceHolder; 307 } 308 309 /** 310 * Convenience for {@link WallpaperManager#getDesiredMinimumWidth() 311 * WallpaperManager.getDesiredMinimumWidth()}, returning the width 312 * that the system would like this wallpaper to run in. 313 */ 314 public int getDesiredMinimumWidth() { 315 return mIWallpaperEngine.mReqWidth; 316 } 317 318 /** 319 * Convenience for {@link WallpaperManager#getDesiredMinimumHeight() 320 * WallpaperManager.getDesiredMinimumHeight()}, returning the height 321 * that the system would like this wallpaper to run in. 322 */ 323 public int getDesiredMinimumHeight() { 324 return mIWallpaperEngine.mReqHeight; 325 } 326 327 /** 328 * Return whether the wallpaper is currently visible to the user, 329 * this is the last value supplied to 330 * {@link #onVisibilityChanged(boolean)}. 331 */ 332 public boolean isVisible() { 333 return mReportedVisible; 334 } 335 336 /** 337 * Returns true if this engine is running in preview mode -- that is, 338 * it is being shown to the user before they select it as the actual 339 * wallpaper. 340 */ 341 public boolean isPreview() { 342 return mIWallpaperEngine.mIsPreview; 343 } 344 345 /** 346 * Control whether this wallpaper will receive raw touch events 347 * from the window manager as the user interacts with the window 348 * that is currently displaying the wallpaper. By default they 349 * are turned off. If enabled, the events will be received in 350 * {@link #onTouchEvent(MotionEvent)}. 351 */ 352 public void setTouchEventsEnabled(boolean enabled) { 353 mWindowFlags = enabled 354 ? (mWindowFlags&~WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE) 355 : (mWindowFlags|WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE); 356 if (mCreated) { 357 updateSurface(false, false, false); 358 } 359 } 360 361 /** 362 * Called once to initialize the engine. After returning, the 363 * engine's surface will be created by the framework. 364 */ 365 public void onCreate(SurfaceHolder surfaceHolder) { 366 } 367 368 /** 369 * Called right before the engine is going away. After this the 370 * surface will be destroyed and this Engine object is no longer 371 * valid. 372 */ 373 public void onDestroy() { 374 } 375 376 /** 377 * Called to inform you of the wallpaper becoming visible or 378 * hidden. <em>It is very important that a wallpaper only use 379 * CPU while it is visible.</em>. 380 */ 381 public void onVisibilityChanged(boolean visible) { 382 } 383 384 /** 385 * Called as the user performs touch-screen interaction with the 386 * window that is currently showing this wallpaper. Note that the 387 * events you receive here are driven by the actual application the 388 * user is interacting with, so if it is slow you will get fewer 389 * move events. 390 */ 391 public void onTouchEvent(MotionEvent event) { 392 } 393 394 /** 395 * Called to inform you of the wallpaper's offsets changing 396 * within its contain, corresponding to the container's 397 * call to {@link WallpaperManager#setWallpaperOffsets(IBinder, float, float) 398 * WallpaperManager.setWallpaperOffsets()}. 399 */ 400 public void onOffsetsChanged(float xOffset, float yOffset, 401 float xOffsetStep, float yOffsetStep, 402 int xPixelOffset, int yPixelOffset) { 403 } 404 405 /** 406 * Process a command that was sent to the wallpaper with 407 * {@link WallpaperManager#sendWallpaperCommand}. 408 * The default implementation does nothing, and always returns null 409 * as the result. 410 * 411 * @param action The name of the command to perform. This tells you 412 * what to do and how to interpret the rest of the arguments. 413 * @param x Generic integer parameter. 414 * @param y Generic integer parameter. 415 * @param z Generic integer parameter. 416 * @param extras Any additional parameters. 417 * @param resultRequested If true, the caller is requesting that 418 * a result, appropriate for the command, be returned back. 419 * @return If returning a result, create a Bundle and place the 420 * result data in to it. Otherwise return null. 421 */ 422 public Bundle onCommand(String action, int x, int y, int z, 423 Bundle extras, boolean resultRequested) { 424 return null; 425 } 426 427 /** 428 * Called when an application has changed the desired virtual size of 429 * the wallpaper. 430 */ 431 public void onDesiredSizeChanged(int desiredWidth, int desiredHeight) { 432 } 433 434 /** 435 * Convenience for {@link SurfaceHolder.Callback#surfaceChanged 436 * SurfaceHolder.Callback.surfaceChanged()}. 437 */ 438 public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) { 439 } 440 441 /** 442 * Convenience for {@link SurfaceHolder.Callback2#surfaceRedrawNeeded 443 * SurfaceHolder.Callback.surfaceRedrawNeeded()}. 444 */ 445 public void onSurfaceRedrawNeeded(SurfaceHolder holder) { 446 } 447 448 /** 449 * Convenience for {@link SurfaceHolder.Callback#surfaceCreated 450 * SurfaceHolder.Callback.surfaceCreated()}. 451 */ 452 public void onSurfaceCreated(SurfaceHolder holder) { 453 } 454 455 /** 456 * Convenience for {@link SurfaceHolder.Callback#surfaceDestroyed 457 * SurfaceHolder.Callback.surfaceDestroyed()}. 458 */ 459 public void onSurfaceDestroyed(SurfaceHolder holder) { 460 } 461 462 private void dispatchPointer(MotionEvent event) { 463 synchronized (mLock) { 464 if (event.getAction() == MotionEvent.ACTION_MOVE) { 465 mPendingMove = event; 466 } else { 467 mPendingMove = null; 468 } 469 } 470 471 Message msg = mCaller.obtainMessageO(MSG_TOUCH_EVENT, event); 472 mCaller.sendMessage(msg); 473 } 474 475 void updateSurface(boolean forceRelayout, boolean forceReport, boolean redrawNeeded) { 476 if (mDestroyed) { 477 Log.w(TAG, "Ignoring updateSurface: destroyed"); 478 } 479 480 int myWidth = mSurfaceHolder.getRequestedWidth(); 481 if (myWidth <= 0) myWidth = ViewGroup.LayoutParams.MATCH_PARENT; 482 int myHeight = mSurfaceHolder.getRequestedHeight(); 483 if (myHeight <= 0) myHeight = ViewGroup.LayoutParams.MATCH_PARENT; 484 485 final boolean creating = !mCreated; 486 final boolean surfaceCreating = !mSurfaceCreated; 487 final boolean formatChanged = mFormat != mSurfaceHolder.getRequestedFormat(); 488 boolean sizeChanged = mWidth != myWidth || mHeight != myHeight; 489 final boolean typeChanged = mType != mSurfaceHolder.getRequestedType(); 490 final boolean flagsChanged = mCurWindowFlags != mWindowFlags; 491 if (forceRelayout || creating || surfaceCreating || formatChanged || sizeChanged 492 || typeChanged || flagsChanged || redrawNeeded) { 493 494 if (DEBUG) Log.v(TAG, "Changes: creating=" + creating 495 + " format=" + formatChanged + " size=" + sizeChanged); 496 497 try { 498 mWidth = myWidth; 499 mHeight = myHeight; 500 mFormat = mSurfaceHolder.getRequestedFormat(); 501 mType = mSurfaceHolder.getRequestedType(); 502 503 mLayout.x = 0; 504 mLayout.y = 0; 505 mLayout.width = myWidth; 506 mLayout.height = myHeight; 507 508 mLayout.format = mFormat; 509 510 mCurWindowFlags = mWindowFlags; 511 mLayout.flags = mWindowFlags 512 | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS 513 | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN 514 | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE 515 ; 516 517 mLayout.memoryType = mType; 518 mLayout.token = mWindowToken; 519 520 if (!mCreated) { 521 mLayout.type = mIWallpaperEngine.mWindowType; 522 mLayout.gravity = Gravity.LEFT|Gravity.TOP; 523 mLayout.setTitle(WallpaperService.this.getClass().getName()); 524 mLayout.windowAnimations = 525 com.android.internal.R.style.Animation_Wallpaper; 526 mInputChannel = new InputChannel(); 527 if (mSession.add(mWindow, mLayout, View.VISIBLE, mContentInsets, 528 mInputChannel) < 0) { 529 Log.w(TAG, "Failed to add window while updating wallpaper surface."); 530 return; 531 } 532 mCreated = true; 533 534 InputQueue.registerInputChannel(mInputChannel, mInputHandler, 535 Looper.myQueue()); 536 } 537 538 mSurfaceHolder.mSurfaceLock.lock(); 539 mDrawingAllowed = true; 540 541 final int relayoutResult = mSession.relayout( 542 mWindow, mLayout, mWidth, mHeight, 543 View.VISIBLE, false, mWinFrame, mContentInsets, 544 mVisibleInsets, mConfiguration, mSurfaceHolder.mSurface); 545 546 if (DEBUG) Log.v(TAG, "New surface: " + mSurfaceHolder.mSurface 547 + ", frame=" + mWinFrame); 548 549 int w = mWinFrame.width(); 550 if (mCurWidth != w) { 551 sizeChanged = true; 552 mCurWidth = w; 553 } 554 int h = mWinFrame.height(); 555 if (mCurHeight != h) { 556 sizeChanged = true; 557 mCurHeight = h; 558 } 559 560 mSurfaceHolder.setSurfaceFrameSize(w, h); 561 mSurfaceHolder.mSurfaceLock.unlock(); 562 563 if (!mSurfaceHolder.mSurface.isValid()) { 564 reportSurfaceDestroyed(); 565 if (DEBUG) Log.v(TAG, "Layout: Surface destroyed"); 566 return; 567 } 568 569 try { 570 mSurfaceHolder.ungetCallbacks(); 571 572 if (surfaceCreating) { 573 mIsCreating = true; 574 if (DEBUG) Log.v(TAG, "onSurfaceCreated(" 575 + mSurfaceHolder + "): " + this); 576 onSurfaceCreated(mSurfaceHolder); 577 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 578 if (callbacks != null) { 579 for (SurfaceHolder.Callback c : callbacks) { 580 c.surfaceCreated(mSurfaceHolder); 581 } 582 } 583 } 584 585 redrawNeeded |= creating 586 || (relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0; 587 588 if (forceReport || creating || surfaceCreating 589 || formatChanged || sizeChanged) { 590 if (DEBUG) { 591 RuntimeException e = new RuntimeException(); 592 e.fillInStackTrace(); 593 Log.w(TAG, "forceReport=" + forceReport + " creating=" + creating 594 + " formatChanged=" + formatChanged 595 + " sizeChanged=" + sizeChanged, e); 596 } 597 if (DEBUG) Log.v(TAG, "onSurfaceChanged(" 598 + mSurfaceHolder + ", " + mFormat 599 + ", " + mCurWidth + ", " + mCurHeight 600 + "): " + this); 601 onSurfaceChanged(mSurfaceHolder, mFormat, 602 mCurWidth, mCurHeight); 603 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 604 if (callbacks != null) { 605 for (SurfaceHolder.Callback c : callbacks) { 606 c.surfaceChanged(mSurfaceHolder, mFormat, 607 mCurWidth, mCurHeight); 608 } 609 } 610 } 611 612 if (redrawNeeded) { 613 onSurfaceRedrawNeeded(mSurfaceHolder); 614 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 615 if (callbacks != null) { 616 for (SurfaceHolder.Callback c : callbacks) { 617 if (c instanceof SurfaceHolder.Callback2) { 618 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded( 619 mSurfaceHolder); 620 } 621 } 622 } 623 } 624 625 } finally { 626 mIsCreating = false; 627 mSurfaceCreated = true; 628 if (redrawNeeded) { 629 mSession.finishDrawing(mWindow); 630 } 631 } 632 } catch (RemoteException ex) { 633 } 634 if (DEBUG) Log.v( 635 TAG, "Layout: x=" + mLayout.x + " y=" + mLayout.y + 636 " w=" + mLayout.width + " h=" + mLayout.height); 637 } 638 } 639 640 void attach(IWallpaperEngineWrapper wrapper) { 641 if (DEBUG) Log.v(TAG, "attach: " + this + " wrapper=" + wrapper); 642 if (mDestroyed) { 643 return; 644 } 645 646 mIWallpaperEngine = wrapper; 647 mCaller = wrapper.mCaller; 648 mConnection = wrapper.mConnection; 649 mWindowToken = wrapper.mWindowToken; 650 mSurfaceHolder.setSizeFromLayout(); 651 mInitializing = true; 652 mSession = ViewRoot.getWindowSession(getMainLooper()); 653 654 mWindow.setSession(mSession); 655 656 IntentFilter filter = new IntentFilter(); 657 filter.addAction(Intent.ACTION_SCREEN_ON); 658 filter.addAction(Intent.ACTION_SCREEN_OFF); 659 registerReceiver(mReceiver, filter); 660 661 if (DEBUG) Log.v(TAG, "onCreate(): " + this); 662 onCreate(mSurfaceHolder); 663 664 mInitializing = false; 665 updateSurface(false, false, false); 666 } 667 668 void doDesiredSizeChanged(int desiredWidth, int desiredHeight) { 669 if (!mDestroyed) { 670 if (DEBUG) Log.v(TAG, "onDesiredSizeChanged(" 671 + desiredWidth + "," + desiredHeight + "): " + this); 672 mIWallpaperEngine.mReqWidth = desiredWidth; 673 mIWallpaperEngine.mReqHeight = desiredHeight; 674 onDesiredSizeChanged(desiredWidth, desiredHeight); 675 doOffsetsChanged(); 676 } 677 } 678 679 void doVisibilityChanged(boolean visible) { 680 if (!mDestroyed) { 681 mVisible = visible; 682 reportVisibility(); 683 } 684 } 685 686 void reportVisibility() { 687 if (!mDestroyed) { 688 boolean visible = mVisible && mScreenOn; 689 if (mReportedVisible != visible) { 690 mReportedVisible = visible; 691 if (DEBUG) Log.v(TAG, "onVisibilityChanged(" + visible 692 + "): " + this); 693 if (visible) { 694 // If becoming visible, in preview mode the surface 695 // may have been destroyed so now we need to make 696 // sure it is re-created. 697 updateSurface(false, false, false); 698 } 699 onVisibilityChanged(visible); 700 } 701 } 702 } 703 704 void doOffsetsChanged() { 705 if (mDestroyed) { 706 return; 707 } 708 709 float xOffset; 710 float yOffset; 711 float xOffsetStep; 712 float yOffsetStep; 713 boolean sync; 714 synchronized (mLock) { 715 xOffset = mPendingXOffset; 716 yOffset = mPendingYOffset; 717 xOffsetStep = mPendingXOffsetStep; 718 yOffsetStep = mPendingYOffsetStep; 719 sync = mPendingSync; 720 mPendingSync = false; 721 mOffsetMessageEnqueued = false; 722 } 723 724 if (mSurfaceCreated) { 725 if (DEBUG) Log.v(TAG, "Offsets change in " + this 726 + ": " + xOffset + "," + yOffset); 727 final int availw = mIWallpaperEngine.mReqWidth-mCurWidth; 728 final int xPixels = availw > 0 ? -(int)(availw*xOffset+.5f) : 0; 729 final int availh = mIWallpaperEngine.mReqHeight-mCurHeight; 730 final int yPixels = availh > 0 ? -(int)(availh*yOffset+.5f) : 0; 731 onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep, xPixels, yPixels); 732 } 733 734 if (sync) { 735 try { 736 if (DEBUG) Log.v(TAG, "Reporting offsets change complete"); 737 mSession.wallpaperOffsetsComplete(mWindow.asBinder()); 738 } catch (RemoteException e) { 739 } 740 } 741 } 742 743 void doCommand(WallpaperCommand cmd) { 744 Bundle result; 745 if (!mDestroyed) { 746 result = onCommand(cmd.action, cmd.x, cmd.y, cmd.z, 747 cmd.extras, cmd.sync); 748 } else { 749 result = null; 750 } 751 if (cmd.sync) { 752 try { 753 if (DEBUG) Log.v(TAG, "Reporting command complete"); 754 mSession.wallpaperCommandComplete(mWindow.asBinder(), result); 755 } catch (RemoteException e) { 756 } 757 } 758 } 759 760 void reportSurfaceDestroyed() { 761 if (mSurfaceCreated) { 762 mSurfaceCreated = false; 763 mSurfaceHolder.ungetCallbacks(); 764 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 765 if (callbacks != null) { 766 for (SurfaceHolder.Callback c : callbacks) { 767 c.surfaceDestroyed(mSurfaceHolder); 768 } 769 } 770 if (DEBUG) Log.v(TAG, "onSurfaceDestroyed(" 771 + mSurfaceHolder + "): " + this); 772 onSurfaceDestroyed(mSurfaceHolder); 773 } 774 } 775 776 void detach() { 777 if (mDestroyed) { 778 return; 779 } 780 781 mDestroyed = true; 782 783 if (mVisible) { 784 mVisible = false; 785 if (DEBUG) Log.v(TAG, "onVisibilityChanged(false): " + this); 786 onVisibilityChanged(false); 787 } 788 789 reportSurfaceDestroyed(); 790 791 if (DEBUG) Log.v(TAG, "onDestroy(): " + this); 792 onDestroy(); 793 794 unregisterReceiver(mReceiver); 795 796 if (mCreated) { 797 try { 798 if (DEBUG) Log.v(TAG, "Removing window and destroying surface " 799 + mSurfaceHolder.getSurface() + " of: " + this); 800 801 if (mInputChannel != null) { 802 InputQueue.unregisterInputChannel(mInputChannel); 803 } 804 805 mSession.remove(mWindow); 806 } catch (RemoteException e) { 807 } 808 mSurfaceHolder.mSurface.release(); 809 mCreated = false; 810 811 // Dispose the input channel after removing the window so the Window Manager 812 // doesn't interpret the input channel being closed as an abnormal termination. 813 if (mInputChannel != null) { 814 mInputChannel.dispose(); 815 mInputChannel = null; 816 } 817 } 818 } 819 } 820 821 class IWallpaperEngineWrapper extends IWallpaperEngine.Stub 822 implements HandlerCaller.Callback { 823 private final HandlerCaller mCaller; 824 825 final IWallpaperConnection mConnection; 826 final IBinder mWindowToken; 827 final int mWindowType; 828 final boolean mIsPreview; 829 int mReqWidth; 830 int mReqHeight; 831 832 Engine mEngine; 833 834 IWallpaperEngineWrapper(WallpaperService context, 835 IWallpaperConnection conn, IBinder windowToken, 836 int windowType, boolean isPreview, int reqWidth, int reqHeight) { 837 if (DEBUG && mCallbackLooper != null) { 838 mCallbackLooper.setMessageLogging(new LogPrinter(Log.VERBOSE, TAG)); 839 } 840 mCaller = new HandlerCaller(context, 841 mCallbackLooper != null 842 ? mCallbackLooper : context.getMainLooper(), 843 this); 844 mConnection = conn; 845 mWindowToken = windowToken; 846 mWindowType = windowType; 847 mIsPreview = isPreview; 848 mReqWidth = reqWidth; 849 mReqHeight = reqHeight; 850 851 Message msg = mCaller.obtainMessage(DO_ATTACH); 852 mCaller.sendMessage(msg); 853 } 854 855 public void setDesiredSize(int width, int height) { 856 Message msg = mCaller.obtainMessageII(DO_SET_DESIRED_SIZE, width, height); 857 mCaller.sendMessage(msg); 858 } 859 860 public void setVisibility(boolean visible) { 861 Message msg = mCaller.obtainMessageI(MSG_VISIBILITY_CHANGED, 862 visible ? 1 : 0); 863 mCaller.sendMessage(msg); 864 } 865 866 public void dispatchPointer(MotionEvent event) { 867 if (mEngine != null) { 868 mEngine.dispatchPointer(event); 869 } 870 } 871 872 public void dispatchWallpaperCommand(String action, int x, int y, 873 int z, Bundle extras) { 874 if (mEngine != null) { 875 mEngine.mWindow.dispatchWallpaperCommand(action, x, y, z, extras, false); 876 } 877 } 878 879 public void destroy() { 880 Message msg = mCaller.obtainMessage(DO_DETACH); 881 mCaller.sendMessage(msg); 882 } 883 884 public void executeMessage(Message message) { 885 switch (message.what) { 886 case DO_ATTACH: { 887 try { 888 mConnection.attachEngine(this); 889 } catch (RemoteException e) { 890 Log.w(TAG, "Wallpaper host disappeared", e); 891 return; 892 } 893 Engine engine = onCreateEngine(); 894 mEngine = engine; 895 mActiveEngines.add(engine); 896 engine.attach(this); 897 return; 898 } 899 case DO_DETACH: { 900 mActiveEngines.remove(mEngine); 901 mEngine.detach(); 902 return; 903 } 904 case DO_SET_DESIRED_SIZE: { 905 mEngine.doDesiredSizeChanged(message.arg1, message.arg2); 906 return; 907 } 908 case MSG_UPDATE_SURFACE: 909 mEngine.updateSurface(true, false, false); 910 break; 911 case MSG_VISIBILITY_CHANGED: 912 if (DEBUG) Log.v(TAG, "Visibility change in " + mEngine 913 + ": " + message.arg1); 914 mEngine.doVisibilityChanged(message.arg1 != 0); 915 break; 916 case MSG_WALLPAPER_OFFSETS: { 917 mEngine.doOffsetsChanged(); 918 } break; 919 case MSG_WALLPAPER_COMMAND: { 920 WallpaperCommand cmd = (WallpaperCommand)message.obj; 921 mEngine.doCommand(cmd); 922 } break; 923 case MSG_WINDOW_RESIZED: { 924 final boolean reportDraw = message.arg1 != 0; 925 mEngine.updateSurface(true, false, reportDraw); 926 mEngine.doOffsetsChanged(); 927 } break; 928 case MSG_TOUCH_EVENT: { 929 boolean skip = false; 930 MotionEvent ev = (MotionEvent)message.obj; 931 if (ev.getAction() == MotionEvent.ACTION_MOVE) { 932 synchronized (mEngine.mLock) { 933 if (mEngine.mPendingMove == ev) { 934 mEngine.mPendingMove = null; 935 } else { 936 // this is not the motion event we are looking for.... 937 skip = true; 938 } 939 } 940 } 941 if (!skip) { 942 if (DEBUG) Log.v(TAG, "Delivering touch event: " + ev); 943 mEngine.onTouchEvent(ev); 944 } 945 ev.recycle(); 946 } break; 947 default : 948 Log.w(TAG, "Unknown message type " + message.what); 949 } 950 } 951 } 952 953 /** 954 * Implements the internal {@link IWallpaperService} interface to convert 955 * incoming calls to it back to calls on an {@link WallpaperService}. 956 */ 957 class IWallpaperServiceWrapper extends IWallpaperService.Stub { 958 private final WallpaperService mTarget; 959 960 public IWallpaperServiceWrapper(WallpaperService context) { 961 mTarget = context; 962 } 963 964 public void attach(IWallpaperConnection conn, IBinder windowToken, 965 int windowType, boolean isPreview, int reqWidth, int reqHeight) { 966 new IWallpaperEngineWrapper(mTarget, conn, windowToken, 967 windowType, isPreview, reqWidth, reqHeight); 968 } 969 } 970 971 @Override 972 public void onCreate() { 973 super.onCreate(); 974 } 975 976 @Override 977 public void onDestroy() { 978 super.onDestroy(); 979 for (int i=0; i<mActiveEngines.size(); i++) { 980 mActiveEngines.get(i).detach(); 981 } 982 mActiveEngines.clear(); 983 } 984 985 /** 986 * Implement to return the implementation of the internal accessibility 987 * service interface. Subclasses should not override. 988 */ 989 @Override 990 public final IBinder onBind(Intent intent) { 991 return new IWallpaperServiceWrapper(this); 992 } 993 994 /** 995 * This allows subclasses to change the thread that most callbacks 996 * occur on. Currently hidden because it is mostly needed for the 997 * image wallpaper (which runs in the system process and doesn't want 998 * to get stuck running on that seriously in use main thread). Not 999 * exposed right now because the semantics of this are not totally 1000 * well defined and some callbacks can still happen on the main thread). 1001 * @hide 1002 */ 1003 public void setCallbackLooper(Looper looper) { 1004 mCallbackLooper = looper; 1005 } 1006 1007 /** 1008 * Must be implemented to return a new instance of the wallpaper's engine. 1009 * Note that multiple instances may be active at the same time, such as 1010 * when the wallpaper is currently set as the active wallpaper and the user 1011 * is in the wallpaper picker viewing a preview of it as well. 1012 */ 1013 public abstract Engine onCreateEngine(); 1014} 1015