flutter端:
时间:2020年11月
class _MyHomePageState extends State<MyHomePage> {
static const platform = const MethodChannel('samples.flutter.dev/battery');//flutter调用Android的通道
static const EventChannel _channel = const EventChannel('Event_Channel');//Android主动传给flutter的通道
String _batteryLevel = 'Unknown battery level.';
StreamSubscription _streamSubscription;
String _platformMessage;
void _enableEventReceiver() {//使能接收Android主动传给flutter的数据
_streamSubscription = _channel.receiveBroadcastStream().listen(
(dynamic event) {
print('Received event: $event');
setState(() {
_platformMessage = event;
});
},
onError: (dynamic error) {
print('Received error: ${error.message}');
},
cancelOnError: true);
}
void _disableEventReceiver() {//不再接收Android主动传给flutter的数据
if (_streamSubscription != null) {
_streamSubscription.cancel();
_streamSubscription = null;
}
}
@override
initState() {
super.initState();
_enableEventReceiver();
print("initState()");
}
@override
void dispose() {
super.dispose();
print("dispose()");
_disableEventReceiver();
}
Future<void> _getBatteryLevel() async {//主动调用Android函数
String batteryLevel;
try {
final int result = await platform.invokeMethod('getBatteryLevel');
batteryLevel = 'Battery level at $result % .';
} on PlatformException catch (e) {
batteryLevel = "Failed to get battery level: '${e.message}'.";
}
setState(() {
_batteryLevel = batteryLevel;
});
}
//如下自由发挥
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/0.bmp'),
fit: BoxFit.fill,
)),
child: Scaffold(
backgroundColor: Colors.transparent, //把scaffold的背景色改成透明
/*appBar: AppBar(
backgroundColor: Colors.transparent, //把appbar的背景色改成透明
// elevation: 0,//appbar的阴影
title: Text(widget.title),
),*/
body: Center(
child: Text(_batteryLevel),
),
floatingActionButton: FloatingActionButton(
onPressed: _getBatteryLevel,//按键手动调用Android函数
tooltip: 'Increment',
child: Icon(Icons.add),
),
)
);
}
}
Android端
class MainActivity: FlutterActivity() {
lateinit var mContext: Context
override fun onCreate(savedInstanceState: Bundle?) {
mContext = this.applicationContext
super.onCreate(savedInstanceState)
init()
registerBroadcastReceiver()
myRequestPermissions()
}
private val CHANNEL = "samples.flutter.dev/battery"//被flutter调用的通道
var mEventSink: EventChannel.EventSink? = null
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
//接收flutter的调用
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
if (call.method == "getBatteryLevel") {
val batteryLevel = getBatteryLevel()
scanfWifi()
if (batteryLevel != -1) {
result.success(batteryLevel)
} else {
result.error("UNAVAILABLE", "Battery level not available.", null)
}
} else {
result.notImplemented()
}
}
//初始化调用flutter,并获取EventSink,赋值给全局变量mEventSink,通过mEventSink.success()即可传数据到flutter
EventChannel(flutterEngine.dartExecutor.binaryMessenger, "Event_Channel").setStreamHandler(object : EventChannel.StreamHandler {
override fun onListen(o: Any?, eventSink: EventChannel.EventSink) {
Log.d("TAG", "EventChannel onListen")
mEventSink = eventSink
eventSink.success("hello world !")
}
override fun onCancel(o: Any?) {
Log.d("TAG", "EventChannel onCancel")
}
})
}
private fun getBatteryLevel(): Int {
val batteryLevel: Int
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager
batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
} else {
val intent = ContextWrapper(applicationContext).registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
batteryLevel = intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
}
return batteryLevel
}
}