詳解android webView獨立進程通訊方式
為什么需要將webView放在獨立進程
- webView 加載網(wǎng)頁的時候可能占用大量內(nèi)存,導(dǎo)致應(yīng)用程序OOM。
- webView 在訪問結(jié)束的時候可以直接殺死該進程,防止內(nèi)存泄漏。
- webView 在崩潰的時候不影響主進程。
webView獨立進程需要注意什么
- 由于進程之間內(nèi)存是獨立的,所以導(dǎo)致了Appcation, 靜態(tài)類需要在新的進程重新創(chuàng)建。
- 內(nèi)存中的數(shù)據(jù)不共享,需要跨進程通訊。
如何聲明一個獨立進程
在默認情況下,同一應(yīng)用的所有組件都在相同的進程中運行。
在Manifest中可以設(shè)置各組件 (<activity>、<service>、<receiver>、<provider>)的 android:process 屬性來指定相應(yīng)的進程。
跨進程的方式
在android當中提供了2種方式實現(xiàn)。
一種是Messenger, 另一種是Aidl.
- Messenger:實現(xiàn)相對簡單,將所有請求放到消息隊列中,不適合做并發(fā)處理,在大多數(shù)的場景用Messenger就可以實現(xiàn)了。
- AIDL: 適合并發(fā)操作。直接方法調(diào)用,結(jié)構(gòu)更清晰。
Messenger
由于Messenger是采用消息隊列的方式實現(xiàn),所有接受和發(fā)送的時候都需要Handler協(xié)助。
服務(wù)端
public class MessengerService extends Service {
public static final int GET_DATA = 1;
public static final int SET_DATA = 2;
Messenger messenger = new Messenger(new ServiceHandler());
Messenger replyMessenger; //向客服端返回信息
public MessengerService() {
}
@Override
public IBinder onBind(Intent intent) {
return messenger.getBinder();
}
class ServiceHandler extends Handler {
@Override
public void handleMessage(Message msg) {
replyMessenger = msg.replyTo;
switch (msg.what) {
case GET_DATA:
//客服端向服務(wù)端請求數(shù)據(jù)
if (replyMessenger != null) {
Bundle bundle = new Bundle();
bundle.putString("str", CustomData.getInstance().getData());
Message message = Message.obtain(null, 1);
message.setData(bundle);
try {
replyMessenger.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
}
break;
case SET_DATA:
//客服端向服務(wù)端請求更新數(shù)據(jù)
CustomData.getInstance().setData(msg.getData().getString("str"));
break;
}
}
}
}
客服端:
public class MessengerClientActivity extends AppCompatActivity {
private WebView mWebView;
private Button mGetDatBtn;
private Button mSetDatBtn;
public static void startThis(Context context, String url) {
Intent intent = new Intent(context, MessengerClientActivity.class);
intent.putExtra("url", url);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messenger_client);
mWebView = (WebView) findViewById(R.id.webview);
mGetDatBtn = (Button) findViewById(R.id.get_data_btn);
mSetDatBtn = (Button) findViewById(R.id.set_data_btn);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportZoom(false);
webSettings.setBuiltInZoomControls(false);
webSettings.setAllowFileAccess(true);
webSettings.setDatabaseEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setGeolocationEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setAppCachePath(getApplicationContext().getCacheDir().getPath());
webSettings.setDefaultTextEncodingName("UTF-8");
//屏幕自適應(yīng)
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
} else {
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
webSettings.setDisplayZoomControls(false);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webSettings.setLoadsImagesAutomatically(true);
} else {
webSettings.setLoadsImagesAutomatically(false);
}
mWebView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setHorizontalFadingEdgeEnabled(false);
mWebView.setVerticalFadingEdgeEnabled(false);
String url = "http://www.jianshu.com/";
mWebView.loadUrl(url);
mGetDatBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getData();
}
});
mSetDatBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setData();
}
});
}
Messenger messenger;
Messenger messengerReply = new Messenger(new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MessengerService.GET_DATA:
mGetDatBtn.setText("" + msg.getData().get("str"));
break;
}
}
});
boolean mBound;
ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
messenger = new Messenger(service);
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
messenger = null;
mBound = false;
}
};
private void getData() {
if (!mBound) return;
Message message = Message.obtain(null, MessengerService.GET_DATA, 0,0);
//用于服務(wù)端應(yīng)答
message.replyTo = messengerReply;
sendMessage(message);
}
private void setData() {
if (!mBound) return;
Message message = Message.obtain(null, MessengerService.SET_DATA, 0,0);
sendMessage(message);
}
private void sendMessage(Message message) {
try {
messenger.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
protected void onStart() {
super.onStart();
// Bind to the service
bindService(new Intent(this, TestWebService.class), serviceConnection,
Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(serviceConnection);
mBound = false;
}
}
private void destroyWebView(WebView webView) {
if (webView == null)
return;
webView.stopLoading();
ViewParent viewParent = webView.getParent();
if (viewParent != null && viewParent instanceof ViewGroup)
((ViewGroup) viewParent).removeView(webView);
webView.removeAllViews();
webView.destroy();
webView = null;
}
@Override
protected void onDestroy() {
destroyWebView(mWebView);
super.onDestroy();
}
}
AIDL
第一步:創(chuàng)建.aidl文件
- aidl默認支持以下的類型:
- Java 編程語言中的所有原語類型(如 int、long、char、boolean 等等)
- String
- CharSequence
- List
- Map
- 如果需要導(dǎo)入自己的類型需要加入一個 import 語句(注意:導(dǎo)入的類需要實現(xiàn)Parcelabel接口)
aidl文件:
interface IAidlProcess {
//默認支持原語類型(int、long、char等等)、String、CharSequence、List、Map
//自定義類型需要導(dǎo)入 import eebochina.com.testtechniques.testwebview.XXXClass
//自定義類型傳輸一定需要是序列化對象
String getCustomData();
void setCustomData(String str);
}
服務(wù)端
public class AidlService extends Service {
public AidlService() {
}
ITestProcess.Stub mBinder = new ITestProcess.Stub() {
@Override
public String getCustomData() throws RemoteException {
return CustomData.getInstance().getData();
}
@Override
public void setCustomData(String str) throws RemoteException {
CustomData.getInstance().setData(str);
}
};
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
}
客服端獲取綁定接口
AidlService mAidlService;
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mAidlService = IAidlProcess.Stub.asInterface(service);
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
mBound = false;
mAidlService = null;
}
};
在獲取了綁定接口后就可以直接和服務(wù)端通訊了。
2種通訊方式都簡單的介紹了下,后面的實際應(yīng)用還需要根據(jù)不同的業(yè)務(wù)進行調(diào)整。
由于aidl是方法直接調(diào)用的,從代碼擴展和閱讀來說比messenger要強很多。
如果有寫的不好和不對的地方,希望大家可以及時指出來。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android利用AsyncTask異步類實現(xiàn)網(wǎng)頁內(nèi)容放大縮小
這篇文章主要為大家介紹了利用AsyncTask異步類實現(xiàn)網(wǎng)頁內(nèi)容放大縮小的相關(guān)資料,感興趣的小伙伴們可以參考一下2016-07-07
Flutter 封裝一個 Banner 輪播圖效果的實例代碼
這篇文章主要介紹了Flutter 封裝一個 Banner 輪播圖效果,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07
Android使用post方式上傳圖片到服務(wù)器的方法
這篇文章主要介紹了Android使用post方式上傳圖片到服務(wù)器的方法,結(jié)合實例形式分析了Android文件傳輸?shù)南嚓P(guān)技巧,需要的朋友可以參考下2016-03-03
Android自定義StickinessView粘性滑動效果
這篇文章主要為大家詳細介紹了Android自定義StickinessView粘性滑動效果的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-03-03
Android編程實現(xiàn)網(wǎng)絡(luò)圖片查看器和網(wǎng)頁源碼查看器實例
這篇文章主要介紹了Android編程實現(xiàn)網(wǎng)絡(luò)圖片查看器和網(wǎng)頁源碼查看器,結(jié)合實例形式分析了Android針對網(wǎng)絡(luò)圖片及網(wǎng)頁的相關(guān)操作技巧,具有一定參考借鑒價值,需要的朋友可以參考下2016-01-01
android開發(fā)教程之間隔執(zhí)行程序(android計時器)
android開發(fā)中有些情況需要隔一段時間去執(zhí)行某個操作一次或者是每隔一段時間久執(zhí)行某個操作,下面是實現(xiàn)方法2014-02-02

