Flutter plugin插件编写如何正确打开,避免报红

2024-09-19  本文已影响0人  Pino

1、文件、新建、新建flutter项目


image.png

2、选择flutter、下一步


image.png

3、选择类型为插件,我这里选择java


image.png

当我们创建一个插件的时候,如何正确打开避免报红?鼠标移动到example>android文件夹,右键


image.png image.png image.png

最后是的MyFfPlugin代码,

package com.example.my_ff;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Build;

import androidx.annotation.NonNull;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

/** MyFfPlugin */
public class MyFfPlugin implements FlutterPlugin, MethodCallHandler {
  private MethodChannel channel;
  private Context context;

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    context = flutterPluginBinding.getApplicationContext();
    channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "my_ff");
    channel.setMethodCallHandler(this);
  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
    if (call.method.equals("getPlatformVersion")) {
      result.success("Android " + android.os.Build.VERSION.RELEASE);
    }else if (call.method.equals("getPlatformBatteryLevel")){
      int batteryLevel=getBatteryLevel();
      result.success("Android"+batteryLevel);
    }else if (call.method.equals("getAppKey")){
      result.success("Android key: asda2323264615++++");
    }else {
      result.notImplemented();
    }
  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    channel.setMethodCallHandler(null);
  }

  // 获取电池电量
  private int getBatteryLevel() {
    int batteryLevel = -1;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      BatteryManager batteryManager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
      if (batteryManager != null) {
        batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
      }
    } else {
      Intent batteryIntent = new ContextWrapper(context)
              .registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
      int level = batteryIntent != null ? batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) : -1;
      int scale = batteryIntent != null ? batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1) : -1;
      batteryLevel = (level * 100) / scale;
    }

    return batteryLevel;
  }
}

上一篇下一篇

猜你喜欢

热点阅读