简体   繁体   中英

Nativescript - Android disabling physical device back button

I am trying to disabling the physical device back in android only in some screens. Trying the below code is not working. Any idea?

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

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

    ngOnInit() {
      if (!isAndroid) {
        return;
      }
      application.android.on(AndroidApplication.activityBackPressedEvent, (data: AndroidActivityBackPressedEventData) => {

          data.cancel = true; // prevents default back button behavior

      });
    }
  }
@Override
public void onBackPressed() {
   if (!shouldAllowBack()) {
       doSomething();
   } else {
       super.onBackPressed();
   }
}

Add this code in your activity-

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
       // Your Code Here. Leave empty if you want nothing to happen on back press.

}

For more information visit this link.

Back button is controlled at Activity level, NativeScript uses one single Activity and all your pages / routes are fragments inside that.

So you don't have to call it on every page / component. Add the listener to your app component and check the router to know which page you are at and cancel the back event.

Use location and check if location consists the desired path(as mentioned in routing file) where you want to use your custom function.

import { Location } from '@angular/common';

constructor(private _location: Location ){}

if (application.android) {
            application.android.on(AndroidApplication.activityBackPressedEvent, (data: AndroidActivityBackPressedEventData) => {
                const path = this._location.path();

            console.log(`path i s--> ${path}`);
            switch (path) {
                case '/Screen 1':
                    data.cancel = true;
                    break;
                case '/Screen 2':
                    //do something else
                    break;
            });
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM