Android integration

更新时间:
复制 MD 格式

EMAS provides WindVane for H5 application integration. This topic describes how to integrate WindVane on Android.

Initialization

  1. Add the dependency to the app/build.gradle file.

    implementation ('com.emas.hybrid:emas-hybrid-android:1.1.2-open') {transitive true}

  2. Add the activity permission.

    <activity android:name="android.taobao.windvane.runtimepermission.PermissionActivity" />
  3. Initialize EmasHybrid in a suitable location in your Application, typically in the onCreate method.

    // Custom adapter (optional)
    EmasHybrid.Config.Builder builder = new EmasHybrid.Config.Builder();
        builder.setNavigatorAdapter(new INavigatorAdapter() {
        
        }).setStorageAdapter(new IStorageAdapter() {
         
        });
    
    EmasHybrid.getInstance()
        .setOpenLog(true)
        .setAppKey(mAppkey)
        .setAppSecret(mAppSecret)
        .setTtid(mChannelID)
        .setAppVersion(BuildConfig.VERSION_NAME)
        .setConfig(builder.build())// Custom adapter, optional
        .init(application);
    Note
    • INavigatorAdapter: The navigator module. The system provides default implementations for pop and push. You can also create custom implementations.

    • IStorageAdapter: The storage module. The system provides default implementations for setItem, getItem, and removeItem. You can also create custom implementations.

Create a container activity

To ensure maximum integration flexibility, this software development kit (SDK) provides an H5 container as a fragment. You can use the provided EmasHybridInstance to render the H5 container fragment to a suitable location in your activity. The following code provides an example:

public class WebViewSampleActivity extends BaseActivity {
    private Fragment webViewFragment;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview_sample);
  
        webViewFragment = EmasHybridWebViewHelper.getInstance().installWebView(
            this,
            Uri.parse("https://emas.xxx.com/"),
            R.id.root,
            new WVWebViewClient(this) {
                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                }
            }, 
            null);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webViewFragment != null) {
            boolean result = EmasHybrid.getInstance().isUseUc()
                ? ((WVUCWebViewFragment) webViewFragment).onBackPressed()
                : ((WVWebViewFragment) webViewFragment).onBackPressed();
            return result || super.onKeyDown(keyCode, event);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        webViewFragment.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onPause() {
        webViewFragment.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        webViewFragment.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        webViewFragment.onDestroy();
        super.onDestroy();
    }
}

Register the activity

To ensure that the built-in navigator module functions correctly, add the following IntentFilter configuration to your activity.

<intent-filter>
    <action android:name="android.intent.action.VIEW"/>
    <category android:name="android.intent.category.BROWSABLE" />
    <category android:name="com.emas.android.intent.category.HYBRID" />
    <category android:name="android.intent.category.DEFAULT"/>

    <data android:scheme="http"/>
    <data android:scheme="https"/>
</intent-filter>
Note

The scheme in the data tag corresponds to the scheme that the navigator module requires for navigation. You can define more custom schemes.

Add the fragment to the activity

  1. Add a FrameLayout to your layout file. The following code provides an example:

    <FrameLayout
        android:id="@+id/root"
        android:layout_width="match_parent"
        android:layout_height="match_content">
    </FrameLayout>
  2. In the activity, use EmasHybridInstance to render the fragment.

    webViewFragment = EmasHybridWebViewHelper.getInstance().installWebView(this,
        getIntent().getData(),
        R.id.root,
        new WVWebViewClient(this){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        }, 
        null);
    Note

    The rendering URL is stored in the Intent data.

  3. Add handling for the back button and callbacks in the activity.

    @Override
    public boolean onKeyDown(int keyCode, KeyEventevent) {
        if (keyCode == KeyEvent.KEYCODE_BACK&& webViewFragment != null) {
            boolean result = EmasHybrid.getInstance().isUseUc() ? ((WVUCWebViewFragment) webViewFragment).onBackPressed() : ((WVWebViewFragment) webViewFragment).onBackPressed();
            return result ||super.onKeyDown(keyCode, event);
        }
        return super.onKeyDown(keyCode,event);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (EmasHybrid.getInstance().isUseUc()) {
            ((WVUCWebViewFragment) webViewFragment).onActivityResult(requestCode, resultCode, data);
        } else {
            ((WVWebViewFragment) webViewFragment).onActivityResult(requestCode, resultCode, data);
        }
    }
    @Override
    protected void onPause() {
        if (EmasHybrid.getInstance().isUseUc()) {
            ((WVUCWebViewFragment) webViewFragment).onPause();
        } else {
            ((WVWebViewFragment) webViewFragment).onPause();
        }
        super.onPause();
    }
    @Override
    protected void onResume() {
        if (EmasHybrid.getInstance().isUseUc()) {
            ((WVUCWebViewFragment) webViewFragment).onResume();
        } else {
            ((WVWebViewFragment) webViewFragment).onResume();
        }
        super.onResume();
    }
    
    @Override
    protected void onDestroy() {
        if (EmasHybrid.getInstance().isUseUc()) {
            ((WVUCWebViewFragment) webViewFragment).onDestroy();
        } else {
            ((WVWebViewFragment) webViewFragment).onDestroy();
        }
        super.onDestroy();
    }

Integrate the grayscale SDK

Add the dependency to the app/build.gradle file.

implementation "com.alibaba.mtl:dynamicconfigadapter:1.1.0-open"

Standard event mechanism

A standard communication interface allows Native and H5 to exchange events. This enables communication based on a unified event model across various scenarios.

  • Send events from Native to H5

    EMAS Hybrid provides the WVStandardEventCenter class for sending events from Native to H5:

    The webView parameter is the target WebView. The eventName parameter is the name of the event string. The eventData parameter is the event data. For iOS, this parameter is an NSDictionary *. For Android, it is a string in JSON object format.

    // Send an event to a specific WebView.
    WVStandardEventCenter.postNotificationToJS(webView,eventName, eventData);
    // Send an event to all WebViews. Use with caution.
    WVStandardEventCenter.postNotificationToJS(eventName, eventData);

    The frontend then uses the W3C canonical form to receive the event.

    document.addEventListener('eventName', function(data) {
        // Note that the event parameter passed from Native is in the param property of data.
        alert(data.param);
    }, false);
  • Send events from H5 to Native

    EMAS Hybrid provides a JS API that allows the frontend to send events.

    var params = {
        event: 'eventName',
        param: {
            // Data to be passed by the event.
        }
    }
    
    window.WindVane.call('WVStandardEventCenter','postNotificationToNative',params, function(e) {
        alert('success');
    }, function(e) {
        alert('failure: ' + JSON.stringify(e));
    });

    Alternatively, use the lib-emas call method.

    emas.WVStandardEventCenter.postNotificationToNative({...})

    If the native side needs to receive events, you must register a WVEventListener listener.

    // First, you need to implement the listener yourself.
    public class JsEventListener implementsWVEventListener {
    
        @Override
        public WVEventResult onEvent(int id, WVEventContext ctx, Object... obj) {
            // All events are dispatched here. WVEventId.H5TONATIVE_EVENT indicates an event sent from H5.
            if (id == WVEventId.H5TONATIVE_EVENT) {
                if (obj[0] instanceof String) {
                    String params = (String)obj[0];
                    // Here, params is a JSON string that contains event and param. You need to deserialize it yourself.
                }
            }
            return null;
        }
    }
    
    // Then, register the listener.
    WVEventService.getInstance().addEventListener(new JsEventListener());