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

Android 動態壁紙的調用原理與系統權限難題

編輯:關於 Android 程式設計

首先要理解一個前提:動態壁紙其實顯示在 Activity 的後面。Activity 必須是透明的,才能透出下面的壁紙;如果 Activity 不透明,就什麼也看不到了。

涉及的三個 AIDL 接口

在 framework 的 wallpaper 目錄下有三個 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();
}

代碼中主要用到 IWallpaperService 和 IWallpaperEngine 兩個接口。

定義與初始化變量

private WallpaperManager mWallpaperManager = null;
private WallpaperInfo mWallpaperInfo = null;
private WallpaperConnection mWallpaperConnection = null;
private Intent mWallpaperIntent;
mWallpaperManager = WallpaperManager.getInstance(this);

// 返回 null 說明當前不是動態壁紙
mWallpaperInfo = mWallpaperManager.getWallpaperInfo();

mWallpaperIntent = new Intent(WallpaperService.SERVICE_INTERFACE);
mWallpaperIntent.setClassName(mWallpaperInfo.getPackageName(),
                              mWallpaperInfo.getServiceName());

綁定壁紙服務

bindService(mIntent, this, Context.BIND_AUTO_CREATE);

IWallpaperService 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 一直失敗,排查後發現是權限問題——只有擁有系統簽名(system uid)的 apk 才能使用 WallpaperService.SERVICE_INTERFACE 這個服務。於是問題就轉化成了「如何獲取系統權限」。

這也說明了為什麼常規第三方應用無法直接以 Activity 的方式接管動態壁紙:這條路徑本身就被系統權限層攔住了。若只是想在自己的應用裡播放動態效果,更現實的做法是覆寫 WallpaperService 提供標準的動態壁紙,或使用普通的 SurfaceView 動畫。

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