NativeScript handling back button event

半腔热情 提交于 2019-11-29 07:32:18
Eddy Verbruggen

I'm using NativeScript with Angular as well and this seems to work quite nicely for me:

import { RouterExtensions } from "nativescript-angular";
import * as application from "tns-core-modules/application";
import { AndroidApplication, AndroidActivityBackPressedEventData } from "tns-core-modules/application";
import { isAndroid } from "tns-core-modules/platform";

export class HomeComponent implements OnInit {
  constructor(private router: Router) {}

  ngOnInit() {
    if (!isAndroid) {
      return;
    }
    application.android.on(AndroidApplication.activityBackPressedEvent, (data: AndroidActivityBackPressedEventData) => {
      if (this.router.isActive("/articles", false)) {
        data.cancel = true; // prevents default back button behavior
        this.logout();
      }
    });
  }
}

Note that hooking into the backPressedEvent is a global thingy so you'll need to check the page you're on and act accordingly, per the example above.

Normally you should have an android activity and declare the backpress function on that activity. Using AndroidApplication only is not enough. Try this code:

import {topmost} from "ui/frame";
import {AndroidApplication} from "application";

let activity = AndroidApplication.startActivity ||
            AndroidApplication.foregroundActivity ||
            topmost().android.currentActivity ||
            topmost().android.activity;

activity.onBackPressed = function() {
    // Your implementation
}

You can also take a look at this snippet for example

import { Component, OnInit } from "@angular/core";
import * as Toast from 'nativescript-toast';
import { Router } from "@angular/router";
import * as application from 'application';

@Component({
  moduleId: module.id,
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.css']
})
export class MainComponent {
  tries: number = 0;
  constructor(
    private router: Router
  ) {
    if (application.android) {
      application.android.on(application.AndroidApplication.activityBackPressedEvent, (args: any) => {
        if (this.router.url == '/main') {
          args.cancel = (this.tries++ > 0) ? false : true;
          if (args.cancel) Toast.makeText("Press again to exit", "long").show();
          setTimeout(() => {
            this.tries = 0;
          }, 2000);
        }
      });
    }
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!