1

I'm developing a hybrid app using Ionic 4. Ionic just like other html5 based apps runs as a webview in MainActivity. using capacitor I've imported my app to android studio and I've created a SecondActivity. How can I go to SecondActivity by clicking a button inside first activity(MainActivity) (which is an Ioninc page and for sure an html webview).

So far i've tried different method to achieve this but no luck. I've created a cordova plugin following this tutorial: Start android activity from cordova plugin it works prefect in cordova application but I was not successful to import it into Ionic. also I've tried Capacitor and apparently accessing native code using capacitor should be very easy but unfortunately I've had no luck so far. https://capacitor.ionicframework.com/docs/plugins/android

Prags
  • 2,457
  • 2
  • 21
  • 38
Ali Haghighi
  • 143
  • 3
  • 11

2 Answers2

2

after struggling a lot! here is the answer: the plugin that I mentioned actually works cool in cordova and to bring it to ionic4 (as the clobbers of plugin is "PluginName", you have to declare and use it in your typescript)my code is as follows (home.page.ts):

import { Component } from '@angular/core';
declare var PluginName: any;
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
goToCustomActivity(){
PluginName.new_activity();
}
}

and in your home.page.html:

<ion-content>
<ion-button (click)="goToCustomActivity()">go to custom activity</ion- 
button>
</ion-content>

I hope this help someOne. and special thanks to original coder of plugin "Ijas Ahamed N" you can find instructions to write plugin here: https://www.ijasnahamed.in/2016/11/start-android-activity-from-cordova.html and here is the stackoverflow (be aware! step to create package.json is omitted in stackoverflow!) Start android activity from cordova plugin

Ali Haghighi
  • 143
  • 3
  • 11
0

You can do it by taking use of WebView.addJavaInterface. Just write a Android class in Java (to launch a the Activity you want), and inject the object into WebView context by calling WebView.addJavaInterface(). When the HTML button is clicked, you call the injected JS method to launch the Activity.

The Activity Launcher:

class MyJsInterface {
    @JavascriptInterface
    public String launchActivity() {
        // ...;
    }
 }

Inject it:

webview.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new MyJsInterface(), "AndroidInterface");
webView.loadUrl(...);

In your web page:

<button onclick="AndroidInterface.launchActivity()">Launche Activity</button>
Wei WANG
  • 1,748
  • 19
  • 23
  • thanks for your reply. this approach should work. but I was not successful to use it in Ionic and typescript! can you share instructions to use it in Ionic? – Ali Haghighi Jan 04 '19 at 05:09