The article directories

  • The use of the demo
    • Download autonavi’s demo
    • How to use Autonavi Demo normally
  • Autonavi integration in their own APP, imitation nail nail punch card
  • debugging

The use of the demo

If you want to integrate Autonavi into your own project, the first step is to look at the demo that someone else has written, so first of all

Download autonavi’s demo

Download address

After downloading, there are 4 folders, among which 2DMap contains many functions we usually use

When we run it on our phones, we’ll be prompted to use certain features

This is the SHA1 value problem, we can do the following to temporarily use autonavi demo

How to use Autonavi Demo normally

1. Enter CMD after obtaining the SHA1 value

cd .android
keytool -list -v -keystore debug.keystore
Copy the code

The default password for the debug keystore provided by the compiler is Android



You can obtain the SHA1 value from the information displayed on the console

2. Log in to Autonavi Open Platform

Create an application and add a new key

3. Copy the application key

Fill in the following location in androidmanifest.xml

Then autonavi’s demo can be used normally

Autonavi integration in their own APP, imitation nail nail punch card

1. Add release signature file to Autonavi open platform to obtain the new key according to the above steps. 2. The Android Studio configuration project introduces positioning dependencies

implementation 'com.amap.api:3dmap:latest.integration'
implementation 'com. Amap. API: location: 5.2.0'
Copy the code

For debugging purposes, you can put debug and release in a single signature file

signingConfigs {
        debug {
            storeFile file('.. /app/key.jks')
            storePassword '123456'
            keyAlias "key0"
            keyPassword '123456'
        }
        release {
            storeFile file('.. /app/key.jks')
            storePassword '123456'
            keyAlias "key0"
            keyPassword '123456'}}Copy the code

Build. Gradle applicationId is the same as build.gradle applicationId

// Map pack, search pack need basic permissions<! -- Allows applications to open network sockets --> <uses-permission Android :name="android.permission.INTERNET"/ > <! -- Allows an application to set the built-in SD card write permission --> <uses-permission Android :name="android.permission.WRITE_EXTERNAL_STORAGE"/ > <! -- Allows applications to obtain network status --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/ > <! -- Allows applications to access WiFi network information --> <uses-permission Android :name="android.permission.ACCESS_WIFI_STATE"/ > <! -- Allows applications to read and write phone status and identity --> <uses-permission Android :name="android.permission.READ_PHONE_STATE"/ > <! -- Allows applications to access CellID or WiFi hotspots to get rough locations --> <uses-permission Android :name="android.permission.ACCESS_COARSE_LOCATION" /> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/ > <! -- If target >= is set28You must declare this permission if you want to enable background positioning --> <uses-permission Android :name="android.permission.FOREGROUND_SERVICE"/ > <! -- If your application requires background location permission and is likely to run on an Android Q device with Target > set28You must add this permission declaration --> <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
<application
        android:name=".MyApplication". > <! -- Set key --> <meta-data
            android:name="com.amap.api.v2.apikey"
            android:value="Set the key you just applied for"/ > <! - positioning need service adapter Android Q plus Android: foregroundServiceType ="location"-->
        <service
            android:name="com.amap.api.location.APSService"
            android:foregroundServiceType="location" />
</application>
Copy the code

6. Since we are going to use geo-fencing, we can look at the official demo first, find Amap_Android_API_Location_Demo in the downloaded instance and run it



7. Add the plugin_geofence_map.xml page to your project


      
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <com.amap.api.maps.MapView
            android:id="@+id/map"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
        </com.amap.api.maps.MapView>

		<ScrollView
                android:layout_width="match_parent"
                android:layout_height="60dp"
                android:background="#D999"
                android:layout_alignParentBottom="true">
        <TextView
            android:id="@+id/tv_result"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        </ScrollView>
    </RelativeLayout>

</LinearLayout>
Copy the code

The code just takes the GeoFence_Round_Activity

Where CheckPermissionsActivity checks the following permissions

protected String[] needPermissions = {
			Manifest.permission.ACCESS_COARSE_LOCATION,
			Manifest.permission.ACCESS_FINE_LOCATION,
			Manifest.permission.WRITE_EXTERNAL_STORAGE,
			Manifest.permission.READ_EXTERNAL_STORAGE,
			Manifest.permission.READ_PHONE_STATE
	};
Copy the code
/** * Circular geographic fence **@author hongming.wang
 * @since3.2.0 * /
public class GeoFence_Round_Activity extends CheckPermissionsActivity
		implements
			OnClickListener.GeoFenceListener.OnMapClickListener.LocationSource.AMapLocationListener.OnCheckedChangeListener {

	private View lyOption;
	
	private TextView tvGuide;
	private TextView tvResult;
	
	private EditText etCustomId;
	private EditText etRadius;
	
	private CheckBox cbAlertIn;
	private CheckBox cbAlertOut;
	private CheckBox cbAldertStated;
	
	private Button btAddFence;
	private Button btOption;

	/** * is used to display the current location * 

* in the example to display the current location, in practice, a separate geofencing can be used without the location interface *

*/
private AMapLocationClient mlocationClient; private OnLocationChangedListener mListener; private AMapLocationClientOption mLocationOption; private MapView mMapView; private AMap mAMap; // Center point coordinates private LatLng centerLatLng = null; // Center point marker private Marker centerMarker; private BitmapDescriptor ICON_YELLOW = BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_YELLOW); private BitmapDescriptor ICON_RED = BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_RED); private MarkerOptions markerOption = null; private List<Marker> markerList = new ArrayList<Marker>(); // The current set of coordinates is mainly used for zooming the visible area of the map private LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder(); // Geo-fencing client private GeoFenceClient fenceClient = null; // The radius of the fence to create private float fenceRadius = 0.0 F; // Trigger geofencing action, default to entry alert private int activatesAction = GeoFenceClient.GEOFENCE_IN; // Broadcast action for geofencing private static final String GEOFENCE_BROADCAST_ACTION = "com.example.geofence.round"; // Record that a fence has been successfully added private HashMap<String, GeoFence> fenceMap = new HashMap<String, GeoFence>(); protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_geofence_new); setTitle(R.string.roundGeoFence); // Initialize the geofencing fenceClient = new GeoFenceClient(getApplicationContext()); lyOption = findViewById(R.id.ly_option); btAddFence = (Button) findViewById(R.id.bt_addFence); btOption = (Button) findViewById(R.id.bt_option); tvGuide = (TextView) findViewById(R.id.tv_guide); tvResult = (TextView) findViewById(R.id.tv_result); tvResult.setVisibility(View.GONE); etCustomId = (EditText) findViewById(R.id.et_customId); etRadius = (EditText) findViewById(R.id.et_radius); cbAlertIn = (CheckBox) findViewById(R.id.cb_alertIn); cbAlertOut = (CheckBox) findViewById(R.id.cb_alertOut); cbAldertStated = (CheckBox) findViewById(R.id.cb_alertStated); mMapView = (MapView) findViewById(R.id.map); mMapView.onCreate(savedInstanceState); markerOption = new MarkerOptions().draggable(true); init(); } void init(a) { if (mAMap == null) { mAMap = mMapView.getMap(); mAMap.getUiSettings().setRotateGesturesEnabled(false); mAMap.moveCamera(CameraUpdateFactory.zoomBy(6)); setUpMap(); } btOption.setVisibility(View.VISIBLE); btOption.setText(getString(R.string.hideOption)); resetView_round(); btAddFence.setOnClickListener(this); btOption.setOnClickListener(this); cbAlertIn.setOnCheckedChangeListener(this); cbAlertOut.setOnCheckedChangeListener(this); cbAldertStated.setOnCheckedChangeListener(this); IntentFilter filter = new IntentFilter(); filter.addAction(GEOFENCE_BROADCAST_ACTION); registerReceiver(mGeoFenceReceiver, filter); /** * Create pendingIntent */ fenceClient.createPendingIntent(GEOFENCE_BROADCAST_ACTION); fenceClient.setGeoFenceListener(this); /** * Sets the trigger behavior of geofencing, default is enter */ fenceClient.setActivateAction(GeoFenceClient.GEOFENCE_IN); } /** * Set some amAP attributes */ private void setUpMap(a) { mAMap.setOnMapClickListener(this); mAMap.setLocationSource(this);// Set location listening mAMap.getUiSettings().setMyLocationButtonEnabled(true);// Sets whether the default location button is displayed // Customize the system to locate blue dots MyLocationStyle myLocationStyle = new MyLocationStyle(); // Customize the blue dot icon myLocationStyle.myLocationIcon( BitmapDescriptorFactory.fromResource(R.drawable.gps_point)); // Customize the precision range of the circular border color myLocationStyle.strokeColor(Color.argb(0.0.0.0)); // Customize the width of the circular border within the precision range myLocationStyle.strokeWidth(0); // Set the fill color of the circle myLocationStyle.radiusFillColor(Color.argb(0.0.0.0)); // Add a custom myLocationStyle object to the map mAMap.setMyLocationStyle(myLocationStyle); mAMap.setMyLocationEnabled(true);// Set to true to show the location layer and trigger the location, false to hide the location layer and not trigger the location, the default is false // Set the location mode to location mode, which can be location, follow, or map rotation according to the orientation mAMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE); } The /** * method must be overridden */ @Override protected void onResume(a) { super.onResume(); mMapView.onResume(); } The /** * method must be overridden */ @Override protected void onPause(a) { super.onPause(); mMapView.onPause(); deactivate(); } The /** * method must be overridden */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mMapView.onSaveInstanceState(outState); } The /** * method must be overridden */ @Override protected void onDestroy(a) { super.onDestroy(); mMapView.onDestroy(); try { unregisterReceiver(mGeoFenceReceiver); } catch (Throwable e) { } if (null! = fenceClient) { fenceClient.removeGeoFence(); }if (null != mlocationClient) { mlocationClient.onDestroy(); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.bt_addFence : addFence(); break; case R.id.bt_option : if (btOption.getText().toString() .equals(getString(R.string.showOption))) { lyOption.setVisibility(View.VISIBLE); btOption.setText(getString(R.string.hideOption)); } else { lyOption.setVisibility(View.GONE); btOption.setText(getString(R.string.showOption)); } break; default : break; }}private void drawFence(GeoFence fence) { switch (fence.getType()) { case GeoFence.TYPE_ROUND : case GeoFence.TYPE_AMAPPOI : drawCircle(fence); break; case GeoFence.TYPE_POLYGON : case GeoFence.TYPE_DISTRICT : drawPolygon(fence); break; default : break; } // // sets all maker to display on the current viewable area map // LatLngBounds bounds = boundsBuilder.build(); // mAMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 150)); removeMarkers(); } private void drawCircle(GeoFence fence) { LatLng center = new LatLng(fence.getCenter().getLatitude(), fence.getCenter().getLongitude()); // Draw a circle mAMap.addCircle(new CircleOptions().center(center) .radius(fence.getRadius()).strokeColor(Const.STROKE_COLOR) .fillColor(Const.FILL_COLOR).strokeWidth(Const.STROKE_WIDTH)); boundsBuilder.include(center); } private void drawPolygon(GeoFence fence) { final List<List<DPoint>> pointList = fence.getPointList(); if (null == pointList || pointList.isEmpty()) { return; } for (List<DPoint> subList : pointList) { List<LatLng> lst = new ArrayList<LatLng>(); PolygonOptions polygonOption = new PolygonOptions(); for (DPoint point : subList) { lst.add(new LatLng(point.getLatitude(), point.getLongitude())); boundsBuilder.include( new LatLng(point.getLatitude(), point.getLongitude())); } polygonOption.addAll(lst); polygonOption.strokeColor(Const.STROKE_COLOR) .fillColor(Const.FILL_COLOR).strokeWidth(Const.STROKE_WIDTH); mAMap.addPolygon(polygonOption); } } Object lock = new Object(); void drawFence2Map(a) { new Thread() { @Override public void run(a) { try { synchronized (lock) { if (null == fenceList || fenceList.isEmpty()) { return; } for (GeoFence fence : fenceList) { if (fenceMap.containsKey(fence.getFenceId())) { continue; } drawFence(fence); fenceMap.put(fence.getFenceId(), fence); }}}catch (Throwable e) { } } }.start(); } Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 0 : StringBuffer sb = new StringBuffer(); sb.append("Fencing added successfully"); String customId = (String)msg.obj; if(! TextUtils.isEmpty(customId)){ sb.append("customId: ").append(customId); } Toast.makeText(getApplicationContext(), sb.toString(), Toast.LENGTH_SHORT).show(); drawFence2Map(); break; case 1 : int errorCode = msg.arg1; Toast.makeText(getApplicationContext(), "Failed to add fence" + errorCode, Toast.LENGTH_SHORT).show(); break; case 2 : String statusStr = (String) msg.obj; tvResult.setVisibility(View.VISIBLE); tvResult.append(statusStr + "\n"); break; default : break; }}}; List<GeoFence> fenceList =new ArrayList<GeoFence>(); @Override public void onGeoFenceCreateFinished(final List<GeoFence> geoFenceList, int errorCode, String customId) { Message msg = Message.obtain(); if (errorCode == GeoFence.ADDGEOFENCE_SUCCESS) { fenceList.addAll(geoFenceList); msg.obj = customId; msg.what = 0; } else { msg.arg1 = errorCode; msg.what = 1; } handler.sendMessage(msg); } /** * Receive the broadcast after the trigger fence, when the fence is added successfully, it will immediately detect all the fence status, if the current state is consistent with the trigger behavior set by the user, it will immediately trigger a fence broadcast; * A broadcast is received only after the fence is triggered. A broadcast is sent only once for the same trigger action and will not be repeated unless the relationship between the position and the fence has changed again. * / private BroadcastReceiver mGeoFenceReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Receive broadcasts if (intent.getAction().equals(GEOFENCE_BROADCAST_ACTION)) { Bundle bundle = intent.getExtras(); String customId = bundle .getString(GeoFence.BUNDLE_KEY_CUSTOMID); String fenceId = bundle.getString(GeoFence.BUNDLE_KEY_FENCEID); //status indicates the current status of the fence, not the fence behavior int status = bundle.getInt(GeoFence.BUNDLE_KEY_FENCESTATUS); StringBuffer sb = new StringBuffer(); switch (status) { case GeoFence.STATUS_LOCFAIL : sb.append("Location failure"); break; case GeoFence.STATUS_IN : sb.append("Enter the fence."); break; case GeoFence.STATUS_OUT : sb.append("Get off the fence."); break; case GeoFence.STATUS_STAYED : sb.append("Stay inside the fence."); break; default : break; } if(status ! = GeoFence.STATUS_LOCFAIL){if(! TextUtils.isEmpty(customId)){ sb.append(" customId: " + customId); } sb.append(" fenceId: " + fenceId); } String str = sb.toString(); Message msg = Message.obtain(); msg.obj = str; msg.what = 2; handler.sendMessage(msg); }}};@Override public void onMapClick(LatLng latLng) { markerOption.icon(ICON_YELLOW); centerLatLng = latLng; addCenterMarker(centerLatLng); tvGuide.setBackgroundColor(getResources().getColor(R.color.gary)); tvGuide.setText("Selected coordinates:" + centerLatLng.longitude + "," + centerLatLng.latitude); } /** * Callback function */ after locating successfully @Override public void onLocationChanged(AMapLocation amapLocation) { if(mListener ! =null&& amapLocation ! =null) { if(amapLocation ! =null && amapLocation.getErrorCode() == 0) { tvResult.setVisibility(View.GONE); mListener.onLocationChanged(amapLocation);// Display system small blue dot } else { String errText = "Location failed," + amapLocation.getErrorCode() + ":" + amapLocation.getErrorInfo(); Log.e("AmapErr", errText); tvResult.setVisibility(View.VISIBLE); tvResult.setText(errText); }}}/** * Activate location */ @Override public void activate(OnLocationChangedListener listener) { mListener = listener; if (mlocationClient == null) { mlocationClient = new AMapLocationClient(this); mLocationOption = new AMapLocationClientOption(); // Set location listening mlocationClient.setLocationListener(this); // Set to high-precision positioning mode mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy); // Just to get the current location, so set it to single location mLocationOption.setOnceLocation(true); // Set location parametersmlocationClient.setLocationOption(mLocationOption); mlocationClient.startLocation(); }}/** * stop positioning */ @Override public void deactivate(a) { mListener = null; if(mlocationClient ! =null) { mlocationClient.stopLocation(); mlocationClient.onDestroy(); } mlocationClient = null; } private void addCenterMarker(LatLng latlng) { if (null == centerMarker) { centerMarker = mAMap.addMarker(markerOption); } centerMarker.setPosition(latlng); markerList.add(centerMarker); } private void removeMarkers(a) { if(null! = centerMarker){ centerMarker.remove(); centerMarker =null; } if (null! = markerList && markerList.size() >0) { for(Marker marker : markerList) { marker.remove(); } markerList.clear(); }}@Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { switch (buttonView.getId()) { case R.id.cb_alertIn : if (isChecked) { activatesAction |= GeoFenceClient.GEOFENCE_IN; } else { activatesAction = activatesAction & (GeoFenceClient.GEOFENCE_OUT | GeoFenceClient.GEOFENCE_STAYED); } break; case R.id.cb_alertOut : if (isChecked) { activatesAction |= GeoFenceClient.GEOFENCE_OUT; } else { activatesAction = activatesAction & (GeoFenceClient.GEOFENCE_IN | GeoFenceClient.GEOFENCE_STAYED); } break; case R.id.cb_alertStated : if (isChecked) { activatesAction |= GeoFenceClient.GEOFENCE_STAYED; } else { activatesAction = activatesAction & (GeoFenceClient.GEOFENCE_IN | GeoFenceClient.GEOFENCE_OUT); } break; default : break; } if (null != fenceClient) { fenceClient.setActivateAction(activatesAction); } } private void resetView_round(a) { etRadius.setHint("Radius of fence"); etRadius.setVisibility(View.VISIBLE); tvGuide.setBackgroundColor(getResources().getColor(R.color.red)); tvGuide.setText("Please click on the map to select the center of the fence."); tvGuide.setVisibility(View.VISIBLE); } /** * Add a fence **@since 3.2.0 * @author hongming.wang * */ private void addFence(a) { addRoundFence(); } /** * Add circular fence **@since 3.2.0 * @author hongming.wang * */ private void addRoundFence(a) { String customId = etCustomId.getText().toString(); String radiusStr = etRadius.getText().toString(); if (null == centerLatLng || TextUtils.isEmpty(radiusStr)) { Toast.makeText(getApplicationContext(), "Incomplete parameters", Toast.LENGTH_SHORT) .show(); return; } DPoint centerPoint = newDPoint(centerLatLng.latitude, centerLatLng.longitude); fenceRadius = Float.parseFloat(radiusStr); fenceClient.addGeoFence(centerPoint, fenceRadius, customId); }}Copy the code

debugging

We can test or verify directly on the web:

Autonavi searches for keywords to get coordinates

Other debugging