Search code examples
androidionic-frameworkandroid-intentandroid-activitycapacitor

How to change android activity by clicking a button in (ionic) webview?


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


Solution

  • 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