Android WebView獨(dú)立進(jìn)程解決方案

App中大量Web頁(yè)面的使用容易導(dǎo)致App內(nèi)存占用巨大,存在內(nèi)存泄露,崩潰率高等問(wèn)題,WebView獨(dú)立進(jìn)程的使用是解決Android WebView相關(guān)問(wèn)題的一個(gè)合理的方案。

為什么要采用WebView獨(dú)立進(jìn)程

Android WebView的問(wèn)題

  1. WebView導(dǎo)致的OOM問(wèn)題
  2. Android版本不同,采用了不同的內(nèi)核,兼容性Crash
  3. WebView代碼質(zhì)量,WebView和Native版本不一致,導(dǎo)致Crash

Android App進(jìn)程的內(nèi)存使用是有限制的,通過(guò)以下兩個(gè)方法可以查看App可用內(nèi)存的大?。?/p>

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

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

Android WebView內(nèi)存占用很大,在低配置手機(jī)上,常有這樣的場(chǎng)景發(fā)生:連續(xù)開(kāi)啟多個(gè)WebView頁(yè)面,此時(shí)棧底的Activity被銷(xiāo)毀了,返回時(shí)Activity需要重新創(chuàng)建;或者連續(xù)開(kāi)啟多個(gè)Webview頁(yè)面,App中的某些單例對(duì)象被系統(tǒng)回收,此時(shí)如果未做特殊處理,就容易報(bào)數(shù)據(jù)空指針錯(cuò)誤。這些都是WebView導(dǎo)致的OOM的表現(xiàn)。WebView獨(dú)立進(jìn)程可以避免對(duì)主進(jìn)程內(nèi)存的占用。

問(wèn)題2 3也是Webview容易發(fā)生的,國(guó)產(chǎn)手機(jī)各家的內(nèi)核都不太一樣,Web頁(yè)面兼容沒(méi)有做到位容易導(dǎo)致Crash;隨著App版本和App-Web版本發(fā)布相互獨(dú)立,web頁(yè)面對(duì)native的依賴(lài)會(huì)變得復(fù)雜,版本兼容性沒(méi)有做好,也會(huì)導(dǎo)致webview與native進(jìn)行交互時(shí)發(fā)生crash。

微信經(jīng)驗(yàn)介紹

啟動(dòng)微信時(shí)進(jìn)程列表


打開(kāi)微信公眾號(hào)時(shí)進(jìn)程列表


image.png

打開(kāi)微信小程序時(shí)進(jìn)程列表


image.png

以上是微信的進(jìn)程list,簡(jiǎn)單分析一下各個(gè)進(jìn)程的功能如下:
com.tencent.mm :微信主進(jìn)程,會(huì)話和朋友圈相關(guān)
com.tencent.mm:push :微信push, ?;?br> com.tencent.mm:tools 和 com.tencent.mm:support : 功能支持,比如微信中打開(kāi)一個(gè)獨(dú)立網(wǎng)頁(yè)是在tools進(jìn)程中
com.tencent.mm:exdevice :估計(jì)是監(jiān)控手機(jī)相關(guān)的
com.tencent.mm:sandbox :公眾號(hào)進(jìn)程,公眾號(hào)打開(kāi)的頁(yè)面都是在該進(jìn)程中運(yùn)行
com.tencent.mm:appbrand :適用于小程序,測(cè)試發(fā)現(xiàn)微信每啟動(dòng)一個(gè)小程序,都會(huì)建立一個(gè)獨(dú)立的進(jìn)程 appbrand[0], 最多開(kāi)5個(gè)進(jìn)程

微信通過(guò)這樣的進(jìn)程分離,將網(wǎng)頁(yè)、公眾號(hào)、小程序分別分離到獨(dú)立進(jìn)程中,有效的增加了微信的內(nèi)存使用,避免了WebView對(duì)主進(jìn)程內(nèi)存的占用導(dǎo)致的主進(jìn)程服務(wù)異常;同時(shí)也通過(guò)這種獨(dú)立進(jìn)程方案避免了質(zhì)量參差不齊的公眾號(hào)網(wǎng)頁(yè)和小程序Crash影響主進(jìn)程的運(yùn)行。由此可見(jiàn),WebView獨(dú)立進(jìn)程方案是可行的,也是必要的。

如何實(shí)現(xiàn)WebView獨(dú)立進(jìn)程

WebView獨(dú)立進(jìn)程的實(shí)現(xiàn)

WebView獨(dú)立進(jìn)程的實(shí)現(xiàn)比較簡(jiǎn)單,只需要在AndroidManifest中找到對(duì)應(yīng)的WebViewActivity,對(duì)其配置"android: process"屬性即可。如下:

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

WebView進(jìn)程與主進(jìn)程間的數(shù)據(jù)通信

首先我們了解下為何兩個(gè)進(jìn)程間不能直接通信


image.png

Android多進(jìn)程的通訊方式有很多種,主要的方式有以下幾種:

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

考慮到WebView主要的通訊方式就是方法調(diào)用,所以采用AIDL方式。AIDL本質(zhì)采用的是Binder機(jī)制,這里貼一張網(wǎng)上的Binder機(jī)制原理圖,具體的AIDL的使用方式這里不贅述, 以下是幾個(gè)核心AIDL文件

image.png

IBinderPool: Webview進(jìn)程和主進(jìn)程的通訊可能涉及到多個(gè)AIDL Binder,從功能上來(lái)講,我們也會(huì)把不同功能的接口寫(xiě)成不同的AIDL Binder,所以IBinderPool用于滿足調(diào)用方根據(jù)不同類(lèi)型獲取不同的Binder。

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

IWebAidlInterface: 最核心的AIDL Binder,這里把WebView進(jìn)程對(duì)主進(jìn)程的每一個(gè)調(diào)用看做一次action, 每個(gè)action都會(huì)有唯一的actionName, 主進(jìn)程會(huì)提前注冊(cè)好這些action,action 也有級(jí)別level,每次調(diào)用結(jié)束通過(guò)IWebAidlCallback返回結(jié)果

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

 }

IWebAidlCallback: 結(jié)果回調(diào)

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

為了維護(hù)獨(dú)立進(jìn)程和主進(jìn)程之間的連接,避免每次aidl調(diào)用時(shí)都去重新進(jìn)行binder連接和獲取,需要專(zhuān)門(mén)提供一個(gè)類(lèi)去維護(hù)連接,并根據(jù)條件返回Binder. 這個(gè)類(lèi)就叫做 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;
        }
    }

}

從代碼中可以看到這個(gè)連接池連接的是主進(jìn)程 MainProHandleRemoteService.

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

Native-Web交互和接口管理

一次完整的Web頁(yè)面和Native交互過(guò)程是這樣的:

  1. Native打開(kāi)頁(yè)面時(shí)注冊(cè)接口:“webView.addJavascriptInterface(jsInterface, "webview");” 其中jsInterface是JsRemoteInterface類(lèi)的實(shí)例:
public final class JsRemoteInterface {
    @JavascriptInterface
    public void post(String cmd, String param) {
        ...
    }
  1. Web頁(yè)面通過(guò)“window.webview.post(cmd,JSON.stringify(para))”調(diào)用native;
  2. Native(即Webview進(jìn)程)收到調(diào)用之后,通過(guò)IWebAidlInterface實(shí)例傳遞給主進(jìn)程執(zhí)行;
  3. 主進(jìn)程收到action請(qǐng)求之后,根據(jù)actionname分發(fā)處理,執(zhí)行結(jié)束之后通過(guò)IWebAidlCallback完成進(jìn)程間回調(diào)。

其中,通用的Action結(jié)構(gòu)如下:

public interface Command {

    String name();

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

根據(jù)不同的Level將所有的command提前注冊(cè)好, 以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 負(fù)責(zé)分發(fā)action,結(jié)構(gòu)如下:

public class CommandsManager {

    private static CommandsManager instance;

    public static final int LEVEL_BASE = 1; // 基礎(chǔ)level
    public static final int LEVEL_ACCOUNT = 2; // 涉及到賬號(hào)相關(guān)的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);
        }
    }

}

描述可能有些不清楚的地方,更詳細(xì)的源碼請(qǐng)轉(zhuǎn)到 github webprogress: Android WebView獨(dú)立進(jìn)程解決方案,歡迎大家star.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容