L o a d i n g . . .
主打一个C++
文章详情

FLutter调用android原生api打开手机电池优化

Posted on 2025-04-30 11:33:44 by 主打一个C++

MainActivity函数添加代码:

private static final String CHANNEL_BATTERY_OPTIMIZATION = "com.myapp.app/battery_optimization";

主代码:

private void setupBatteryOptimizationChannel(@NonNull FlutterEngine flutterEngine) {
        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL_BATTERY_OPTIMIZATION)
                .setMethodCallHandler(
                        (call, result) -> {
                            if ("openBatteryOptimizationSettings".equals(call.method)) {
                                openBatteryOptimizationSettings();
                                result.success(null);
                            } else {
                                result.notImplemented();
                            }
                        }
                );
    }

    // 打开系统电池优化设置页面
    private void openBatteryOptimizationSettings() {
        Intent intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //避免在非Activity上下文中启动问题
        startActivity(intent);
    }

//注册

setupBatteryOptimizationChannel(flutterEngine);

//Flutter调用函数

import 'package:flutter/services.dart';

Future<void> openBatteryOptimizationSettings() async {
  const platform = MethodChannel('com.myapp.app/battery_optimization');

  try {
    await platform.invokeMethod('openBatteryOptimizationSettings');
  } on PlatformException catch (e) {
    print("Failed to open battery optimization settings: ${e.message}");
  }
}



*转载请注明出处:原文链接:https://cpp.vin/page/144.html

作者近期文章
提示
×
确定
数据库执行: 7次 总耗时: 0.01s
页面加载耗时: 



wechat +447752296473
wechat cpp-blog