flutter调用Android原生方法 MethodChannel

flutter端:

import 'package:flutter/services.dart';

class GeocoderToAddress{

  static const MethodChannel _channel = const MethodChannel('analysis_address');

  static Future getPlatformVersion(double lon,double lat) async {
    Map args = {
      "lon": lon,
      "lat":lat
    };
    print(args);
    final String address = await _channel.invokeMethod('getPlatformAddress',args);
    return address;
  }
}

flutter调用:

GeocoderToAddress.getPlatformVersion(CommonUntil.lon, CommonUntil.lat).then((onValue){
  print(onValue);
});

 

Android端

//在启动方法中
val shimPluginRegistry = ShimPluginRegistry(flutterEngine)
val registrar = shimPluginRegistry.registrarFor(packageName)
getAddress(registrar);
public fun getAddress(registrar: PluginRegistry.Registrar) {
    MethodChannel(registrar.messenger(), "analysis_address").setMethodCallHandler { methodCall, result ->
        if (methodCall.method == "getPlatformAddress") {
            val lon = methodCall.argument("lon")
            val lat = methodCall.argument("lat")

            val handle = object: Handler(){
                override fun handleMessage(msg: Message?) {
                    print(msg?.obj);
                    result.success(msg?.obj);
                }
            }

            Thread(Runnable {
                try {
                  val  addresses = getAddress(context, lat, lon)?.getAddressLine(0)?.replace("Unnamed Road", "")!!
                    val msg = Message.obtain()
                    msg.obj = addresses
                    handle.sendMessage(msg)

                } catch (e: Exception) {
                    Log.d("地址解析异常", e.message)
                }
            }).start()
        }

    }
}


/**
 * 根据经纬度获取地理位置
 * * @param context 上下文
 *
 * @param latitude  纬度
 * @param longitude 经度
 * @return [Address]
 */
fun getAddress(context: Context, latitude: Double?, longitude: Double?): Address? {
    val geocoder = Geocoder(context, Locale.getDefault())
    try {
        val addresses = geocoder.getFromLocation(latitude!!, longitude!!, 1)
        if (addresses.size > 0)
            return addresses[0]
    } catch (e: IOException) {
        e.printStackTrace()
    }

    return null
}

你可能感兴趣的:(Flutter)