Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 動態壁紙的調用原理與實現

編輯:關於 Android 程式設計

動態壁紙的實現,本質上是在 Activity 中調用壁紙服務:透過綁定服務取得 IWallpaperService,再調用該接口的 attach 函數來完成壁紙的挂載。

值得特別注意的是,調用之後動態壁紙其實是顯示在 Activity 的「背後」,而 Activity 本身則以透明方式呈現,這樣用戶才能透見下方的動態壁紙。倘若 Activity 並非透明,那麼壁紙便會被完全遮擋,什麼也看不到。

涉及的兩個核心接口

代碼中會用到以下兩個接口:

IWallpaperService mService;
IWallpaperEngine mEngine;

在相應目錄下可以看到三個 aidl 接口定義,分別是:

interface IWallpaperConnection {
  void attachEngine(IWallpaperEngine engine);
  ParcelFileDescriptor setWallpaper(String name);
}

oneway interface IWallpaperService {
  void attach(IWallpaperConnection connection, IBinder windowToken, int windowType, boolean isPreview, int reqWidth, int reqHeight);
}

oneway interface IWallpaperEngine {
  void setDesiredSize(int width, int height);
  void setVisibility(boolean visible);
  void dispatchPointer(in MotionEvent event);
  void dispatchWallpaperCommand(String action, int x, int y, int z, in Bundle extras);
  void destroy();
}

定義壁紙管理與信息變量

private WallpaperManager mWallpaperManager = null;
private WallpaperInfo mWallpaperInfo = null;
private WallpaperConnection mWallpaperConnection = null;
private Intent mWallpaperIntent;

初始化這些變量

mWallpaperManager = WallpaperManager.getInstance(this);
mWallpaperInfo = mWallpaperManager.getWallpaperInfo();//若返回 null,則說明當前並非動態壁紙
mWallpaperIntent = new Intent(WallpaperService.SERVICE_INTERFACE);
mWallpaperIntent.setClassName(mWallpaperInfo.getPackageName(), mWallpaperInfo.getServiceName());

綁定動態壁紙服務

bindService(mIntent, this, Context.BIND_AUTO_CREATE);

其中 mService 就是前面提到的 aidl 接口。在連接監聽回調中嘗試執行 attach:

public void onServiceConnected(ComponentName name, IBinder service) {
 mService = IWallpaperService.Stub.asInterface(service);
 try {
  mService.attach(this, view.getWindowToken(),
   // WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA_OVERLAY,
   WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA,
   true, root.getWidth(), root.getHeight());
 } catch (RemoteException e) {
  Log.w("", "Failed attaching wallpaper; clearing", e);
 }
}

踩坑記錄:權限問題

在實踐過程中,我發現 bindService 總是失敗。排查之後才意識到這是權限問題——只有具備系統權限的 apk 才能使用 WallpaperService.SERVICE_INTERFACE 服務。於是問題便轉化為:該如何獲取系統權限。這一步往往需要將應用打包為系統簽名,或放入系統的特定目錄下,才能順利調用該壁紙服務。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved