【问题标题】:Cordova batterystatus - how to get level straight away?Cordova 电池状态 - 如何立即获得水平?
【发布时间】:2014-03-31 10:29:58
【问题描述】:

我正在使用这个事件: http://cordova.apache.org/docs/en/3.0.0/cordova_events_events.md.html#batterystatus

它工作正常,当它改变或开始/结束充电时它会获取电池电量。

但是,如何在打开应用程序时立即获得电池电量?谢谢。

【问题讨论】:

    标签: ios iphone objective-c cordova batterylevel


    【解决方案1】:

    您好,您可以编写一个插件来获取当前电池电量,更多关于插件开发检查this 并在 deviceready 事件中调用此插件

    *javascript

     cordova.exec(function(status) {
    
           console.log(status); //will get current ststus
    
       }, function(error) {}, "Status",
                     "Status", ["givestatus"]);
    

    这是本机代码Objective C

    - (void)Status:(CDVInvokedUrlCommand*)command
    {
    CDVPluginResult* pluginResult = nil;
    NSString* myarg = [command.arguments objectAtIndex:0];
    
    if (myarg != nil) {
    
    [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
    UIDevice *myDevice = [UIDevice currentDevice];
    [myDevice setBatteryMonitoringEnabled:YES];
    double batLeft = (float)[myDevice batteryLevel] * 100;
    
    
    
    
    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"%.f",batLeft]];
    } else {
    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR    messageAsString:@"Arg was null"];
    }
    
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }
    

    也将新项目添加到 config.xml

    <feature name="Status">
        <param name="ios-package" value="Status" />
    </feature>
    

    【讨论】:

    • 感谢您的回复! :) 你能再帮忙一点吗,在哪里添加这些东西?我在看这里,但我不是 100% 确定该怎么做。 cordova.apache.org/docs/en/3.4.0/… 我需要在 /platforms/ios/appname/Plugins 中添加一个文件夹,对吗?然后我需要在这个文件夹中添加 status.h 和 status.m 吗?但我不确定在哪些文件中放什么。
    • 我在其中包含了一个 .js 文件:CDV = ( typeof CDV == 'undefined' ? {} : CDV ); var cordova = window.cordova || window.Cordova; cordova.exec(function(status) { console.log(status); //will get current ststus }, function(error) {}, "Status", "Status", ["givestatus"]); 我在配置文件中添加了功能参考。但是我不确定如何实现本机代码。
    • 将其中一行改成这样,现在可以了。谢谢! pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[NSString stringWithFormat:@"%.0f", batLeft]];
    猜你喜欢
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 2020-01-23
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多