Flutter插件开发--获取Android手机电池信息
由于我不會(huì)做IOS開(kāi)發(fā),文章里面沒(méi)有IOS的代碼。下面的參考教程里有具體的IOS代碼
參考教程:flutter中文網(wǎng)–Flutter實(shí)戰(zhàn)–插件開(kāi)發(fā),平臺(tái)介紹和實(shí)現(xiàn)Android端API
?最后的執(zhí)行效果如下:
平臺(tái)通道
?平臺(tái)指的是flutter運(yùn)行的平臺(tái),如Android或者ios,可以認(rèn)為就是應(yīng)用的原生部分,所以,平臺(tái)通道正是Flutter和原生之間通信的橋梁,它也是Flutter插件的底層基礎(chǔ)設(shè)施。
?Flutter使用了一個(gè)靈活的系統(tǒng),允許調(diào)用特定平臺(tái)的API,無(wú)論在Android上的Java或者Kotlin代碼中,還是在IOS上的OC或者swift代碼中均可用。
?Flutter與原生之間的通信依賴(lài)靈活的消息傳遞方式:
- 應(yīng)用的Flutter部分通過(guò)平臺(tái)通道(platform channel)將消息發(fā)送到其應(yīng)用程序所在的宿主(IOS或者Android)應(yīng)用(原生應(yīng)用)
- 宿主監(jiān)聽(tīng)平臺(tái)通道,并接受該消息,然后它會(huì)調(diào)用該平臺(tái)的API,并將響應(yīng)發(fā)送回客戶(hù)端,即應(yīng)用程序的Flutter部分。
?使用平臺(tái)通道在Flutter(client)和原生(host)之間傳遞消息,如下圖所示:
?當(dāng)在Flutter中調(diào)用原生方法時(shí),調(diào)用信息通過(guò)平臺(tái)通道傳遞到原生,原生收到調(diào)用信息后可以執(zhí)行指定的操作,如果需要返回?cái)?shù)據(jù),則原生會(huì)將數(shù)據(jù)再通過(guò)平臺(tái)通道傳遞給Flutter,需要注意的是消息的傳遞是異步的,這確保了用戶(hù)界面再消息傳遞時(shí)不會(huì)被掛起。
?在客戶(hù)端,MethodChannel API可以發(fā)送與方法調(diào)用相對(duì)應(yīng)的消息,在宿主平臺(tái)上,MethodChannel在Android API和FlutterMethodChannel IOS API可以接收方法調(diào)用并返回結(jié)果,這些類(lèi)可以幫助我們用很少的代碼就能開(kāi)發(fā)平臺(tái)插件。
?如果需要,方法調(diào)用(消息傳遞)可以是反向的,即宿主作為客戶(hù)端調(diào)用Dart中實(shí)現(xiàn)的API,quick_actions插件就可以這么做。
開(kāi)發(fā)Flutter插件
?使用平臺(tái)通道調(diào)用原生代碼
?下面是一個(gè)獲取電池電量的插件,該插件在Dart中通過(guò)getBatteryLevel調(diào)用Android BatteryManager API和IOS的相關(guān)API。
?Flutter中的代碼如下:
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart';/*** 插件開(kāi)發(fā)--獲取宿主平臺(tái)的電量信息*/class BetteryInfoPage extends StatelessWidget {@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text("插件開(kāi)發(fā)--獲取電量",style: TextStyle(color: Colors.greenAccent,),maxLines: 1,overflow: TextOverflow.ellipsis,),elevation: 0.0,backgroundColor: Colors.lime,),body: BetteryInfoRoute(),);} }class BetteryInfoRoute extends StatefulWidget {@override_BetteryInfoRouteState createState() {return _BetteryInfoRouteState();} }class _BetteryInfoRouteState extends State with SingleTickerProviderStateMixin {static const platform = const MethodChannel("samples.flutter.io/battery");//默認(rèn)電量100%double _currentBetteryInfo = 100;//當(dāng)前的文字顏色,根據(jù)不同的電量改變Color _betteryColor = Colors.greenAccent;//動(dòng)畫(huà)控制器AnimationController _animationController;//動(dòng)畫(huà)Animation _animation;//顯示當(dāng)前獲取電量的狀態(tài)信息String _currentState = "正在獲取信息";@overridevoid initState() {// TODO: implement initStatesuper.initState();setBatteryColor();getValueColorAnimation();_getBatteryLevel();}@overrideWidget build(BuildContext context) {//一個(gè)圓形進(jìn)度條中間顯示電量的百分比return Center(child: Stack(alignment: Alignment.center,children: <Widget>[Container(constraints: BoxConstraints.expand(width: 120.0, height: 120.0),child: CircularProgressIndicator(backgroundColor: Colors.redAccent,valueColor: _animation,value: _currentBetteryInfo / 100,),),Padding(padding: EdgeInsets.all(10.0),child: Text(_currentState,style: TextStyle(color: _betteryColor,),),),],),);}//設(shè)置動(dòng)畫(huà)void getValueColorAnimation() {if (_animationController == null) {_animationController =AnimationController(duration: Duration(seconds: 5), vsync: this);}_animation =CurvedAnimation(parent: _animationController, curve: Curves.ease);_animation = Tween(begin: _betteryColor, end: Colors.greenAccent).animate(_animation);}//設(shè)置不同電量的顏色void setBatteryColor() {if (_currentBetteryInfo > 80) {_betteryColor = Colors.greenAccent;} else if (_currentBetteryInfo > 50) {_betteryColor = Colors.orangeAccent;} else {_betteryColor = Colors.redAccent;}}//獲取電量Future<Null> _getBatteryLevel() async {try {_currentBetteryInfo = await platform.invokeMethod("getBatteryLevel");_currentState = "${_currentBetteryInfo.toString()}%";} on PlatformException catch (e) {//出現(xiàn)異常_currentState = "failed";} finally {//最終都會(huì)執(zhí)行刷新操作setState(() {setBatteryColor();getValueColorAnimation();});}} }//Android中的代碼如下:
package com.example.basicwidgetdemo1;import android.content.ContextWrapper; import android.content.Intent; import android.content.IntentFilter; import android.os.BatteryManager; import android.os.Build; import android.os.Bundle;import io.flutter.app.FlutterActivity; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugins.GeneratedPluginRegistrant;public class MainActivity extends FlutterActivity {private static final String CHANNEL = "samples.flutter.io/battery";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);GeneratedPluginRegistrant.registerWith(this);new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(new MethodChannel.MethodCallHandler() {@Overridepublic void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {if(methodCall.method.equals("getBatteryLevel")){double batteryLevel = getBatteryLevel();if(batteryLevel != -1){result.success(batteryLevel);}else{result.error("UNAVAILABLE","Battery level not available",null);}}else{result.notImplemented();}}});}//獲取手機(jī)剩余電量private double getBatteryLevel(){double battery = -1;if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){BatteryManager manager = (BatteryManager) getSystemService(BATTERY_SERVICE);battery = manager.getLongProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);}else{Intent intent = new ContextWrapper(getApplicationContext()).registerReceiver(null,new IntentFilter(Intent.ACTION_BATTERY_CHANGED));battery = intent.getIntExtra(BatteryManager.EXTRA_LEVEL,-1) / intent.getIntExtra(BatteryManager.EXTRA_SCALE,-1);}return battery;} }總結(jié)
以上是生活随笔為你收集整理的Flutter插件开发--获取Android手机电池信息的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: kodi mysql_Kodi
- 下一篇: dsp和通用计算机的区别,汽车dsp和功