Flutter Native 方法调用

在混合开发中,无论哪种技术手段都避免不了native与框架的互相调用。Flutter基于以下方法实现了与native的互相调用。

Flutter称这种操作叫platform-specific

接下来要实现一个栗子、Flutter端获取Native的电量,并且当电量改变时会通知Flutter端。

一、Flutter调用Native

使用android端实现

1、创建一个项目

项目创建

2、在Flutter端封装一个获取手机电量的方法

import 'package:flutter/services.dart';

class BatteryManager {
  /// MethodChannel name是一个唯一标记,不重复就好
  static const platform =
      const MethodChannel('org.tiny.platformspecific/battery');

  /// 远程调用需要异步操作, 把这个方法生命成 async
  static Future<int> getBattery() async {
    // 处理异常
    try {
      // getBatteryLevel 是远程方法的名字
      final int result = await platform.invokeMethod('getBatteryLevel');
      return Future.value(result);
    } on PlatformException catch (e) {
      return Future.value(-1);
    }
  }
}

3、Android端具体实现

package org.tiny.platformspecific;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;

import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.view.FlutterView;

/**
 * Created by tiny on 2/21/2019.
 */
public class BatteryManager implements MethodChannel.MethodCallHandler {
    private static final String CHANNEL = "org.tiny.platformspecific/battery";
    private Context mContext;

    static void registerWith(FlutterActivity activity) {
        new BatteryManager(activity.getFlutterView());
    }

    private BatteryManager(FlutterView view) {
        mContext = view.getContext();
        new MethodChannel(view, CHANNEL).setMethodCallHandler(this);
    }

    @Override
    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
        String method = methodCall.method;
        switch (method) {
            case "getBatteryLevel":
                result.success(getBatteryLevel());
                break;
            default:
                result.notImplemented();
                break;
        }
    }

    private int getBatteryLevel() {
        Intent intent = new ContextWrapper(mContext.getApplicationContext()).
                registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        if (intent == null) return -1;
        return intent.getIntExtra(android.os.BatteryManager.EXTRA_LEVEL, -1);
    }
}

4、注册

package org.tiny.platformspecific;

import android.os.Bundle;

import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;

public class MainActivity extends FlutterActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GeneratedPluginRegistrant.registerWith(this);
        BatteryManager.registerWith(this);
    }
}

5、总结

以上完成了Flutter到Android端的调用、套路还是很简单的,总结一下:
1、Flutter端创建 MethodChannel,使用 invokeMethod 调用远程方法
2、Native端创建 MethodChannel,实现 MethodCallHandler
3、Native完成注册

二、Flutter对Native设置监听

因为电量是一个不断变化的值,所以就需要Flutter对Native的监听这时候使用MethodChannel是不行的,所以有请下一个EventChannel,还是先上代码。

1、Flutter端创建

参照之前的Flutter代码进行了修改,使电量管理成为一个单例

import 'dart:async';

import 'package:flutter/services.dart';

class BatteryManager {
  static BatteryManager _instance;
  final MethodChannel _methodChannel;
  final EventChannel _eventChannel;
  StreamSubscription _eventStreamSubscription;

  /// _私有构造方法
  BatteryManager._(this._methodChannel, this._eventChannel);

  /// 创建单例
  static BatteryManager getInstance() {
    if (_instance == null) {
      final MethodChannel methodChannel =
          const MethodChannel('org.tiny.platformspecific/battery');
      final EventChannel eventChannel =
          const EventChannel('org.tiny.platformspecific/charging');
      _instance = BatteryManager._(methodChannel, eventChannel);
    }
    return _instance;
  }

  /// 得到电量
  Future<int> getBatteryLevel() async {
    try {
      final int level = await _methodChannel.invokeMethod('getBatteryLevel');
      return Future.value(level);
    } on PlatformException catch (e) {
      return Future.value(-1);
    }
  }

  /// 监听电量的变化
  StreamSubscription setOnBatteryListener(void onEvent(int battery)) {
    if (_eventStreamSubscription == null) {
      _eventStreamSubscription = _eventChannel
          .receiveBroadcastStream()
          .listen((data) => onEvent(data));
    }
    return _eventStreamSubscription;
  }
}

2、Android端代码

package org.tiny.platformspecific;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;

import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

/**
 * Created by tiny on 2/21/2019.
 */
public class BatteryManager implements MethodChannel.MethodCallHandler, EventChannel.StreamHandler {
    private static final String METHOD = "org.tiny.platformspecific/battery";
    private static final String EVENT = "org.tiny.platformspecific/charging";
    private FlutterActivity mFlutterActivity;
    private BroadcastReceiver mChargingStateChangeReceiver;

    static void registerWith(FlutterActivity activity) {
        new BatteryManager(activity);
    }

    private BatteryManager(FlutterActivity activity) {
        mFlutterActivity = activity;
        new MethodChannel(mFlutterActivity.getFlutterView(), METHOD).setMethodCallHandler(this);
        new EventChannel(mFlutterActivity.getFlutterView(), EVENT).setStreamHandler(this);
    }

    @Override
    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
        String method = methodCall.method;
        switch (method) {
            case "getBatteryLevel":
                result.success(getBatteryLevel());
                break;
            default:
                result.notImplemented();
                break;
        }
    }

    private int getBatteryLevel() {
        Intent intent = new ContextWrapper(mFlutterActivity.getApplicationContext()).
                registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        if (intent == null) return -1;
        return intent.getIntExtra(android.os.BatteryManager.EXTRA_LEVEL, -1);
    }

    @Override
    public void onListen(Object arguments, final EventChannel.EventSink eventSink) {
        mChargingStateChangeReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                int battery = intent.getIntExtra(android.os.BatteryManager.EXTRA_LEVEL, -1);
                eventSink.success(battery);
            }
        };
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        mFlutterActivity.registerReceiver(mChargingStateChangeReceiver, filter);
    }

    @Override
    public void onCancel(Object arguments) {
        if (mChargingStateChangeReceiver != null) {
            mFlutterActivity.unregisterReceiver(mChargingStateChangeReceiver);
        }
    }
}

3、使用

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  int _battery = 0;
  StreamSubscription _streamSubscription;

  @override
  void initState() {
    _getBattery();
    super.initState();
  }

  void _getBattery() async {
    int battery = await BatteryManager.getInstance().getBatteryLevel();
    _setBattery(battery);
    _streamSubscription =
        BatteryManager.getInstance().setOnBatteryListener(_setBattery);
  }

  void _setBattery(int battery) {
    setState(() {
      _battery = battery;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text('Battery: $_battery'),
      ),
    );
  }

  @override
  void dispose() {
    _streamSubscription?.cancel();
    super.dispose();
  }
}

三、遇到的一些坑

1、android studio 代码离奇报错

我在android studio中编辑代码的时候,出现了各种莫名其妙的错误,比如



显示我现在最小sdk版本是1?wtf。所以我直接用as打开了flutter中的android项目, 啥毛病也没有了

2、取消广播

就android端实现而言,获取电量是通过广播获取的, 所以要在生命周期中加入取消的动作,flutter页面被销毁时调用了dispose方法,结果我得到的是一堆报错,说明没有调用unregisterReceiver,天地良心,我确实写了,但flutter并没有为我调用dispose。
原因是这样的, 我在flutter使用hot reload,直接在首页调用了(整个应用只有一个页面)直接按back键退出时,可能是reload的问题,导致了dispose不调用。我把代码修改成了这个样子。

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:platform_specific/battery_manager.dart';

void main() => runApp(Main());

class Main extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Hello(),
    );
  }
}

class Hello extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(),
      body: Center(
        child: RaisedButton(
          child: Text('Hello'),
          onPressed: () {
            Navigator.of(context).push(MaterialPageRoute(builder: (context) {
              return MyApp();
            }));
          },
        ),
      ),
    ));
  }
}

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  int _battery = 0;
  StreamSubscription _streamSubscription;

  @override
  void initState() {
    _getBattery();
    super.initState();
  }

  void _getBattery() async {
    int battery = await BatteryManager.getInstance().getBatteryLevel();
    _setBattery(battery);
    _streamSubscription =
        BatteryManager.getInstance().setOnBatteryListener(_setBattery);
  }

  void _setBattery(int battery) {
    setState(() {
      _battery = battery;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text('Battery: $_battery'),
      ),
    );
  }

  @override
  void dispose() {
    _streamSubscription?.cancel();
    super.dispose();
  }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,569评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,499评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,271评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,087评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,474评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,670评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,911评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,636评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,397评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,607评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,093评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,418评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,074评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,092评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,865评论 0 196
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,726评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,627评论 2 270