如何从颤动中正确调用android本机代码(android/IOS)?
Posted
技术标签:
【中文标题】如何从颤动中正确调用android本机代码(android/IOS)?【英文标题】:how to call android native code(both android/IOS) properly from flutter? 【发布时间】:2020-05-10 17:48:42 【问题描述】:我是 Flutter 的初学者。老实说不知道android Studio。
我的目标是实现本地(系统)身份验证。所以得到了local_auth
插件,它只给你一个指纹选项。如果用户没有指纹硬件怎么办?所以我打算通过从flutter调用原生代码(Android)来实现这个东西。
但问题是我无法正确验证用户身份。
例如,在进行身份验证时,响应来自本机代码。
在进行身份验证之前,我无法暂停函数的执行。尝试过同步方法
但仍然没有运气。
我的飞镖代码:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(Container(
child: Row(
children: <Widget>[
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Center(child: 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,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
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(()
// // This call to setState tells the Flutter framework that something has
// // changed in this State, which causes it to rerun the build method below
// // so that the display can reflect the updated values. If we changed
// // _counter without calling setState(), then the build method would not be
// // called again, and so nothing would appear to happen.
// _counter++;
// );
// my_count();
// var cc = code().toString();
// print(cc);
// if(cc == "200")
// Navigator.push(
// context,
// MaterialPageRoute(builder: (context) => SecondRoute()),
// );
// else if( cc == "333")
// Navigator.push(context,
// MaterialPageRoute(
// builder: (context) => ThirdRoute()
// ));
//
code();
@override
void initState()
// TODO: implement initState
super.initState();
my_count();
@override
Widget build(BuildContext context)
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
static const paltform = const MethodChannel('lock');
// ignore: missing_return
void code() async
int ii;
try
ii = await paltform.invokeMethod('value');
catch (e)
print(e);
// print(ii);
// return ii;
if(ii == 200)
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);
else if( ii == 333)
Navigator.push(context,
MaterialPageRoute(
builder: (context) => ThirdRoute()
));
// ignore: non_constant_identifier_names
void my_count() async
try
_counter = await paltform.invokeMethod('getCounter');
catch(e)
print(e);
//if i call code() here it not executing
code();
class SecondRoute extends StatelessWidget
@override
Widget build(BuildContext context)
return Scaffold(
appBar: AppBar(
title: Text("Second Route"),
),
body: Center(
child: RaisedButton(
onPressed: ()
// Navigate back to first route when tapped.
Navigator.pop(context);
,
child: Text('Go back!'),
),
),
);
class ThirdRoute extends StatelessWidget
@override
Widget build(BuildContext context)
return Scaffold(
appBar: AppBar(
title: Text("Third Route"),
),
body: Center(
child: RaisedButton(
onPressed: ()
// Navigate back to first route when tapped.
Navigator.pop(context);
,
child: Text('Go back!'),
),
),
);
我正在做的是从颤振调用本机代码并从本机端获取响应代码 基于该路由页面 这是我的 Android 代码:
package com.example.native_3;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;
import android.app.KeyguardManager;
import android.content.Intent;
import android.os.Build;
public class MainActivity extends FlutterActivity
private static final int LOCK_REQUEST_CODE = 221;
private static final int SECURITY_SETTING_REQUEST_CODE = 233;
int code = 0;
private static final String CHANNEL = "lock";
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine)
GeneratedPluginRegistrant.registerWith(flutterEngine);
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
.setMethodCallHandler(
(call, result) ->
// Note: this method is invoked on the main thread.
if (call.method.equals("getCounter"))
synchronized (this)
authenticateApp();
int batteryLevel = 0;
if (batteryLevel >= 0)
result.success(batteryLevel);
else
result.error("UNAVAILABLE", "Battery level not available.", null);
else if (call.method.equals("value"))
result.success(get());
else
result.notImplemented();
);
private int get()
return code;
private synchronized void authenticateApp()
//Get the instance of KeyGuardManager
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
//Check if the device version is greater than or equal to Lollipop(21)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
//Create an intent to open device screen lock screen to authenticate
//Pass the Screen Lock screen Title and Description
Intent i = keyguardManager.createConfirmDeviceCredentialIntent("unlock", "to unlock");
try
//Start activity for result
startActivityForResult(i, LOCK_REQUEST_CODE);
catch (Exception e)
// //If some exception occurs means Screen lock is not set up please set screen lock
// //Open Security screen directly to enable patter lock
// Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
// try
//
// //Start activity for result
// startActivityForResult(intent, SECURITY_SETTING_REQUEST_CODE);
// catch (Exception ex)
//
// //If app is unable to find any Security settings then user has to set screen lock manually
// textView.setText(getResources().getString(R.string.setting_label));
//
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
// super.onActivityResult(requestCode, resultCode, data);
synchronized (this)
switch (requestCode)
case LOCK_REQUEST_CODE:
if (resultCode == RESULT_OK)
//If screen lock authentication is success update text
code = 200;
else
//If screen lock authentication is failed update text
code = 333;
break;
case SECURITY_SETTING_REQUEST_CODE:
//When user is enabled Security settings then we don't get any kind of RESULT_OK
//So we need to check whether device has enabled screen lock or not
if (isDeviceSecure())
//If screen lock enabled show toast and start intent to authenticate user
code = 444;
else
//If screen lock is not enabled just update text
code = 555;
break;
private boolean isDeviceSecure()
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
//this method only work whose api level is greater than or equal to Jelly_Bean (16)
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && keyguardManager.isKeyguardSecure();
//You can also use keyguardManager.isDeviceSecure(); but it requires API Level 23
运行它们后,我只有在按下按钮后才会得到成功的响应。 但我希望它应该根据本机代码的响应相应地路由自己
【问题讨论】:
【参考方案1】:local_auth 还允许进行 pin、模式或密码验证。您可以通过auth.getAvailableBiometrics()
获取设备可用的生物特征认证列表。
【讨论】:
以上是关于如何从颤动中正确调用android本机代码(android/IOS)?的主要内容,如果未能解决你的问题,请参考以下文章
如何更新本机现有应用程序以在 Appstore 和 PlayStore 中颤动?