简体   繁体   中英

Ionic call function when app is loaded

I would like to check every time the app is loaded if the device has an internet connection. This function has nothing to do with any of my Ionic Views/pages. I don't need to make this check on a specific page. I need it to run every time the app is actually loaded on the screen.

For example, if I hit the app icon from my home screen and load it, the check function should run. Then I decide to open my emails to check on something. At the end, I just re-open my app which is running in the background (Not terminated), the app should check again for an internet connection.

Im not asking how I'm I gonna write the function to check, but where shall I place that segment of code to run only when the app is loaded regardless the view/page of the app.

For the first check, when you start your app, add your check code inside $ionicPlatform.ready method (app.js file).

For the check when you return to app from other activity, create inside .run method (app.js file) the $ionicPlatform.on method.

Something like this (at app.js file):

angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])

.run(function($ionicPlatform) {

  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)

    // PUT YOUR CHECK CODE HERE, TRIGGERED WHEN THE APP RUN FOR THE FIRST TIME

    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);

    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });

  $ionicPlatform.on('resume', function() {
   // PUT YOUR CHECK CODE HERE TOO. TRIGGERED WHEN YOU RETURN TO APP FROM OTHER ACTIVITY.
  });
})

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