App中大量Web頁面的使用容易導致App內存占用巨大,存在內存泄露,崩潰率高等問題,WebView獨立進程的使用是解決Android WebView相關問題的一個合理的方案。
為什么要采用WebView獨立進程
Android WebView的問題
- WebView導致的OOM問題
- Android版本不同,采用了不同的內核,兼容性Crash
- 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。
微信經驗介紹
啟動微信時進程列表
打開微信公眾號時進程列表
打開微信小程序時進程列表
以上是微信的進程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進程與主進程間的數據通信
首先我們了解下為何兩個進程間不能直接通信
Android多進程的通訊方式有很多種,主要的方式有以下幾種:
- AIDL
- Messenger
- ContentProvider
- 共享文件
- 組件間Bundle傳遞
- Socket傳輸
考慮到WebView主要的通訊方式就是方法調用,所以采用AIDL方式。AIDL本質采用的是Binder機制,這里貼一張網上的Binder機制原理圖,具體的AIDL的使用方式這里不贅述, 以下是幾個核心AIDL文件
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交互過程是這樣的:
- Native打開頁面時注冊接口:“webView.addJavascriptInterface(jsInterface, "webview");” 其中jsInterface是JsRemoteInterface類的實例:
public final class JsRemoteInterface {
@JavascriptInterface
public void post(String cmd, String param) {
...
}
- Web頁面通過“window.webview.post(cmd,JSON.stringify(para))”調用native;
- Native(即Webview進程)收到調用之后,通過IWebAidlInterface實例傳遞給主進程執行;
- 主進程收到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.