core-egret.ExternalInterface

egret.ExternalInterface 使用範例


class Main extends eui.UILayer {

    protected createChildren(): void {
        super.createChildren();
        egret.lifecycle.onPause = () => egret.ticker.pause();
        egret.lifecycle.onResume = () => egret.ticker.resume();
        egret.registerImplementation('eui.IAssetAdapter', new AssetAdapter());
        egret.registerImplementation('eui.IThemeAdapter', new ThemeAdapter());
        this.runGame();
    }

    private async loadResource() {
        let loadingView = this.stage.addChild(new LoadingUI()) as LoadingUI;
        await RES.loadConfig('resource/default.res.json', 'resource/');
        await new Promise(resolve => new eui.Theme('resource/default.thm.json', this.stage).once(eui.UIEvent.COMPLETE, resolve, this));
        await RES.loadGroup('preload', 0, loadingView);
        this.stage.removeChild(loadingView);
    }

    private async runGame() {
        await this.loadResource();
        // --- Edwin 給你最乾淨的程式碼, 從這行以下開始寫喔 ---

        // egret.ExternalInterface 是與原生程式溝通的方法, 譬如你可以讓手機震動或是跳出原生對話框都做得到

        // 從 android 或 ios 回來的資訊
        egret.ExternalInterface.addCallback('sendToJS', function (message) {
            egret.log('message form native : ' + message);//message form native : message from native
        });
    
        // && 為短路與, 前面沒達成後面也不會執行
        // 送出給 andorid 的資訊
        egret.Capabilities.os == 'Android' && egret.ExternalInterface.call('sendToAndroid', 'message from js');
        // 送出給 ios 的資訊
        egret.Capabilities.os == 'iOS' && egret.ExternalInterface.call('sendToNative', 'message from js');

        //對應的 Android Java 程式:
        `
        IGameExternalInterface externalInterface = gameEngine.game_engine_get_externalInterface();
        externalInterface.run();
        externalInterface.addCallBack('sendToAndroid', new IGameExternalInterfaceCallBack(){
            public void callBack(String str){
                Log.i('externalInterface', 'message form js : ' + str);
                IGameExternalInterface externalInterface = gameEngine.game_engine_get_externalInterface();
                externalInterface.call('sendToJS', 'message from native');
            }
        });
        `;

        //對應的 iOS Objective-C 程式:
        `
        __block EgretNativeIOS* support = _native;
        [_native setExternalInterface:@"sendToNative" Callback:^(NSString* message) {
            NSString* str = @"Native get message: ";
            str = [str stringByAppendingString:message];
            NSLog(@"%@", str);
            [support callExternalInterface:@"sendToJS" Value:str];
        }];
        `;

    }

}

spacer

沒有留言:

張貼留言