15 Replies Latest reply on Oct 23, 2016 10:26 AM by scon2016

    Battery status plugin doesn't work

    scon2016 Level 1

      Dear users,

       

      I'm trying the battery status plugin cordova-plugin-battery-status but it doesn't work on my device.

       

      This is the code I have written in my application:

       

      function vedibatt(z) {

      document.getElementById('rispbatt').innerHTML = "Livello: " + z.level + " - Attaccato: " + z.isPlugged;

      }

      document.addEventListener("batterystatus", vedibatt, false);

       

      When I try to plug and unplug the power cable on my device, it doesn't fire the event, also when the battery changes its percentage.

       

      My device is android, on phonegap developer app.

       

       

      How can I fix this issue?

       

       

       

      Thanks

        • 1. Re: Battery status plugin doesn't work
          Chris W. Griffith Adobe Community Professional

          With all plugins, you need to make sure you create the reference to them after the device ready event. The document ready event typically fires before the device ready event.

           

          Plus double check that plugin is included in the PhoneGap Developer App suite. I think it is, but since you can not reference plugins not included, it is worth checking.

           

          Chris

          • 2. Re: Battery status plugin doesn't work
            kerrishotts Adobe Community Professional

            Read the docs, specifically https://www.npmjs.com/package/cordova-plugin-battery-status#example .

             

            The docs use `window.addEventListener`, NOT `document.addEventListener`. Definitely will make a difference.

             

            Chris W. Griffith:

             

            I just checked, and cordova-plugin-battery-status is included in the PhoneGap developer app.

            1 person found this helpful
            • 3. Re: Battery status plugin doesn't work
              scon2016 Level 1

              I know I must call these API after device ready event.

               

              In fact, the code of index.html is this:

               

              <html>

               

               

              <head>

              <title>mmm</title>

                  <meta charset="utf-8" />

                  <meta name="format-detection" content="telephone=no" />

                  <meta name="msapplication-tap-highlight" content="no" />

                  <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />

                  <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'; style-src 'self' 'unsafe-inline'; media-src *" />

               

               

              <link rel="stylesheet" type="text/css" href="css/grafica.css" />

              <script type="text/javascript" src="js/miecose.js"></script>

              <script type="text/javascript" src="js/conn-batt.js"></script>

              </head>

               

               

               

               

              <body onload="setInterval('animabarra()', 700)">

               

              etc...

               

               

                  <script type="text/javascript" src="cordova.js"></script>

                  <script type="text/javascript" src="js/index.js"></script>

                  <script type="text/javascript">

                      app.initialize();

                  </script>

              </body>

              </html>

               

              ---------------------------------

              The code of js/miecose.js is this:

               

              var apertura = null;

               

               

              function animabarra() {

                  var barra = document.getElementById('intestazione');

                  if(barra.style.backgroundColor == 'green') {

                      barra.style.backgroundColor = 'blue';

                  } else {

                      barra.style.backgroundColor = 'green';

                  }

              }

               

              function pronto() {

              document.addEventListener("batterystatus", vedibatt, false);

              }

               

              ---------------------------------

              The code of js/conn-batt.js is this:

               

              function vediconn() {

                  var codicestato = navigator.connection.type;

                  var stati = {};

                  stati[Connection.UNKNOWN]  = 'Sconosciuta';

                  stati[Connection.ETHERNET] = 'Ethernet';

                  stati[Connection.WIFI]     = 'Wi-Fi';

                  stati[Connection.CELL_2G]  = '2G mobile';

                  stati[Connection.CELL_3G]  = '3G mobile';

                  stati[Connection.CELL_4G]  = '4G mobile';

                  stati[Connection.CELL]     = 'Generica mobile';

                  stati[Connection.NONE]     = 'Nessuna';

              document.getElementById('rispconn').innerHTML = 'Tipo connessione: ' + stati[codicestato];

              }

               

              function vedibatt(z) {

              document.getElementById('rispbatt').innerHTML = "Livello: " + z.level + " - Attaccato: " + z.isPlugged;

              }

               

              document.addEventListener("online", vediconn, false);

              document.addEventListener("offline", vediconn, false);

               

               

              ---------------------------------

              The code of js/index.js is this:

               

              var app = {

                  // Application Constructor

                  initialize: function() {

                      this.bindEvents();

                  },

                  // Bind Event Listeners

                  //

                  // Bind any events that are required on startup. Common events are:

                  // 'load', 'deviceready', 'offline', and 'online'.

                  bindEvents: function() {

                      document.addEventListener('deviceready', this.onDeviceReady, false);

                  },

                  // deviceready Event Handler

                  //

                  // The scope of 'this' is the event. In order to call the 'receivedEvent'

                  // function, we must explicitly call 'app.receivedEvent(...);'

                  onDeviceReady: function() {

                      app.receivedEvent('deviceready');

                  },

                  // Update DOM on a Received Event

                  receivedEvent: function(id) {

                      var parentElement = document.getElementById(id);

                      var listeningElement = parentElement.querySelector('.listening');

                      var receivedElement = parentElement.querySelector('.received');

               

               

                pronto();

               

                      listeningElement.setAttribute('style', 'display:none;');

                      receivedElement.setAttribute('style', 'display:block;');

               

               

                      console.log('Received Event: ' + id);

                  }

              };

               

              --------------------

               

              I have added the connection type plugin not after the device ready event, and it works.

               

              This is my code, to be noted the pronto() function, called in device ready event.

               

              Where did I mistake the code?

               

               

               

              Thanks

              • 4. Re: Battery status plugin doesn't work
                kerrishotts Adobe Community Professional

                Repeating what I said earlier regarding the battery plugin:

                 

                The docs use `window.addEventListener`, NOT `document.addEventListener`. Definitely will make a difference.

                • 5. Re: Battery status plugin doesn't work
                  scon2016 Level 1

                  I tried to change "document" with "window", but it's the same. It doesn't work.

                   

                  How can I do to fix this issue?

                   

                   

                  Thanks

                  • 6. Re: Battery status plugin doesn't work
                    kerrishotts Adobe Community Professional

                    What version of the PhoneGap Developer app are you using? If it's not the most recent version, try updating and see if the issue goes away.

                     

                    Without seeing debugging output, it's difficult to help further. Normally I'd say connect Chrome and debug remotely, but the PGDev app is going to block that.

                     

                    You might try adding the a global error handler as described here:  GlobalEventHandlers.onerror - Web APIs | MDN

                    • 7. Re: Battery status plugin doesn't work
                      scon2016 Level 1

                      I use the version 6.3.3 of phonegap cli.

                       

                      Actually, the plugin works on browser (chrome), telling me the level at 100% and the plugged at true.

                       

                      I want to know why the plugin doesn't work on my phone with PGDev.

                       

                       

                       

                      Thanks

                      • 8. Re: Battery status plugin doesn't work
                        kerrishotts Adobe Community Professional

                        6.3.3 cli version doesn't tell me anything about the version of the PG Dev app you're using. Make sure you're using the most recent version of the app as well.

                         

                        Did you add a global error handler as I suggested in the last post? If so, did it generate any alerts?

                        • 9. Re: Battery status plugin doesn't work
                          scon2016 Level 1

                          These are the versions:

                          • phonegap cli: 6.3.3
                          • pg dev on my android phone: 1.7.2
                          • pg dev on my friend's ios tablet (ipad): 1.7.2

                           

                          These are the results:

                          • on browser (chrome): level always 100%, plugged always true
                          • on my phone: it works correctly
                          • on ipad: it doesn't work

                           

                          I have also a tablet with android, but I didn't test yet.

                           

                          I have run these commands in the project folder on ubuntu server (where there is pg cli):

                          phonegap platform add ios

                          phonegap platform add wp8

                          phonegap platform add android

                          phonegap plugin add cordova-plugin-battery-status

                           

                          After, this is the result when I run the command "phonegap platform list":

                          Installed platforms:

                            android 5.1.1

                            browser 4.1.0

                            ios 4.1.1

                            wp8 (deprecated)

                          Available platforms:

                            amazon-fireos ~3.6.3 (deprecated)

                            blackberry10 ~3.8.0

                            firefoxos ~3.6.3

                            ubuntu ~4.3.3

                            webos ~3.7.0

                           

                          I want to know how I can fix the issue on iOS, after I'll test the app on my android tablet.

                           

                           

                          Thanks

                          • 10. Re: Battery status plugin doesn't work
                            kerrishotts Adobe Community Professional

                            I can confirm that the battery status plugin does indeed work with the PhoneGap Developer app. I just tested it with a simple snippet, and it worked fine.

                             

                            Keep the following in mind:

                            • It may not return immediately; it only fires when the battery level drops by at least 1% or if the device is plugged in or unplugged.
                            • See the docs for Android quirks -- apparently this function is greedy and will increase battery drain (cordova-plugin-battery-status ). You might want to use `batterylow` or `batterycritical` events instead.

                             

                            My code: Battery Status example for phonegap forum post · GitHub

                             

                            (Note: I only supplied index.js here; everything's based off of the PhoneGap Hello World template you get when you create an app using the PhoneGap CLI.)

                            • 11. Re: Battery status plugin doesn't work
                              scon2016 Level 1

                              For the casting out nines, I have tested also on my android tablet, and I can say that the app works correctly on android (phone and tablet).

                               

                              The problem is on ios and wp8, I have tested indeed the app on my friends' phones.

                               

                              On iOS and wp8 the event never fires, the label where I put the data is always empty.

                               

                              You can see my code in post #3 on this topic, with a little change on received event:

                              receivedEvent: function(id) {

                                pronto();

                                console.log('Received Event: ' + id);

                              }

                              The app works correctly on Android and browser, but why it doesn't work on ios and wp8?

                               

                               

                              Thanks

                              • 12. Re: Battery status plugin doesn't work
                                kerrishotts Adobe Community Professional

                                I've told you that the plugin works with the PhoneGap Developer app (v1.7.2). I've provided you with code that works. Please test that code on your devices and see what happens. Then start adding your own customizations to see what broke and why.

                                 

                                Also, since you're pointing back to the code in #3, you'll have a problem from the start: you can't use "document.addEventListener". It must be "window.addEventListener", as my code example shows. The former simply will not work at all. Furthermore, I've tested your code as provided (but you haven't provided all of it, since I had to guess at some of your HTML elements), and with the change I mention, it works just fine, as the image below proves:

                                 

                                 

                                File Oct 16, 11 22 45.png

                                 

                                You must keep in mind that you will not receive constant updates about the battery level -- you may only be notified when the plugged-in status changes, or when the the power level drops by at least 1%, and the latter can take a long time to happen (it took easily two or three minutes before I could take the above screenshot). You can't assume you'll get an initial message when your app starts, either, which may mean that that your app has no idea about battery level for several minutes.

                                 

                                If you're simply worried about what to do when the battery level goes too low, switch to the batterylow and batterycritical events. Then your app can take whatever steps it needs to take in order to reduce battery use, save state, etc.

                                1 person found this helpful
                                • 13. Re: Battery status plugin doesn't work
                                  scon2016 Level 1

                                  I tried your code, similar to mine.

                                   

                                  It's the same, it works on android, but not on ios and wp8.

                                   

                                  Why?

                                   

                                   

                                  Thanks

                                  • 14. Re: Battery status plugin doesn't work
                                    kerrishotts Adobe Community Professional

                                    How long are you waiting before deciding that the plugin is failing? You need to wait until at least 1% of your battery has drained, OR switch the device to/from plugged-in status. You will not necessarily receive a notification at app start.

                                    • 15. Re: Battery status plugin doesn't work
                                      scon2016 Level 1

                                      I try to plug and unplug the device, and I also wait at least 1% of battery has drained.

                                       

                                      In the code I added a js alert in callback function, but the alert never is called, then the event never fires.

                                       

                                      I have this problem on ios and wp8.

                                       

                                       

                                      Thanks