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