Các skill bao gồm tích hợp SDK, xây dựng flow và paywall, kiểm tra trước khi phát hành, di chuyển placement và nhiều hơn nữa. Mô tả công việc bằng ngôn ngữ thường ngày và agent sẽ chọn skill phù hợp.
Làm theo hướng dẫn này để tích hợp bản đồ tương tác vào một flow. Bản đồ hiển thị các địa điểm của bạn, chẳng hạn như các trung tâm thể dục đối tác, trong phạm vi 2 km tính từ vị trí người dùng. Ứng dụng của bạn render bản đồ dưới dạng native view trong một phần tử tùy chỉnh, sử dụng MapLibre. Ứng dụng sẽ yêu cầu quyền truy cập vị trí ngay trên màn hình flow.
Trước khi bắt đầu
Cập nhật ứng dụng lên Adapty Android SDK 4.4 trở lên. Các phiên bản SDK cũ hơn sẽ hiển thị nội dung dự phòng cho mọi phần tử tùy chỉnh.
Để yêu cầu người dùng cấp quyền truy cập vị trí, hãy hiển thị flow trong một activity kế thừa từ ComponentActivity, chẳng hạn như AppCompatActivity.
Thêm MapLibre vào ứng dụng bằng Gradle, từ org.maplibre.gl:android-sdk-opengl. Với artifact này, Google Play cũng cung cấp ứng dụng của bạn cho các thiết bị không có Vulkan — đây là yêu cầu của artifact android-sdk mặc định.
Đặt minSdk ở mức 23 hoặc cao hơn, vì MapLibre yêu cầu như vậy.
Để giới hạn ứng dụng chỉ sử dụng vị trí gần đúng, hãy thêm đoạn sau vào bên trong phần tử <manifest> của AndroidManifest.xml. Đảm bảo rằng phần tử <manifest> đã khai báo xmlns:tools="http://schemas.android.com/tools".
Height: Giữ nguyên chiều cao mặc định Fixed. Bản đồ sẽ lấp đầy phần tử tùy chỉnh.
Đặt phần tử tùy chỉnh ngoài các container phản hồi thao tác chạm, chẳng hạn như carousel, để chỉ bản đồ phản hồi khi người dùng kéo trên nó.
Bên trong phần tử tùy chỉnh, thêm một Image với hình ảnh bản đồ. Người dùng sẽ thấy ảnh này như là nội dung dự phòng khi:
Phiên bản ứng dụng của họ không hiển thị được bản đồ.
Họ đã từ chối quyền truy cập vị trí trước khi màn hình mở ra.
Nếu người dùng chưa trả lời lời nhắc quyền truy cập vị trí, ứng dụng sẽ hiển thị lời nhắc đó khi bản đồ xuất hiện. Để cho người dùng biết tại sao ứng dụng cần vị trí của họ, hãy thêm một phần tử văn bản phía trên phần tử tùy chỉnh, ví dụ: “Tìm trung tâm thể dục gần bạn.”
2. Tạo map view
Tạo một kiểu dữ liệu cho các địa điểm của bạn và một model để truy cập vị trí:
// a place of your app, such as a partner fitness centerdata class Place(val name: String, val latitude: Double, val longitude: Double)private const val PERMISSION = Manifest.permission.ACCESS_COARSE_LOCATION // approximate location// one location access model for the resolver and the map viewclass LocationAccess(context: Context) { private val appContext = context.applicationContext // checkSelfPermission returns the same value before the first request and after a denial: save the answer private val answers = appContext.getSharedPreferences("location_access", Context.MODE_PRIVATE) private var isAsking = false var isMapOnScreen = false val isAllowed: Boolean get() = ContextCompat.checkSelfPermission(appContext, PERMISSION) == PackageManager.PERMISSION_GRANTED val isDenied: Boolean get() = !isAllowed && answers.getBoolean("denied", false) // requests location access and saves the answer // unregister the returned launcher when the view leaves the screen fun requestAccess(activity: ComponentActivity, onAnswer: (Boolean) -> Unit): ActivityResultLauncher<String> { val isPromptOpen = isAsking // after a screen rotation, this request receives the answer from the open prompt val request = activity.activityResultRegistry.register("location_access", RequestPermission()) { granted -> isAsking = false answers.edit().putBoolean("denied", !granted).apply() onAnswer(granted) } if (!isPromptOpen) { isAsking = true request.launch(PERMISSION) } return request }}// the activity that shows the flowtailrec fun Context.findComponentActivity(): ComponentActivity = this as? ComponentActivity ?: (this as ContextWrapper).baseContext.findComponentActivity()
// a place of your app, such as a partner fitness centerpublic class Place { public final String name; public final double latitude; public final double longitude; public Place(String name, double latitude, double longitude) { this.name = name; this.latitude = latitude; this.longitude = longitude; }}// one location access model for the resolver and the map viewpublic class LocationAccess { private static final String PERMISSION = Manifest.permission.ACCESS_COARSE_LOCATION; // approximate location private final Context appContext; // checkSelfPermission returns the same value before the first request and after a denial: save the answer private final SharedPreferences answers; private boolean isAsking; public boolean isMapOnScreen; public LocationAccess(Context context) { appContext = context.getApplicationContext(); answers = appContext.getSharedPreferences("location_access", Context.MODE_PRIVATE); } public boolean isAllowed() { return ContextCompat.checkSelfPermission(appContext, PERMISSION) == PackageManager.PERMISSION_GRANTED; } public boolean isDenied() { return !isAllowed() && answers.getBoolean("denied", false); } // requests location access and saves the answer // unregister the returned launcher when the view leaves the screen public ActivityResultLauncher<String> requestAccess(ComponentActivity activity, ActivityResultCallback<Boolean> onAnswer) { boolean isPromptOpen = isAsking; // after a screen rotation, this request receives the answer from the open prompt ActivityResultLauncher<String> request = activity.getActivityResultRegistry().register( "location_access", new RequestPermission(), granted -> { isAsking = false; answers.edit().putBoolean("denied", !granted).apply(); onAnswer.onActivityResult(granted); }); if (!isPromptOpen) { isAsking = true; request.launch(PERMISSION); } return request; } // the activity that shows the flow public static ComponentActivity findComponentActivity(Context context) { while (!(context instanceof ComponentActivity)) { context = ((ContextWrapper) context).getBaseContext(); } return (ComponentActivity) context; }}
Tạo một view với bản đồ. View này yêu cầu quyền truy cập vị trí và hiển thị một marker cho mỗi địa điểm của bạn trong phạm vi 2 km tính từ người dùng:
// map tiles without an API keyconst val MAP_STYLE_URL = "https://tiles.openfreemap.org/styles/liberty"class NearbyFitnessCentersMap( context: Context, private val access: LocationAccess, private val places: List<Place>,) : FrameLayout(context), DefaultLifecycleObserver, LocationEngineCallback<LocationEngineResult> { private val activity = context.findComponentActivity() private val locationEngine = LocationEngineDefault.getDefaultLocationEngine(context) private val mapView: MapView private var permissionRequest: ActivityResultLauncher<String>? = null init { MapLibre.getInstance(context) mapView = MapView(context) mapView.onCreate(null) mapView.getMapAsync { map -> map.setStyle(MAP_STYLE_URL) } addView(mapView) } override fun onAttachedToWindow() { super.onAttachedToWindow() access.isMapOnScreen = true // tells the resolver that the map is on the screen activity.lifecycle.addObserver(this) when { access.isAllowed -> showUser() access.isDenied -> showAccessOff() else -> permissionRequest = access.requestAccess(activity) { granted -> if (granted) showUser() else showAccessOff() } } } override fun onDetachedFromWindow() { access.isMapOnScreen = false permissionRequest?.unregister() locationEngine.removeLocationUpdates(this) activity.lifecycle.removeObserver(this) // the SDK creates a new view each time the custom element appears: release this map mapView.onPause() mapView.onStop() mapView.onDestroy() super.onDetachedFromWindow() } // passes the lifecycle of the activity to the map override fun onStart(owner: LifecycleOwner) = mapView.onStart() override fun onResume(owner: LifecycleOwner) = mapView.onResume() override fun onPause(owner: LifecycleOwner) = mapView.onPause() override fun onStop(owner: LifecycleOwner) = mapView.onStop() @SuppressLint("MissingPermission") // runs only after the user allows location access private fun showUser() = mapView.getMapAsync { map -> map.getStyle { style -> val options = LocationComponentActivationOptions.builder(context, style).locationEngine(locationEngine) map.locationComponent.activateLocationComponent(options.build()) map.locationComponent.isLocationComponentEnabled = true val request = LocationEngineRequest.Builder(1_000).build() // milliseconds between updates locationEngine.requestLocationUpdates(request, this, Looper.getMainLooper()) // calls onSuccess } } // the first location of the user override fun onSuccess(result: LocationEngineResult) { val user = result.lastLocation ?: return locationEngine.removeLocationUpdates(this) showPlaces(user) } override fun onFailure(exception: Exception) = Unit // a teal circle for each of your places within 2 km of the user private fun showPlaces(user: Location) = mapView.getMapAsync { map -> val distance = FloatArray(1) val pins = places.filter { place -> Location.distanceBetween(user.latitude, user.longitude, place.latitude, place.longitude, distance) distance[0] <= 2_000 // meters }.map { place -> Feature.fromGeometry(Point.fromLngLat(place.longitude, place.latitude)) } map.getStyle { style -> style.addSource(GeoJsonSource("places", FeatureCollection.fromFeatures(pins))) val teal = PropertyFactory.circleColor(Color.rgb(0, 128, 128)) style.addLayer(CircleLayer("pins", "places").withProperties(teal, PropertyFactory.circleRadius(8f))) } // zoom in on the area around the user map.animateCamera(CameraUpdateFactory.newLatLngZoom(LatLng(user.latitude, user.longitude), 12.0)) } private fun showAccessOff() { mapView.visibility = GONE addView(TextView(context).apply { text = "Location access is off. To see fitness centers near you, allow location access in Settings." gravity = Gravity.CENTER }) }}
Chế độ xem tải bản đồ từ OpenFreeMap, một dịch vụ miễn phí không cần API key và không có đảm bảo về thời gian hoạt động. Để chuyển sang nguồn tile khác, hãy thay đổi hằng số MAP_STYLE_URL.
public class NearbyFitnessCentersMap extends FrameLayout implements DefaultLifecycleObserver, LocationEngineCallback<LocationEngineResult> { // map tiles without an API key public static final String MAP_STYLE_URL = "https://tiles.openfreemap.org/styles/liberty"; private final LocationAccess access; private final List<Place> places; private final ComponentActivity activity = LocationAccess.findComponentActivity(getContext()); private final LocationEngine locationEngine = LocationEngineDefault.INSTANCE.getDefaultLocationEngine(getContext()); private final MapView mapView; private ActivityResultLauncher<String> permissionRequest; public NearbyFitnessCentersMap(Context context, LocationAccess access, List<Place> places) { super(context); this.access = access; this.places = places; MapLibre.getInstance(context); mapView = new MapView(context); mapView.onCreate(null); mapView.getMapAsync(map -> map.setStyle(MAP_STYLE_URL)); addView(mapView); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); access.isMapOnScreen = true; // tells the resolver that the map is on the screen activity.getLifecycle().addObserver(this); if (access.isAllowed()) showUser(); else if (access.isDenied()) showAccessOff(); else permissionRequest = access.requestAccess(activity, granted -> { if (granted) showUser(); else showAccessOff(); }); } @Override protected void onDetachedFromWindow() { access.isMapOnScreen = false; if (permissionRequest != null) permissionRequest.unregister(); locationEngine.removeLocationUpdates(this); activity.getLifecycle().removeObserver(this); // the SDK creates a new view each time the custom element appears: release this map mapView.onPause(); mapView.onStop(); mapView.onDestroy(); super.onDetachedFromWindow(); } // passes the lifecycle of the activity to the map @Override public void onStart(LifecycleOwner owner) { mapView.onStart(); } @Override public void onResume(LifecycleOwner owner) { mapView.onResume(); } @Override public void onPause(LifecycleOwner owner) { mapView.onPause(); } @Override public void onStop(LifecycleOwner owner) { mapView.onStop(); } @SuppressLint("MissingPermission") // runs only after the user allows location access private void showUser() { mapView.getMapAsync(map -> map.getStyle(style -> { map.getLocationComponent().activateLocationComponent( LocationComponentActivationOptions.builder(getContext(), style).locationEngine(locationEngine).build()); map.getLocationComponent().setLocationComponentEnabled(true); LocationEngineRequest request = new LocationEngineRequest.Builder(1000).build(); // milliseconds between updates locationEngine.requestLocationUpdates(request, this, Looper.getMainLooper()); // calls onSuccess })); } // the first location of the user @Override public void onSuccess(LocationEngineResult result) { Location user = result.getLastLocation(); if (user == null) return; locationEngine.removeLocationUpdates(this); showPlaces(user); } @Override public void onFailure(Exception exception) {} // a teal circle for each of your places within 2 km of the user private void showPlaces(Location user) { List<Feature> pins = new ArrayList<>(); float[] distance = new float[1]; for (Place place : places) { Location.distanceBetween(user.getLatitude(), user.getLongitude(), place.latitude, place.longitude, distance); if (distance[0] > 2000) continue; // meters pins.add(Feature.fromGeometry(Point.fromLngLat(place.longitude, place.latitude))); } mapView.getMapAsync(map -> map.getStyle(style -> { style.addSource(new GeoJsonSource("places", FeatureCollection.fromFeatures(pins))); style.addLayer(new CircleLayer("pins", "places").withProperties( PropertyFactory.circleColor(Color.rgb(0, 128, 128)), PropertyFactory.circleRadius(8f))); // zoom in on the area around the user map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(user.getLatitude(), user.getLongitude()), 12)); })); } private void showAccessOff() { mapView.setVisibility(GONE); TextView message = new TextView(getContext()); message.setText("Location access is off. To see fitness centers near you, allow location access in Settings."); message.setGravity(Gravity.CENTER); addView(message); }}
Chế độ xem tải bản đồ từ OpenFreeMap, một dịch vụ miễn phí không cần API key và không có đảm bảo về uptime. Để chuyển sang nguồn tile khác, thay đổi hằng số MAP_STYLE_URL.
Nếu người dùng từ chối quyền truy cập vị trí trên màn hình, chế độ xem sẽ thay thế bản đồ bằng thông báo hướng dẫn cách cho phép truy cập trong Settings.
3. Khớp map với custom element
Trong resolver toàn app của bạn, hãy thêm các thuộc tính cho model LocationAccess và các địa điểm của bạn. Sau đó trả về map view cho Type map và ID fitness_centers. Các dòng được highlight cho thấy những gì cần thêm hoặc thay đổi. Nếu app của bạn chưa có resolver toàn app, hãy copy toàn bộ code:
class CustomElementsResolver( context: Context, private val places: List<Place>, // your app's places, such as partner fitness centers) : AdaptyCustomElementsResolver { private val locationAccess = LocationAccess(context) override fun resolve(type: String, id: String): AdaptyCustomElementContent? = when (type) { "map" -> when (id) { "fitness_centers" -> if (locationAccess.isDenied && !locationAccess.isMapOnScreen) { null // access denied before the screen opened: show the fallback } else { AdaptyCustomElementContent.view( factory = { context, _ -> NearbyFitnessCentersMap(context, locationAccess, places) }, ) } // the other maps of your resolver else -> null } // the other Types of your resolver else -> null }}
public class CustomElementsResolver implements AdaptyCustomElementsResolver { private final LocationAccess locationAccess; private final List<Place> places; // your app's places, such as partner fitness centers public CustomElementsResolver(Context context, List<Place> places) { this.locationAccess = new LocationAccess(context); this.places = places; } @Override public AdaptyCustomElementContent resolve(String type, String id) { if (type.equals("map")) { if (id.equals("fitness_centers")) { if (locationAccess.isDenied() && !locationAccess.isMapOnScreen) { return null; // access denied before the screen opened: show the fallback } return AdaptyCustomElementContent.view( (context, elementContext) -> new NearbyFitnessCentersMap(context, locationAccess, places) ); } // the other maps of your resolver return null; } // the other Types of your resolver return null; }}
SDK gọi resolver khi màn hình mở, và gọi lại mỗi khi vẽ lại phần tử tùy chỉnh trong khi màn hình đang mở. Quyền truy cập vị trí xác định những gì resolver trả về trong mỗi lần gọi:
Chưa trả lời: Chế độ xem bản đồ, để chế độ xem có thể yêu cầu quyền truy cập.
Đã cho phép: Chế độ xem bản đồ, hiển thị các địa điểm của bạn gần người dùng.
Đã từ chối trước khi màn hình mở: Không có chế độ xem, nên người dùng thấy fallback thay vì thông báo về Settings.
Đã từ chối trên màn hình: Chế độ xem bản đồ, vì chế độ xem đặt isMapOnScreen trong khi nó đang hiển thị. Nếu resolver không trả về chế độ xem ở đây, SDK sẽ thay thế thông báo về Settings bằng fallback ở lần gọi tiếp theo.
Tạo resolver với các phần tử của bạn, rồi đặt nó làm resolver toàn ứng dụng. Gọi AdaptyUI.setCustomElementsResolver một lần duy nhất, chẳng hạn khi khởi động ứng dụng:
class App : Application() { // your app's places, such as partner fitness centers val places = listOf( Place("Central Fitness", latitude = 52.5219, longitude = 13.4132), Place("Riverside Gym", latitude = 52.5163, longitude = 13.3777), ) // keep this instance: a resolver for one flow can reuse it // lazy: the context isn't attached yet while App is constructed val customElementsResolver by lazy { CustomElementsResolver(this, places) } override fun onCreate() { super.onCreate() AdaptyUI.setCustomElementsResolver(customElementsResolver) }}
public class App extends Application { // your app's places, such as partner fitness centers private final List<Place> places = Arrays.asList( new Place("Central Fitness", 52.5219, 13.4132), new Place("Riverside Gym", 52.5163, 13.3777) ); // keep this instance: a resolver for one flow can reuse it private CustomElementsResolver customElementsResolver; @Override public void onCreate() { super.onCreate(); customElementsResolver = new CustomElementsResolver(this, places); AdaptyUI.setCustomElementsResolver(customElementsResolver); } public CustomElementsResolver getCustomElementsResolver() { return customElementsResolver; }}
4. Kiểm thử trên thiết bị
Flow & Paywall Builder không thể chạy mã ứng dụng của bạn, vì vậy canvas chỉ hiển thị fallback. Để xem trước bản đồ:
Xuất bản flow. Để xem phiên bản đã xuất bản mới nhất thay vì phiên bản được lưu trong bộ nhớ đệm, hãy đăng ký thiết bị làm thiết bị kiểm thử.
Để xem một điểm đánh dấu trên bản đồ, hãy thêm một địa điểm trong phạm vi 2 km so với vị trí của bạn vào danh sách địa điểm.
Chạy bản build ứng dụng có bao gồm resolver. Mở màn hình và cho phép truy cập vị trí. Xác minh rằng bản đồ hiển thị vị trí của bạn và điểm đánh dấu cho địa điểm bạn đã thêm.
Để kiểm tra fallback, trong ứng dụng Settings, hãy tắt quyền truy cập vị trí cho ứng dụng của bạn. Mở màn hình, và nếu có hộp thoại xuất hiện, hãy từ chối quyền truy cập vị trí. Chế độ xem bản đồ sẽ hiển thị thông báo về Settings. Mở lại màn hình và kiểm tra xem paywall dự phòng có xuất hiện không.
Để tìm hiểu lý do tại sao paywall dự phòng hiển thị thay vì bản đồ, hãy làm theo hướng dẫn trong phần Kiểm tra trên thiết bị của hướng dẫn Android.