亲宝软件园·资讯

展开

android webView独立进程 详解android webView独立进程通讯方式

区区一只yamada 人气:0
想了解详解android webView独立进程通讯方式的相关内容吗,区区一只yamada在本文为您仔细讲解android webView独立进程的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:android,独立进程,android,独立进程通讯,android,进程通讯,下面大家一起来学习吧。

为什么需要将webView放在独立进程

webView独立进程需要注意什么

如何声明一个独立进程

在默认情况下,同一应用的所有组件都在相同的进程中运行。
在Manifest中可以设置各组件 (<activity>、<service>、<receiver>、<provider>)的 android:process 属性来指定相应的进程。

跨进程的方式

在android当中提供了2种方式实现。

一种是Messenger, 另一种是Aidl.

Messenger

由于Messenger是采用消息队列的方式实现,所有接受和发送的时候都需要Handler协助。

服务端

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:
          //客服端向服务端请求数据
          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:
          //客服端向服务端请求更新数据
          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");
    //屏幕自适应
    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);
    //用于服务端应答
    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

第一步:创建.aidl文件

aidl文件:

interface IAidlProcess {

  //默认支持原语类型(int、long、char等等)、String、CharSequence、List、Map
  //自定义类型需要导入 import eebochina.com.testtechniques.testwebview.XXXClass
  //自定义类型传输一定需要是序列化对象
  String getCustomData();

  void setCustomData(String str);
}

服务端

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;
    }
  };

在获取了绑定接口后就可以直接和服务端通讯了。

2种通讯方式都简单的介绍了下,后面的实际应用还需要根据不同的业务进行调整。

由于aidl是方法直接调用的,从代码扩展和阅读来说比messenger要强很多。

如果有写的不好和不对的地方,希望大家可以及时指出来。

加载全部内容

相关教程
猜你喜欢
用户评论