LoginSignup
0
0

More than 5 years have passed since last update.

[*Cordova*] バッテリー状態プラグインを使ってみる

Last updated at Posted at 2015-12-05

はじめに

環境構築はできたので、プラグインで遊んでみます。
簡単そうなバッテリープラグインから

プロジェクト作成

プロジェクトを作成してプラットフォームとしてiOSを追加。
そしてバッテリー状態プラグインを追加。

$ cordova create batteryPush com.example.batteryPush -d
$ cordova platform add ios
$ cordova plugin add cordova-plugin-battery-status

コード

index.html
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
        <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">
        <link rel="stylesheet" type="text/css" href="css/index.css">
        <meta charset="utf-8">
        <title>Battery</title>
    </head>
    <body>
        <div class="app">
            <h1>Battery</h1>
        </div>
        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
    </body>
</html>
index.js
var app = {
    // コンストラクタ
    initialize: function() {
        this.bindEvents();
    },
    // devicereadyはCordovaを全部読み込んでから発火
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // バッテリーの残量が変化したら呼ばれるように設定
    onDeviceReady: function() {
        window.addEventListener("batterystatus", onBatteryStatus, false);
    },
};

app.initialize();


function onBatteryStatus(info) {
    alert("バッテリー残量:" + info.level + ", デバイスの接続:" + info.isPlugged)
}

取得できる値

キー
level バッテリー残量
isPlugged デバイスが接続されているか

イベントの種類

種類 説明
batterystatus バッテリー残業が変化した時、デバイスが接続されたまたはされなくなった時にイベントが発生。
batterycritical バッテリー残量がとても少なくなった時にイベントが発生。基準はデバイスに依存する。
batterylow バッテリー残量が少なくなった時にイベントが発生。基準はデバイスに依存する。

実行結果

バッテリー残量が変化した時にイベントが発生する。
MacにPCを接続して、Xcodeから実行しiPadで見ているのでデバイスの接続はtrueになる。
skitch.png

まとめ

アプリ起動時のバッテリー残量は取れないのでしょうか。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0