2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > api接口优化_使用电池状态API优化开发

api接口优化_使用电池状态API优化开发

时间:2018-08-26 23:39:20

相关推荐

api接口优化_使用电池状态API优化开发

api接口优化

Imagine if you could program your app to adapt to the end user's device — such as turning off certain processes if the user's device has a low battery status. Well, you can.

试想一下,如果您可以对应用程序进行编程以使其适应最终用户的设备,例如在用户设备的电池电量不足时关闭某些进程。 好吧,可以。

TheDevice APIs Working Groupis a series of specifications drafted to provide developers with access to additional information about a user's device, so that a more tailored experience can be created. This working group contains several evolving standards, including theBattery APIwhich we will take a look at in this tutorial.

Device APIs Working Group是一系列规范,旨在为开发人员提供访问有关用户设备的其他信息的权限,以便可以创建更加定制的体验。 这个工作组包含一些不断发展的标准,包括Battery API,我们将在本教程中对其进行介绍。

The Battery API is now supported on several desktop and mobile browsers, so now is a good time to look at the Battery API and see what it is, where it's supported, and why you should consider leveraging it in your upcoming projects.

现在,一些台式机和移动浏览器都支持Battery API,因此现在是查看Battery API的好时机,了解它的含义,支持的位置以及为什么要考虑在即将来临的项目中使用它。

电池API:简介 (The Battery API: A Brief Introduction)

The Battery Status API (Battery API) is exactly what it sounds like: an interface that lets developers access information about the current user's battery.

电池状态API(Battery API)的确切含义是:开发人员可以通过该接口访问有关当前用户电池的信息。

It's a JavaScript-level API that enables developers to hook into various events and properties of the user's device. For example, if we have access to the API, we can get the current battery percentage and, based on that value, set good default settings. For example, if the user's device is in a low battery state, we can remove all background tasks and make them manual only.

它是JavaScript级别的API,使开发人员能够了解用户设备的各种事件和属性。 例如,如果我们可以访问API,则可以获取当前的电池电量百分比,并根据该值设置良好的默认设置。 例如,如果用户的设备处于电池电量不足的状态,则我们可以删除所有后台任务并将其设为手动。

Since early , this API has been continually under development, moving back and forth from working draft to candidate recommendation status at the W3C. Over this period, several browsers have adopted support — though some more than others.

自初以来,该API一直在不断开发中,从工作草案到W3C的候选推荐状态来回移动。 在此期间,一些浏览器采用了支持-尽管其中一些比其他浏览器更多。

API如何帮助我们? (How Can the API Help Us?)

Since the specification is not yet finalized, we can't count on developing websites or web apps that fully depend on the Battery API. What wecando, however, is provide additional functionality, or a more customized experience, if the current browser supports the API — i.e., using it in a progressive enhancement style.

由于规范尚未最终确定,因此我们不能指望完全依赖Battery API开发网站或Web应用程序。 但是,如果当前的浏览器支持API,那么我们可以做的就是提供其他功能,或者提供更多的自定义体验,即以渐进增强样式使用它。

我们可以访问哪些信息? (What Information Can We Access?)

Since we can access the user's battery state, we can determine their current battery level and whether the device is charging or discharging. In addition, we can sometimes get the device's approximate charge or discharge time (the time until the device is either charged or dead).

由于我们可以访问用户的电池状态,因此我们可以确定他们当前的电池电量以及设备是否正在充电或放电。 另外,有时我们可以获得设备的大概充电或放电时间(直到设备被充电或耗尽的时间)。

With this information, we can start to change the user experience to help the user.

有了这些信息,我们就可以开始改变用户体验以帮助用户。

无论如何我们可以使用此信息吗? (What Could We Use This Information for Anyway?)

Even though battery optimization generally isn't in the forefront of a developer's mind, it's a factor that should be considered, especially with everything moving towards mobiles.

即使电池优化通常不在开发人员的视野中,但仍应考虑这一因素,尤其是在一切朝着移动技术发展的过程中。

Websites offer a range of useful but expensive operations that could be adjusted so that your users spend less of their battery on your website. (No one likes a website or web app that demolishes your battery.)

网站提供了一系列有用但昂贵的操作,可以对其进行调整,以使用户减少在网站上的电池消耗。 (没有人喜欢破坏电池的网站或网络应用。)

Let's look at some of the ways we could save some battery power:

让我们看一些节省电池电量的方法:

We couldcustomize the Geolocation elementsso that they have a lower accuracy and don't request usage of the inbuilt GPS by default. We could have two options displayed to the user, one to request it normally and another with high accuracy.

我们可以自定义Geolocation元素,以使其准确性较低,并且默认情况下不要求使用内置GPS。 我们可以向用户显示两个选项,一个可以正常请求,另一个可以高精度。

We couldset video streams or playback to lower qualitylevels by default, making data transfers are quicker (and thus requiring less work of the device). An option to download the high quality stream could be provided.

默认情况下,我们可以将视频流或播放设置为较低的质量级别,从而使数据传输更快(从而减少设备工作量)。 可以提供下载高质量流的选项。

We couldreduce complex CSS animationsor interface elements and provide a more basic interface.

我们可以减少复杂CSS动画或界面元素,并提供更基本的界面。

We could use the battery level to determine thedefault interval in which background tasks are run— such as Ajax and Web Workers. We could use the state to determine how frequently our tasks should be called, in order to minimize network usage. Providing an option or setting so users could set what they want is also a good idea.

我们可以使用电池电量来确定运行后台任务默认间隔,例如Ajax和Web Workers。 我们可以使用状态来确定应该多久调用一次任务,以最大程度地减少网络使用量。 提供一个选项或设置以便用户可以设置他们想要的内容也是一个好主意。

Overall, the idea is that we can use the Battery API to provide some good defaults that save battery power, while providing more options for interacting with the website.

总体而言,我们的想法是,我们可以使用Battery API提供一些良好的默认设置,以节省电池电量,同时提供更多与网站交互的选项。

浏览器支持 (Browser Support)

Since the Battery API is not finalized, it doesn't have universal support across all browsers yet.

由于Battery API尚未最终确定,因此尚未在所有浏览器中提供通用支持。

On a positive note, a good number of browsers now support it(as of November ), so now's the perfect time to get up and running with this API.

令人欣慰的是,现在(截至11月),许多浏览器都支持它,因此,现在正是使用此API并开始运行的最佳时机。

移动设备 (Mobile Devices)

Mobile browsers are where support is most important. FireFox mobile has had the longest support, ranging back to early days of version 18 (January ). Opera followed suit in version 25 (October ) and finally Chrome in version 40 (April ).

移动浏览器是支持最重要的地方。 FireFox移动版的支持时间最长,可追溯到版本18的早期(1月)。 Opera在25版(10月)中效仿,最后在Chrome 40版(4月)中效仿。

Firefox 18+ Firefox 18+ Opera Mobile 25+ Opera Mobile 25+ Chrome 42 +Chrome42 +

台式机 (Desktops)

While the Battery API makes the most sense for mobile devices (and their browsers), it's still important to have support for the API across the traditional browsers, as they're often used on laptops and other portable devices (where the API is useful).

虽然Battery API对移动设备(及其浏览器)最有意义,但在传统浏览器中对API的支持仍然很重要,因为它们通常用于笔记本电脑和其他便携式设备(在该API有用处) 。

Firefox, again, has the longest history of support, back to version 18 (launched in ). Chrome added support in version 39 (October ), closely followed by Opera with its 25th version (October )

Firefox的支持历史最长,可以追溯到18版(于推出)。 Chrome在第39版(10月)中增加了支持,紧随其后的Opera在其第25版中(10月)

Firefox 18+Firefox 18+ Chrome 39+Chrome39+ Opera 25+歌剧25+

一个实际示例:减少后台API调用 (A Practical Example: Reducing Background API Calls)

You can go directly to the full code for this demo if you'd rather skip this section.

如果您想跳过本节,可以直接转到此演示的完整代码 。

One good way of using the API is by detecting the user's current battery state and setting the default intervals for data- and processor-intensive tasks.

使用API​​的一种好方法是检测用户当前的电池状态,并设置数据和处理器密集型任务的默认间隔。

Websites will often request new information dynamically, using Ajax or other techniques to pull or push data while users go about their normal website interactions.

当用户进行正常的网站交互时,网站通常会使用Ajax或其他技术动态地请求新信息,以提取或推送数据。

These events are often started by users, such as when they want to load additional content. Other times, they happen in the background without any user input.

这些事件通常由用户启动,例如当他们想要加载其他内容时。 其他时间,它们在没有任何用户输入的情况下在后台发生。

By looking at the battery state, we can choose the best default experience for the user.

通过查看电池状态,我们可以为用户选择最佳的默认体验。

Click here to view this example live. The example works best on devices and browsers that support for the API.

单击此处以实时查看此示例 。 该示例在支持API的设备和浏览器上效果最佳。

示例概述 (Example Overview)

The website will display random images from The Cat API and show them to our users. Once the user loads the page, it will continually pull images from the API and replace our existing images.

该网站将显示The Cat API中的随机图像并将其显示给我们的用户。 用户加载页面后,它将不断从API中提取图像并替换我们现有的图像。

Here's what we'll be doing:

这是我们要做的:

Creating a new PHP class that will handle the interactions with the CatAPI.

创建一个新PHP类,以处理与CatAPI的交互。

Extending a new class that will be used to get a single image from the CatAPI and return it back to our browser for processing. (This process will be executed via Ajax.)

扩展一个新类,该类将用于从CatAPI获取单个图像并将其返回给我们的浏览器进行处理。 (此过程将通过Ajax执行。)

Building our basic landing page. The page will initially get a few images from the CatAPI and display useful information about the battery state and battery API.

构建我们的基本目标网页。 该页面最初将从CatAPI中获取一些图像,并显示有关电池状态和电池API的有用信息。

Creating the JavaScript interactivity with thebattery status API. It's here that the majority of the fun stuff will be happening — as we check for API support and how we can interact with it.

使用battery status API创建JavaScript交互性。 在这里,大多数有趣的事情都会在这里发生-我们检查API支持以及如何与之交互。

If you're new to cURL, it's probably best to read up on it first.

如果您不熟悉cURL,最好先阅读一下 。

If you want to get straight to the code, feel free to fork a copy from the SitePoint GitHub account.

如果您想直接使用代码,请随时从SitePoint GitHub帐户派生一个副本 。

CatAPI:快速概述 (The CatAPI: a Quick Overview)

The Cat API lets us pull random images of cats, which will work perfectly as all we need is a basic random image passed back to us every X seconds depending on the current battery state.

使用Cat API ,我们可以提取猫的随机图像,因为我们需要的只是根据当前电池状态每隔X秒传回给我们的基本随机图像,因此它们可以完美运行。

We'll be using the get method of the API to collect our images. This method outlines several options that you can use to modify your request. However, for our needs, we'll keep it pretty simple:

我们将使用API的get方法来收集图像。 此方法概述了可用于修改请求的几个选项。 但是,出于我们的需要,我们将使其保持简单 :

/api/images/get

Note:Normally, you wouldn't need to use PHP to connect with your API; you'd just build your URL and connect to the API with JavaScript. However, the CatAPI currently doesn't support JSON, so we may as well just use cURL on the server to get our information.

注意:通常,您不需要使用PHP来连接API。 您只需构建URL并使用JavaScript连接到API。 但是,CatAPI当前不支持JSON,因此我们也可以只在服务器上使用cURL来获取我们的信息。

电池API类别 (Battery API Class)

Our main interaction with the CatAPI will be via thebattery_api_class.phpfile.

我们与CatAPI的主要交互将通过battery_api_class.php文件进行。

Inside the class we define several methods, which we'll use to interact with the CatAPI and display useful information about the Battery Status API. Let's quickly run through what these do.

在类中,我们定义了几种方法,这些方法将用于与CatAPI交互并显示有关Battery Status API的有用信息。 让我们快速浏览一下这些操作。

get_image_items($ method,$ arguments = array()) (get_image_items($method, $arguments = array()))

This function initializes a cURL session with the CatAPI.

此函数使用CatAPI初始化cURL会话。

It takes in the method used for the API along with an array of arguments.

它接受用于API的方法以及参数数组。

For our example, the method will be/api/images/get?, and our array will have our options (such as choosing the size of the image returned, the return format, the type of image etc.).

对于我们的示例,方法将是/api/images/get?,我们的数组将具有我们的选项(例如选择返回图像的大小,返回格式,图像类型等)。

We now start our cURL request withcurl_init(), and grab its content withcurl_exec. We close the connection withcurl_closeonce we're done.

现在,我们使用curl_init()启动cURL请求,并使用curl_exec获取其内容。 完成后,我们使用curl_close关闭连接。

We check the error status and error code numbers withcurl_errorandcurl_errno. If we have no error messages, and we have content, we start processing the returned information. For our examples, we'll be getting our data back in XML, so we create a newSimpleXMLElementfrom our cURL content and then loop through each of the records.

我们使用curl_errorcurl_errno检查错误状态和错误代码编号。 如果没有错误消息,并且有内容,我们将开始处理返回的信息。 对于我们的示例,我们将以XML格式返回数据,因此我们将从cURL内容中创建一个新的SimpleXMLElement,然后遍历每条记录。

Once we have the information we need, we return the images, orfalse, depending on how our cURL request goes.

获得所需信息后,我们将根据cURL请求的处理方式返回图像或false

display_image_items($ images_array) (display_image_items($images_array))

This function displays all the saved information we collected in theget_image_items()function. If we have images, we display a manual load button to fetch images. (This will be displayed when we're on critical battery and run no background tasks.)

此函数显示我们在get_image_items()函数中收集的所有已保存信息。 如果有图像,则显示一个手动加载按钮以获取图像。 (当我们的电池电量严重不足并且不执行任何后台任务时,将显示此内容。)

We loop through the records and print the markup for each image. We're using several inner containers, as we're taking advantage of theobject-fitandobject-positionCSS properties to give us perfectly square, fully responsive image elements.

我们遍历记录并为每个图像打印标记。 我们使用了多个内部容器,因为我们利用了object-fitobject-positionCSS属性来为我们提供完美方形,完全响应的图像元素。

display_battery_example_description() (display_battery_example_description())

This function displays the introductory text for users, telling them about this web page and how it works. Fairly standard.

此功能为用户显示介绍性文本,向他们介绍此网页及其工作方式。 相当标准。

display_battery_information_summary() (display_battery_information_summary())

This function displays all the summary information about the device's support for the Battery API. It indicates if the device supports the API, the current charge percentage, if the device is charging, and, most importantly, the current interval in which the next call to the CatAPI will be made.

此功能显示有关设备对Battery API支持的所有摘要信息。 它指示设备是否支持API,当前充电百分比,设备是否正在充电以及最重要的是,下次呼叫CatAPI的当前时间间隔。

In addition, we also define the simulation buttons that can be used to trigger the other battery states (so you can simulate having a low battery state).

此外,我们还定义了可用于触发其他电池状态的模拟按钮(因此您可以模拟电池电量低的状态)。

Battery API子类 (The Battery API Child Class)

Thebattery_api_single.phpclass will be called periodically by our JavaScript, based on the current battery level of the device. A higher battery level will result in more frequent calls to this file.

根据设备当前的电池电量,我们JavaScript会定期调用battery_api_single.php类。 较高的电池电量将导致对该文件的调用更加频繁。

The purpose of this class is to extend the parentbattery_apiclass and use itsconstructorto fetch an image from the CatAPI. We start by loading our parent class and extending a new class based off it.

该类的目的是扩展父battery_api类,并使用其constructor从CatAPI中获取图像。 我们首先加载父类,然后基于它扩展一个新类。

We start by defining an array of our options inside the$argumentsvariable. We set the data type to be XML and to pull a single small JPG from the CatAPI. We define the$methodto be thegetmethod of/api/images/get?

我们首先在$arguments变量中定义一个选项数组。 我们将数据类型设置为XML,并从CatAPI中提取单个小的JPG。 我们将$method定义为/api/images/get?get方法/api/images/get?

We then call theget_image_items()function, passing in our$methodand$arguments. We'll be returned an array of image information. We then use thejson_encodefunction to pass an encoded string of information back to our website.

然后,我们调用get_image_items()函数,传入$method$arguments。 我们将返回图像信息数组。 然后,我们使用json_encode函数将经过编码的信息字符串传递回我们的网站。

网站登陆页面 (Website Landing Page)

index.phpis the landing page we'll get to when we visit our example. The file itself is basic and acts as a wrapper for our different functions, so that we can display our example descriptions, information summary and grid of initial images from the CatAPI.

index.php是访问我们的示例时将到达的登录页面。 该文件本身是基本文件,并充当我们不同功能的包装,因此我们可以显示示例说明,信息摘要以及CatAPI中的初始图像网格。

We load thebattery_api_class.phpfile and then call the CatAPI to get our initial series of eight images to display on page load.

我们加载battery_api_class.php文件,然后调用CatAPI以获取我们的八个图像的初始系列,以在页面加载时显示。

JavaScript与电池状态API的交互性 (JavaScript Interactivity with the Battery Status API)

Arguably the most important part of the example is the interactivity with the Battery Status API and the various other functions that help piece everything together.

可以说,该示例中最重要的部分是与Battery Status API和有助于将所有内容组合在一起的各种其他功能的交互性。

Thebattery_api_scripts.jsfile contains several interconnected functions that provide connectivity with the Battery Status API and set up/update the various areas in our example.

battery_api_scripts.js文件包含几个互连的函数,这些函数提供与Battery Status API的连接并在我们的示例中设置/更新了各个区域。

全局变量 (Global Variables)

At the very top of the file, we create all the variables we'll need. These variables will end up containing strings, booleans, objects etc. Here's a quick breakdown:

在文件的最顶部,我们创建了所有需要的变量。 这些变量最终将包含字符串,布尔值,对象等。以下是快速细分:

We use these extensively throughout the example, and most are used to trigger other actions.

在整个示例中,我们广泛使用了这些功能,并且大多数用于触发其他操作。

检测对Battery API的支持 (Detecting Support for the Battery API)

We execute thebattery_start()function as soon as the page is ready. Its purpose is to test for Battery API support. Since the API is changing, we need to check two different ways to see if we have support.

页面准备就绪后,我们将立即执行battery_start()函数。 其目的是测试电池API支持。 由于API不断变化,因此我们需要检查两种不同的方式以查看是否有支持。

The oldernavigator.batteryvalue exists in older browsers and will directly return thebatteryMangerobject if we have it. If we have support, we set thebatteryvariable totrueand start executing our functions.

较旧的navigator.battery值存在于较旧的浏览器中,如果有的话,它将直接返回batteryManger对象。 如果有支持,可以将battery变量设置为true并开始执行我们的功能。

The newernavigator.getBatteryfunction exists only in newer browsers, and instead of directly giving you thebatteryManagerobject, it executes apromiseto give you the object as soon as it can. Once we get back this promised value, we set thebatteryvariable totrueand start executing our functions.

较新的navigator.getBattery函数仅在较新的浏览器中存在,而不是直接为您提供batteryManager对象,而是执行一个promise,以尽快为您提供该对象。 取回此承诺值后,我们将battery变量设置为true并开始执行我们的功能。

If there's no support, we set thebatteryvariable tofalseand continue with our setup actions.

如果没有支持,我们将battery变量设置为false并继续我们的设置操作。

设置/更新电池状态信息 (Setting/Updating the Battery Status Information)

Theupdate_status_information()function is called next in our flow. It calls a whole heap of other helper functions that will set our variables based on the support of the API.

在我们的流程中,下一步将调用update_status_information()函数。 它调用其他帮助函数的整个堆,这些函数将基于API的支持来设置变量。

Since there are many elements to track, we occasionally call this function to update values — such as when we move up a percentage in charging, or when we toggle our simulated battery states.

由于要跟踪的元素很多,因此我们有时会调用此函数来更新值-例如,当我们提高充电百分比或切换模拟电池状态时。

get_battery_support(): checks ourbatteryvariable to see if we have a Battery Manager object (we will if we have support for the API). If we have support we set this to true, else we set it to false.

get_battery_support():检查我们的battery变量以查看是否有电池管理器对象(如果我们有对API的支持,我们将这样做)。 如果有支持,则将其设置为true,否则将其设置为false。

get_battery_level(): checks to to see if we have ourbatteryvariable. if we do it uses thelevelproperty of the battery manager object to set ourbattery_levelvariable. (The level value represents a value between 0 and 1, so we multiply the value by 100 to get our percentage.)

get_battery_level():检查是否有battery变量。 如果执行此操作,则使用电池管理器对象的level属性设置我们的battery_level变量。 (级别值表示介于0到1之间的值,因此我们将其乘以100得到百分比。)

get_battery_status(): this determines whatstatestring the device will be set to. This state is saved in ourbattery_statusvariable, and is used in other areas of the website (such as our main Ajax function). If we have access to the API, we check against the currentbattery_levelto determine if the device will be in ahigh,medium,loworcriticalstate. If we don't have access to the API we set this tono_support.

get_battery_status():这确定设备将设置为哪个state字符串。 此状态保存在我们的battery_status变量中,并在网站的其他区域(例如我们的主要Ajax函数)中使用。 如果可以访问该API,则会根据当前的battery_level进行检查,以确定该设备将处于highmediumlow还是critical状态。 如果我们无权访问API,则将其设置为no_support

get_battery_charging(): if we support the API, we look at thechargingproperty. This property lets us know if the device is charging or not. We set the value ofbattery_is_chargingaccordingly.

get_battery_charging():如果我们支持API,我们将查看charging属性。 此属性可让我们知道设备是否正在充电。 我们相应地设置battery_is_charging的值。

set_background_colour(): checks the current status in thebattery_statusvariable and sets a class to theHTMLelement. This is mainly used for presentation, and each state sets a different color on the background.

set_background_colour():检查battery_status变量中的当前状态,并将类设置为HTML元素。 这主要用于演示,每个状态在背景上设置不同的颜色。

get_api_action_interval(): this function is where we determine how often we'll be calling our Ajax function to pull a new image from the CatAPI. We check thebattery_supportvariable, and if we have support, we then compare ourbattery_statusvariable against our ranges. Depending on the battery status, we'll set ourapi_action_interval_timevariable either to3000,5000,8000orfalse. If we have no support for the API, we set it to a default value of3000.

get_api_action_interval():此函数是我们确定调用Ajax函数以从CatAPI中提取新图像的频率的位置。 我们检查battery_support变量,如果有支持,则将我们的battery_status变量与我们的范围进行比较。 根据电池状态,我们将设置我们api_action_interval_time任一变量300050008000false。 如果我们不支持该API,则将其设置为默认值3000

get_api_counter_interval(): this is a helper function used to determine, in milliseconds, how quickly we will update our visual counter (the element that says we have X seconds until our next Ajax call). We set theapi_action_counter_timevariable to 100 (meaning it will update 10 times a second).

get_api_counter_interval():这是一个辅助函数,用于以毫秒为单位确定更新视觉计数器的速度(该元素表示在下一次Ajax调用之前,我们有X秒)。 我们将api_action_counter_time变量设置为100(这意味着它将每秒更新10次)。

可视显示电池信息 (Displaying Battery Information Visually)

Thedisplay_status_information()function is what we call when we need to display or update the battery information to the user. We collect our variables — such as thebattery_level,battery_supportand so on — and then update our information. This function is often called when various battery events happen (such as when our battery level changes).

当我们需要向用户显示或更新电池信息时,将调用display_status_information()函数。 我们收集变量(例如battery_levelbattery_support等),然后更新我们的信息。 当发生各种电池事件时(例如,当我们的电池电量发生变化时),通常会调用此函数。

If we have support for the Battery API, we also display our buttons to simulate the battery state (so you can see the update interval change to different values).

如果我们支持Battery API,我们还将显示按钮以模拟电池状态(因此您可以看到更新间隔更改为不同的值)。

处理电池API事件 (Handling Battery API Events)

If we have support for the Battery API, we also want to hook onto the various battery events so that we can react when things change. Thebattery_event_handlers()function is called and looks for two specific events.

如果我们有对Battery API的支持,我们还希望了解各种电池事件,以便在事情发生变化时能够做出React。 调用battery_event_handlers()函数,并查找两个特定事件。

ThelevelchangeEvent: this is called whenever our device increases or decreases in charge. When we change this state, we call theupdate_status_information()function again, as the level may change the state the device is now in (which will affect how often our Ajax is called etc). Afterwards, we update the front end withdisplay_status_information().

levelchange事件 :每当我们的设备电量增加或减少时,都会调用此事件 。 当我们更改此状态时,我们再次调用update_status_information()函数,因为该级别可能会更改设备当前所处的状态(这将影响Ajax的调用频率等)。 然后,我们使用display_status_information()更新前端。

ThechargingchangeEvent: this is called when the device either stops or starts charging. We call theget_battery_charging()function to get the new state, and then update the front end withdisplay_status_information().

chargingchange事件 :当设备停止或开始充电时,将调用此事件 。 我们调用get_battery_charging()函数以获取新状态,然后使用display_status_information()更新前端。

创建主循环功能 (Creating the Main Loop Function)

The last step in this sequence is to call thestart_ajax_api_task()function. Inside here, we check for thebattery_statusand see if it's critical. If it is, we won't be having any Ajax calls (it's a manual update only).

此序列的最后一步是调用start_ajax_api_task()函数。 在这里,我们检查battery_status并查看它是否很关键。 如果是这样,我们将不会有任何Ajax调用(仅是手动更新)。

If we're not in a critical state, we then create two loops. The first loop will be assigned to theapi_action_interval_itemvariable, and it will be used to call thereplace_grid_image()function every X seconds (where the time is determined based on your battery state). The second loop is used to act as a counter, so visually you can see when the next update will be happening.

如果我们没有处于临界状态,那么我们将创建两个循环。 第一个循环将分配给api_action_interval_item变量,并且将用于每X秒调用一次replace_grid_image()函数(该时间取决于您的电池状态)。 第二个循环用作计数器,因此您可以直观地看到何时进行下一次更新。

调用CatAPI替换图像 (Calling the CatAPI to Replace an Image)

Thereplace_grid_image()function is called every X seconds so that we can pull a new image from the CatAPI.

每X秒调用一次replace_grid_image()函数,以便我们可以从CatAPI中提取新图像。

We use jQuery's$.ajaxfunction to send a request to our PHP file and return a single image from the CatAPI. This is then added into our gallery. We use a few neat functions so that a random image will be replaced and that it will fade in nicely (this is all for presentation).

我们使用jQuery的$.ajax函数将请求发送到我们PHP文件,并从CatAPI返回单个图像。 然后将其添加到我们的画廊中。 我们使用一些简洁的函数,以便替换随机图像并使它淡入淡出(全部用于演示)。

Here's a GIF representation of the API in action:

这是实际使用的API的GIF表示形式:

You could modify the example so that you do something else. However, the main point is that you're now executing this function conditionally on the battery state.

您可以修改示例,以便执行其他操作。 但是,主要要点是您现在可以根据电池状态有条件地执行此功能。

包装全部 (Wrapping It All Up)

Now that you've seen how you can use the additional information from the Battery Status API, you can customize each user's experience to match their device's available power.

既然您已经了解了如何使用电池状态API中的其他信息,则可以自定义每个用户的体验以匹配其设备的可用功率。

You could do subtle things such as setting conservative default settings on low battery, or you may opt to change a user's experience entirely.

您可以做一些微妙的事情,例如在电池电量低时设置保守的默认设置,或者您可以选择完全改变用户的体验。

Once again, you cancheck out the GitHub repositoryto see all the code used in this demo.

再一次,您可以检出GitHub存储库以查看此演示中使用的所有代码。

And you can alsoview a working demoto see it in action. (Try it out on various devices, at various battery levels, to compare results!)

您还可以查看正在运行的演示,以查看实际操作。 (在各种设备,不同电池电量下尝试一下,以比较结果!)

Let us know in the comments if you've used the Battery API, or if you plan to use it to build something exciting! I'd love to know what you think of it.

在注释中让我们知道您是否使用过Battery API,或者您打算使用它来构建令人兴奋的东西! 我很想知道您对此有何看法。

翻译自: /using-the-battery-status-api-to-optimize-your-development/

api接口优化

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。