首页 > 解决方案 > 如何创建一个可以正确访问android原生AudioManager的flutter插件

问题描述

我正在创建一个名为“newplugin”的插件。我想做的是AudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION)让应用程序通过手机的听筒输出音频。(这适用于本机 Java Android 应用程序)但它不适用于颤振。我怎样才能正确实施它?

package com.newplugin.newplugin;

import android.content.Context;
import android.media.AudioManager;

import androidx.annotation.NonNull;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.BinaryMessenger;
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;
import io.flutter.plugin.common.PluginRegistry.Registrar;

/** NewpluginPlugin */
public class NewpluginPlugin implements FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private MethodChannel channel;
  private AudioManager audioManager;
  private Context context;
  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {

    channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "newplugin");
    channel.setMethodCallHandler(this);

    context = flutterPluginBinding.getApplicationContext();
    audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
    if (call.method.equals("setComMode")) {
      audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
    }
    else {
      result.notImplemented();
    }
  }

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

标签: flutterflutter-plugin

解决方案


推荐阅读