ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Flutter与Native交互(Android百度地图与Flutter交互实战)

2021-12-12 14:00:01  阅读:95  来源: 互联网

标签:baidu 交互 void new import Android com Flutter android


class MapPage extends StatefulWidget {
const MapPage({Key key}) : super(key: key);

@override
_MapPageState createState() => _MapPageState();
}

class _MapPageState extends State with AutomaticKeepAliveClientMixin {
static const platform = const MethodChannel(‘samples.flutter.io/getLocation’);
// 需要跟MainActivity中的一致(com.example.my_project/event)
static const EventChannel eventChannel = const EventChannel(‘com.example.my_project/event’);
bool isShowCard = false;
string eventString = ‘’;

@override
void initState() {
print(’-------------initState--------------’);
super.initState();
eventChannel.receiveBroadcastStream().listen(_onEvent, one rror: _onError);
}

void _onEvent(Object event) {
this.setState(() {
eventString = event;
});
print(’-------------Message from native------------------’ + event.toString());
}

void _onError(Object error) {
setState(() {
print(
‘-------------Error occured on communicate between flutter and native------------------’);
});
}

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
print(’-------------didChangeAppLifecycleState-------------$state-’);
}

@override
void dispose() {
print(’----------dispose---------------’);
super.dispose();
}

void updateMapMarker()

《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》

【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 完整内容开源分享

async {
await platform.invokeMethod(‘refrashMap’, “我是参数”);
}

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
print(’-------------build--------------’);
updateMapMarker();
return Scaffold(
body: Stack(
children: [
Center(
child: AndroidView(viewType: ‘MyMap’),
),
],
));
}

@override
bool get wantKeepAlive => true;
}

Android端代码

怎么配置baidu地图的sdk这里就不细说了,baidu地图的文档给开发者提供了相当详细的说明,在代码里面主要看中MethodChannel和EventChannel的功能,MethodChannel可以通过MethodCall监听Flutter程序事件发来的事件的数据,然后可以通过EventChannel进行发送数据回去,两者结合再一起则是双通道的通信机制。这里发送的数据格式有要求,格式如下(官网图片)

MainActivity.java

com.example.my_project

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;

import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.EventChannel;
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.plugins.GeneratedPluginRegistrant;

public class MainActivity extends FlutterActivity {
private final String eventString = “event”;
private static final String TAG = “MainActivity”;
private static final String CHANNEL = “samples.flutter.io/getLocation”;
private static final String eventChannel = “com.example.my_project/event”;
private MethodChannel channel;
// 后台服务器地址
String host = null;

String locationText;
Double longitude, latitude;
static User user = new User("", “”);

private static MapView mapView;
private static BaiduMap mBaiduMap;
private LocationClient mLocationClient;
private static String myId = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
mapView = new MapView(this);
MapRegistrant.registerWith(this, mapView);

//定位初始化
mLocationClient = new LocationClient(this);
//注册LocationListener监听器
MyLocationListener myLocationListener = new MyLocationListener();
mLocationClient.registerLocationListener(myLocationListener);

// 不显示百度地图Logo
mapView.removeViewAt(1);
mBaiduMap = mapView.getMap();
// 改变地图状态,使地图显示在恰当的缩放大小
mMapStatus = new MapStatus.Builder().zoom(18.0f).build();
MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
mBaiduMap.setMapStatus(mMapStatusUpdate);
mBaiduMap.setMyLocationEnabled(true);

mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
MyLocationConfiguration.LocationMode.FOLLOWING, true, null));

//实例化UiSettings类对象
UiSettings mUiSettings = mBaiduMap.getUiSettings();
//禁用地图旋转功能,启用后对显示屏幕范围内的Marker有一定影响
mUiSettings.setRotateGesturesEnabled(false);
//禁用地图俯视功能
mUiSettings.setOverlookingGesturesEnabled(false);

new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
new MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, Result result) {
// 在这个回调里处理从Flutter来的调用
switch (call.method) {
case “getLocationDics”:
if (locationText == “”) {
result.success(“地球的某一个角落”);
break;
}
result.success(locationText);
break;
case “getLocationLongitude”:
result.success(longitude);
break;
case “getLocationLatitue”:
result.success(latitude);
break;
case “refrashMap”:
if (user.getUserId() != “”) {
mapView.onResume();
if(!isFirstMapRender) {
UpdateMapState();
}
Log.d(“tag”, call.arguments.toString());
result.success(null);
}
break;
case “setUserId”:
mapView.onResume();
user.setUserId(call.arguments.toString());
result.success(null);
break;
case “setUserToken”:
user.setToken(call.arguments.toString());
result.success(null);
break;
case “openGps”:
addEmojiMarkers();
addUserTagBitMaps();
addUserTagBitMaps_Personal();
requestLocation();
result.success(null);
break;
}
}
}
);

//设置地图渲染完成回调
mBaiduMap.setOnMapRenderCallbadk(renderCallback);
//设置地图状态监听
mBaiduMap.setOnMapStatusChangeListener(listener);
}

new EventChannel(getFlutterView(), eventChannel).setStreamHandler(
new EventChannel.StreamHandler() {
@Override
public void onListen(Object args, final EventChannel.EventSink events) {
Log.d(TAG, “adding listener”);
mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
events.success(eventString);// 发送事件(eventString);
}
return true;
}
});
}
@Override
public void onCancel(Object args) {
Log.d(TAG, “cancelling listener”);
}
}
);

BaiduMap.OnMapRenderCallback renderCallback = new BaiduMap.OnMapRenderCallback() {
/**

  • 地图渲染完成回调函数
    */
    @Override
    public void onMapRenderFinished() {
    if(isFirstMapRender) {
    Log.d(“OnMapRenderCallback”,“地图首次渲染完成回调函数”);
    “cancelling listener”);
    }
    }
    );

BaiduMap.OnMapRenderCallback renderCallback = new BaiduMap.OnMapRenderCallback() {
/**

  • 地图渲染完成回调函数
    */
    @Override
    public void onMapRenderFinished() {
    if(isFirstMapRender) {
    Log.d(“OnMapRenderCallback”,“地图首次渲染完成回调函数”);

标签:baidu,交互,void,new,import,Android,com,Flutter,android
来源: https://blog.csdn.net/m0_65145113/article/details/121886417

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有