1. 程式人生 > >cordova + ionic前端框架 js和android ios原生(native)互動

cordova + ionic前端框架 js和android ios原生(native)互動

因為專案是大部分程式碼是js+html 寫的,現在想在js中開啟原生的頁面(Android為activity;ios是ViewController),解決android 的時候發現了兩種方法,其中一種是android和ios通用的,另一種只能在android上使用。

-、android/ios通用的

在之前先說一下cordova的工作原理,android大家都知道就是得有一個"main" Acitvity,cordova就是在mainActivity中載入一個webview然後webview載入html +js ;同理,在iOS中,在“main”ViewController中載入webview然後webview載入html +js 。

進入正題:

這個外掛是通過廣播在js和原生之間傳遞訊息,可以原生髮送廣播js接收廣播,也可以js傳送廣播原生接收廣播,那麼解決方案就出來,在js中呼叫原生的頁面可以在js中傳送廣播,在原生的main Activity(ViewController)中監

聽廣播事件,js傳送特定廣播,原生收到廣播在跳轉介面(android mainActivity跳轉其他Activity;ios mianViewController跳轉其他controller)。這樣就可以實現js跳轉原生介面了。下面上程式碼:

Javascript

  window.broadcaster.fireNativeEvent( "open.native", { item:'test data' }, function() {
    	console.log( "native fired!" );
    } );

IOS

[[NSNotificationCenter defaultCenter] addObserverForName:@"open.native"
                                                  object:nil
                                                   queue:[NSOperationQueue mainQueue]
                                              usingBlock:^(NSNotification *note) {

                                                      NSLog(@"Handled 'js to native' [%@]", note.userInfo[@"item"]);
							AddressViewController *add = [storyboard instantiateViewControllerWithIdentifier:@"AddressViewController"];
                                                      [self presentViewController:add animated:true completion:nil ];
                                                    }];

ANDROID

final BroadcastReceiver receiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
          final JSONObject data = new JSONObject( intent.getBundle().getString("userdata"));

          Log.d("js to Native","js to Native:"+data.toString()));	
	startActivity(new Intent(MainActivity.this,TargetActivity.class));
}
};

LocalBroadcastManager.getInstance(this)
            .registerReceiver(receiver, new IntentFilter("open.native"));
}

當然,處理完原生介面,可能需要返回資料給js,也可以使用,只是這個是原生髮送廣播,js接收廣播 Javascript
window.broadcaster.addEventListener( "return.js", function( e ) {
                //log: return js received! userInfo: {"data":"test"}
                console.log( "return js received! userInfo: " + JSON.stringify(e)  );
    });
IOS
[[NSNotificationCenter defaultCenter] postNotificationName:@"return.js"
                                                    object:nil
                                                  userInfo:@{ @"data":@"test"}];
Android
final Intent intent = new Intent("return.js");

Bundle b = new Bundle();
b.putString( "userdata", "{ data: 'test'}" );
intent.putExtras( b);

LocalBroadcastManager.getInstance(this).sendBroadcastSync(intent);


二、android js to native

window.plugins.webintent.startActivity({
      action: window.plugins.webintent.ACTION_VIEW,
      url: theFile.toURL(),
      type: 'application/vnd.android.package-archive'
    },
    function() {},
    function() {
      alert('Failed to open URL via Android Intent.');
      console.log("Failed to open URL via Android Intent. URL: " + theFile.fullPath)
    }
);
具體不詳細說了,點選github連線吧