Flutter笔记-Android&iOS原生交互

Flutter同React Native一样,可以调用原生方法。

Flutter 代码如下:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:async';      // 异步

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter & Android交互',
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('Flutter & Android交互'),
        ),
        body: new HomeApp(),
      ),
    );
  }
}

class HomeApp extends StatefulWidget {
  @override
  State createState() {
    // TODO: implement createState
    return new HomeAppPage();
  }
}

class HomeAppPage extends State {
  static const platform = const MethodChannel("samples.flutter.io/battery");
  String _batteryLevel = "Unknown battery level.";

  Future _getBatteryLevel() async {
    String batteryLevel;
    try{
       print('dart-_getBatteryLevel');
       // 在通道上调用此方法
       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) {
    // TODO: implement build
    return new Column(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        new RaisedButton(onPressed: _getBatteryLevel,
          child: new Text('Get battery level'),
        ),
        new Text('当前电量:$_batteryLevel')
      ],
    );
  }

}

Android代码:

package com.example.beautifuldemo;

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";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GeneratedPluginRegistrant.registerWith(this);

    // setMethodCallHandler在此通道上接收方法调用的回调
    new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
            new MethodChannel.MethodCallHandler() {
              @Override
              public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
                 // 通过methodCall可以获取参数和方法名  执行对应的平台业务逻辑即可
                 if(methodCall.method.equals("getBatteryLevel")){
                    int batteryLevel = getBatteryLevel();
                    if(batteryLevel != -1){
                       result.success(batteryLevel);
                    }else{
                      result.error("UNAVAILABLE", "Battery level not available.", null);
                    }
                 }else{
                   result.notImplemented();
                 }
              }
            }
    );
  }


  /*获取电池电量*/
  private int getBatteryLevel(){
    int batteryLevel = -1;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
      batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
    } else {
      Intent intent = new ContextWrapper(getApplicationContext()).
            registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
      batteryLevel = (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100) /
            intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    }
    return batteryLevel;
  }
}

iOS 代码:

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GeneratedPluginRegistrant registerWithRegistry:self];
   
  // 获取电池电量
  FlutterViewController *controller = (FlutterViewController*)self.window.rootViewController;
  FlutterMethodChannel *batteryLevelChannel = [FlutterMethodChannel methodChannelWithName:@"samples.flutter.io/battery" binaryMessenger:controller];
    [batteryLevelChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
        if ([@"getBatteryLevel" isEqualToString:call.method]) {
            result(@100);
            return;
        }
        result(FlutterMethodNotImplemented);
    }];
  // Override point for customization after application launch.
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end

效果图:

Flutter笔记-Android&iOS原生交互_第1张图片

你可能感兴趣的:(Android,iOS基础(Swift),Flutter,Flutter学习)