Android WebView獨立進程解決方案

App中大量Web頁面的使用容易導致App內存占用巨大,存在內存泄露,崩潰率高等問題,WebView獨立進程的使用是解決Android WebView相關問題的一個合理的方案。

為什么要采用WebView獨立進程

Android WebView的問題

  1. WebView導致的OOM問題
  2. Android版本不同,采用了不同的內核,兼容性Crash
  3. WebView代碼質量,WebView和Native版本不一致,導致Crash

Android App進程的內存使用是有限制的,通過以下兩個方法可以查看App可用內存的大小:

ActivityManager.getMemoryClass()獲得正常情況下可用內存的大小
ActivityManager.getLargeMemoryClass()可以獲得開啟largeHeap最大的內存大小

以Google Nexus 6P為例,正常情況下可用內存是192M,最大可用內存是512M。

Android WebView內存占用很大,在低配置手機上,常有這樣的場景發生:連續開啟多個WebView頁面,此時棧底的Activity被銷毀了,返回時Activity需要重新創建;或者連續開啟多個Webview頁面,App中的某些單例對象被系統回收,此時如果未做特殊處理,就容易報數據空指針錯誤。這些都是WebView導致的OOM的表現。WebView獨立進程可以避免對主進程內存的占用。

問題2 3也是Webview容易發生的,國產手機各家的內核都不太一樣,Web頁面兼容沒有做到位容易導致Crash;隨著App版本和App-Web版本發布相互獨立,web頁面對native的依賴會變得復雜,版本兼容性沒有做好,也會導致webview與native進行交互時發生crash。

微信經驗介紹

啟動微信時進程列表


打開微信公眾號時進程列表


image.png

打開微信小程序時進程列表


image.png

以上是微信的進程list,簡單分析一下各個進程的功能如下:
com.tencent.mm :微信主進程,會話和朋友圈相關
com.tencent.mm:push :微信push, 保活
com.tencent.mm:tools 和 com.tencent.mm:support : 功能支持,比如微信中打開一個獨立網頁是在tools進程中
com.tencent.mm:exdevice :估計是監控手機相關的
com.tencent.mm:sandbox :公眾號進程,公眾號打開的頁面都是在該進程中運行
com.tencent.mm:appbrand :適用于小程序,測試發現微信每啟動一個小程序,都會建立一個獨立的進程 appbrand[0], 最多開5個進程

微信通過這樣的進程分離,將網頁、公眾號、小程序分別分離到獨立進程中,有效的增加了微信的內存使用,避免了WebView對主進程內存的占用導致的主進程服務異常;同時也通過這種獨立進程方案避免了質量參差不齊的公眾號網頁和小程序Crash影響主進程的運行。由此可見,WebView獨立進程方案是可行的,也是必要的。

如何實現WebView獨立進程

WebView獨立進程的實現

WebView獨立進程的實現比較簡單,只需要在AndroidManifest中找到對應的WebViewActivity,對其配置"android: process"屬性即可。如下:

<activity
    android:name=".remote.RemoteCommonWebActivity"
    android:configChanges="orientation|keyboardHidden|screenSize"
    android:process=":remoteWeb"/>

WebView進程與主進程間的數據通信

首先我們了解下為何兩個進程間不能直接通信


image.png

Android多進程的通訊方式有很多種,主要的方式有以下幾種:

  1. AIDL
  2. Messenger
  3. ContentProvider
  4. 共享文件
  5. 組件間Bundle傳遞
  6. Socket傳輸

考慮到WebView主要的通訊方式就是方法調用,所以采用AIDL方式。AIDL本質采用的是Binder機制,這里貼一張網上的Binder機制原理圖,具體的AIDL的使用方式這里不贅述, 以下是幾個核心AIDL文件

image.png

IBinderPool: Webview進程和主進程的通訊可能涉及到多個AIDL Binder,從功能上來講,我們也會把不同功能的接口寫成不同的AIDL Binder,所以IBinderPool用于滿足調用方根據不同類型獲取不同的Binder。

interface IBinderPool {
    IBinder queryBinder(int binderCode);  //查找特定Binder的方法
}

IWebAidlInterface: 最核心的AIDL Binder,這里把WebView進程對主進程的每一個調用看做一次action, 每個action都會有唯一的actionName, 主進程會提前注冊好這些action,action 也有級別level,每次調用結束通過IWebAidlCallback返回結果

interface IWebAidlInterface {
    
    /**
     * actionName: 不同的action, jsonParams: 需要根據不同的action從map中讀取并依次轉成其他
     */
    void handleWebAction(int level, String actionName, String jsonParams, in IWebAidlCallback callback);

 }

IWebAidlCallback: 結果回調

interface IWebAidlCallback {
    void onResult(int responseCode, String actionName, String response);
}

為了維護獨立進程和主進程之間的連接,避免每次aidl調用時都去重新進行binder連接和獲取,需要專門提供一個類去維護連接,并根據條件返回Binder. 這個類就叫做 RemoteWebBinderPool

public class RemoteWebBinderPool {

    public static final int BINDER_WEB_AIDL = 1;

    private Context mContext;
    private IBinderPool mBinderPool;
    private static volatile RemoteWebBinderPool sInstance;
    private CountDownLatch mConnectBinderPoolCountDownLatch;

    private RemoteWebBinderPool(Context context) {
        mContext = context.getApplicationContext();
        connectBinderPoolService();
    }

    public static RemoteWebBinderPool getInstance(Context context) {
        if (sInstance == null) {
            synchronized (RemoteWebBinderPool.class) {
                if (sInstance == null) {
                    sInstance = new RemoteWebBinderPool(context);
                }
            }
        }
        return sInstance;
    }

    private synchronized void connectBinderPoolService() {
        mConnectBinderPoolCountDownLatch = new CountDownLatch(1);
        Intent service = new Intent(mContext, MainProHandleRemoteService.class);
        mContext.bindService(service, mBinderPoolConnection, Context.BIND_AUTO_CREATE);
        try {
            mConnectBinderPoolCountDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public IBinder queryBinder(int binderCode) {
        IBinder binder = null;
        try {
            if (mBinderPool != null) {
                binder = mBinderPool.queryBinder(binderCode);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return binder;
    }

    private ServiceConnection mBinderPoolConnection = new ServiceConnection() {   // 5

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mBinderPool = IBinderPool.Stub.asInterface(service);
            try {
                mBinderPool.asBinder().linkToDeath(mBinderPoolDeathRecipient, 0);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            mConnectBinderPoolCountDownLatch.countDown();
        }
    };

    private IBinder.DeathRecipient mBinderPoolDeathRecipient = new IBinder.DeathRecipient() {    // 6
        @Override
        public void binderDied() {
            mBinderPool.asBinder().unlinkToDeath(mBinderPoolDeathRecipient, 0);
            mBinderPool = null;
            connectBinderPoolService();
        }
    };

    public static class BinderPoolImpl extends IBinderPool.Stub {

        private Context context;

        public BinderPoolImpl(Context context) {
            this.context = context;
        }

        @Override
        public IBinder queryBinder(int binderCode) throws RemoteException {
            IBinder binder = null;
            switch (binderCode) {
                case BINDER_WEB_AIDL: {
                    binder = new MainProAidlInterface(context);
                    break;
                }
                default:
                    break;
            }
            return binder;
        }
    }

}

從代碼中可以看到這個連接池連接的是主進程 MainProHandleRemoteService.

public class MainProHandleRemoteService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Binder mBinderPool = new RemoteWebBinderPool.BinderPoolImpl(context);
        return mBinderPool;
    }
}

Native-Web交互和接口管理

一次完整的Web頁面和Native交互過程是這樣的:

  1. Native打開頁面時注冊接口:“webView.addJavascriptInterface(jsInterface, "webview");” 其中jsInterface是JsRemoteInterface類的實例:
public final class JsRemoteInterface {
    @JavascriptInterface
    public void post(String cmd, String param) {
        ...
    }
  1. Web頁面通過“window.webview.post(cmd,JSON.stringify(para))”調用native;
  2. Native(即Webview進程)收到調用之后,通過IWebAidlInterface實例傳遞給主進程執行;
  3. 主進程收到action請求之后,根據actionname分發處理,執行結束之后通過IWebAidlCallback完成進程間回調。

其中,通用的Action結構如下:

public interface Command {

    String name();

    void exec(Context context, Map params, ResultBack resultBack);
}

根據不同的Level將所有的command提前注冊好, 以BaseLevelCommand為例:

public class BaseLevelCommands {

    private HashMap<String, Command> commands;
    private Context mContext;

    public BaseLevelCommands(Context context) {
        this.mContext = context;
        registerCommands();
    }

    private void registerCommands() {
        commands = new HashMap<>();
        registerCommand(playVideoByNativeCommand);
    }

    private Command playVideoByNativeCommand = new Command() {
        @Override
        public String name() {
            return "videoPlay";
        }

        @Override
        public void exec(Context context, Map params, ResultBack resultBack) {
            if (params != null) {
                String videoUrl = (String) params.get("url");
                if (!TextUtils.isEmpty(videoUrl)) {
                    String suffix = videoUrl.substring(videoUrl.lastIndexOf(".") + 1);
                    DJFullScreenActivity.startActivityWithLanscape(context, videoUrl, DJFullScreenActivity.getVideoType(suffix), DJVideoPlayer.class, " ");
                }
            }
        }
    };
}

CommandsManager 負責分發action,結構如下:

public class CommandsManager {

    private static CommandsManager instance;

    public static final int LEVEL_BASE = 1; // 基礎level
    public static final int LEVEL_ACCOUNT = 2; // 涉及到賬號相關的level

    private Context context;
    private BaseLevelCommands baseLevelCommands;
    private AccountLevelCommands accountLevelCommands;

    private CommandsManager(Context context) {
        this.context = context;
        baseLevelCommands = new BaseLevelCommands(context);
        accountLevelCommands = new AccountLevelCommands(context);
    }

    public static CommandsManager getInstance(Context context) {
        if (instance == null) {
            synchronized (CommandsManager.class) {
                instance = new CommandsManager(context);
            }
        }
        return instance;
    }

    public void findAndExec(int level, String action, Map params, ResultBack resultBack) {
        boolean methodFlag = false;
        switch (level) {
            case LEVEL_BASE: {
                if (baseLevelCommands.getCommands().get(action) != null) {
                    methodFlag = true;
                    baseLevelCommands.getCommands().get(action).exec(context, params, resultBack);
                }
                if (accountLevelCommands.getCommands().get(action) != null) {
                    AidlError aidlError = new AidlError(RemoteActionConstants.ERRORCODE.NO_AUTH, RemoteActionConstants.ERRORMESSAGE.NO_AUTH);
                    resultBack.onResult(RemoteActionConstants.FAILED, action, aidlError);
                }
                break;
            }
            case LEVEL_ACCOUNT: {
                if (baseLevelCommands.getCommands().get(action) != null) {
                    methodFlag = true;
                    baseLevelCommands.getCommands().get(action).exec(context, params, resultBack);
                }
                if (accountLevelCommands.getCommands().get(action) != null) {
                    methodFlag = true;
                    accountLevelCommands.getCommands().get(action).exec(context, params, resultBack);
                }
                break;
            }
        }
        if (!methodFlag) {
            AidlError aidlError = new AidlError(RemoteActionConstants.ERRORCODE.NO_METHOD, RemoteActionConstants.ERRORMESSAGE.NO_METHOD);
            resultBack.onResult(RemoteActionConstants.FAILED, action, aidlError);
        }
    }

}

描述可能有些不清楚的地方,更詳細的源碼請轉到 github webprogress: Android WebView獨立進程解決方案,歡迎大家star.

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,748評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,165評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,595評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,633評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,435評論 6 405
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,943評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,035評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,175評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,713評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,599評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,788評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,303評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,034評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,412評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,664評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,408評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,747評論 2 370