Android 原生与Flutter交互 MethodChannel


参考网上案列flutter  model中获取原生电量案例

Flutter代码

main.dart页面

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

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
  //根据原生条装过来的路由信息打开不同的flutter页面
home: getDefaultRouter(),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);

final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;

void _incrementCounter() {
setState(() {
_counter++;
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}


Widget getDefaultRouter(){
String router = window.defaultRouteName;
if (router == 'routerPage') {
return BatteryWidget();
} else {
return MyHomePage();
}
}

显示获取到电量的battery_widget.dart页面
class BatteryWidget extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new _BatteryWidgetState();
}
}

class _BatteryWidgetState extends State<BatteryWidget> {
String _batteryLevel = "Battery level: unknown.";
 
//samples.flutter.io/battery指定唯一标志字符串
  static const MethodChannel methodChannel =
MethodChannel('samples.flutter.io/battery');

@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(_batteryLevel),
RaisedButton(
child: const Text('Refresh'),
onPressed: _getBatteryLevel,
),
],
),
),
);
}

Future<void> _getBatteryLevel() async {
String batteryLevel;
try {
    //getBatteryLevel调用方法名,取值时需保持一致
      final int result = await methodChannel.invokeMethod('getBatteryLevel');
batteryLevel = 'Battery level: $result%.';
} on PlatformException {
batteryLevel = 'Failed to get battery level.';
}
setState(() {
_batteryLevel = batteryLevel;
});
}
}

Activity 代码

public class MainActivity extends AppCompatActivity {
  
  //指定唯一标志字符串与flutter中保持一致
    private static final String BATTERY_CHANNEL = "samples.flutter.io/battery";

TextView tv_btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

tv_btn = findViewById(R.id.tv_btn);

//创建flutter发动机
FlutterEngine flutterEngine = new FlutterEngine(MainActivity.this);
//指定想要跳转的flutter页面 这里要和下图对应上 记住他
flutterEngine.getNavigationChannel().setInitialRoute("routerPage");
flutterEngine.getDartExecutor().executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault());
//这里做一个缓存 可以在适当的地方执行他 比如MyApp里 或者未跳转flutterr之前 在flutter页面执行前预加载
FlutterEngineCache flutterEngineCache = FlutterEngineCache.getInstance();
//缓存可以缓存好多个 以不同的的id区分
flutterEngineCache.put("default_engine_id", flutterEngine);
tv_btn.setOnClickListener(v -> {
startActivity(FlutterActivity.withCachedEngine("default_engine_id").build(MainActivity.this));
});
//MethodChannel实现一
new MethodChannel(new ShimPluginRegistry(flutterEngine).registrarFor(BATTERY_CHANNEL).messenger(), BATTERY_CHANNEL).setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
                //getBatteryLevel根据约定方名取值
                        if (call.method.equals("getBatteryLevel")) {
int batteryLevel = getBatteryLevel();

if (batteryLevel != -1) {
result.success(batteryLevel);
} else {
result.error("UNAVAILABLE", "Battery level not available.", null);
}
} else {
result.notImplemented();
}
}
}
);
//MethodChannel实现二
// ShimPluginRegistry shimPluginRegistry = new ShimPluginRegistry(flutterEngine);
// FlutterPluginSendToAct flutterPluginSendToAct=new FlutterPluginSendToAct(MainActivity.this);
// flutterPluginSendToAct.registerWith(shimPluginRegistry.registrarFor(BATTERY_CHANNEL));


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

class FlutterPluginSendToAct implements MethodChannel.MethodCallHandler {

MethodChannel channel;

private Activity activity;

private FlutterPluginSendToAct(Activity activity) {
this.activity = activity;
}

public void registerWith(PluginRegistry.Registrar registrar) {
channel = new MethodChannel(registrar.messenger(), BATTERY_CHANNEL);
FlutterPluginSendToAct instance = new FlutterPluginSendToAct(registrar.activity());
//setMethodCallHandler在此通道上接收方法调用的回调
channel.setMethodCallHandler(instance);
}

@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
//接收来自flutter的指令
if (call.method.equals("getBatteryLevel")) {//getBatteryLevel根据约定方名取值
                int batteryLevel = getBatteryLevel();
          //将电量(实际情况可根据需要传值)赋给result,可在flutter中调用
                if (batteryLevel != -1) {
result.success(batteryLevel);
} else {
result.error("UNAVAILABLE", "Battery level not available.", null);
}
} else {
result.notImplemented();
}
}
}
}

以上即可在flutter中调用Android原生,并取值


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM