美文网首页读书点点
Android集成高德定位SDK

Android集成高德定位SDK

作者: SeekLife0 | 来源:发表于2022-04-14 11:31 被阅读0次

参考入门指南:https://lbs.amap.com/api/android-location-sdk/gettingstarted

1、获取高德key

参考:https://lbs.amap.com/api/android-location-sdk/guide/create-project/get-key/

(1)、高德SDK控制台,点击我的应用

image.png

(2)、右上角点击创建应用

随便填写一个应用名称,以及选择一个应用类型,然后创建


image.png

(3)、点击添加

image.png

(4)、创建新KEY

点击如何获取,得到对应的SHA1填入即可,高德自己教程已经很详细出此处不再赘述。


image.png

2、集成高德定位功能

(1)、集成SDK

参考:https://lbs.amap.com/api/android-location-sdk/guide/create-project/android-studio-create-project

(2)、使用

自己创建了一个工具类,把定位代码放入其中
后台定位参考(实践之后发现没用,不知道是什么问题,暂时没实现后台定位的功能):https://lbs.amap.com/api/android-location-sdk/guide/utilities/permision_8

public class AMapLocationUtils {

    private static int locateTimes = 0;

    //声明AMapLocationClient类对象
    private static AMapLocationClient mLocationClient = null;
    private static AMapLocationClientOption mOption = null;

    public static boolean isSartLocation = false;

    public static void startLocate(Context mContext){

        try{
            Application appContext = BaseApp.getApp();
            AMapLocationClient.updatePrivacyShow(appContext,true,true);
            AMapLocationClient.updatePrivacyAgree(appContext,true);
            mOption = new AMapLocationClientOption();
            //初始化定位
            mLocationClient.setLocationOption(mOption);

            mLocationClient = new AMapLocationClient(appContext);
            //异步获取定位结果
            AMapLocationListener mAMapLocationListener = new AMapLocationListener(){
                @Override
                public void onLocationChanged(AMapLocation amapLocation) {
                    if (amapLocation != null) {
//                        locateTimes ++;
                        if (amapLocation.getErrorCode() == 0) {
                            LocationBean info = new LocationBean();
                            //解析定位结果
                            info.setCity(amapLocation.getCity());
                            info.setProvince(amapLocation.getProvince());
                            info.setDistrict(amapLocation.getDistrict());
                            info.setCode(amapLocation.getCityCode());
                            Log.e("省:",amapLocation.getProvince() + "");
                            Log.e("市:",amapLocation.getCity() + "");
                            Log.e("区:",amapLocation.getDistrict() + "");
                            Log.e("城市编码 + 装修服务:",amapLocation.getCityCode() + "");
                            //定位完成之后更新数据,去查本地db文件得到id
                            //DBManager dbManager = new DBManager(mContext);
                            //LocatedCity locatedCity = dbManager.getLocatedCity(info.getDistrict()).get(0); //new LocatedCity(info.getDistrict(), info.getProvince(), "101240701")
//                            Log.e("测试是否获取的code","code->"+locatedCity.getCode());
                            //CityPicker.from((FragmentActivity) mContext).locateComplete(locatedCity, LocateState.SUCCESS);
                            AppSharedPreferences.getInstance(mContext).set("district",info.getDistrict());
                            AppSharedPreferences.getInstance(mContext).set("city",info.getCity());
                            AppSharedPreferences.getInstance(mContext).set("code",locatedCity.getCode());
                        }else{
                            Log.e("高德地图调试:","错误码" + amapLocation.getErrorCode() + "");
                            Log.e("高德地图调试:","错误信息" + amapLocation.getErrorInfo() + "");
                            Log.e("高德地图调试:","错误描述" + amapLocation.getLocationDetail() + "");
                        }
                    }else{
                        ToastUtils.showShort("定位失败 ");
                    }
                    //停止定位
                    stopLocation();
                }
            };
            //设置定位回调监听
            mLocationClient.setLocationListener(mAMapLocationListener);
            //启动定位
            mLocationClient.startLocation();
            isSartLocation = true;
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public static void bindLocate(Context mContext, View v){

        try{
            Application appContext = BaseApp.getApp();
            AMapLocationClient.updatePrivacyShow(appContext,true,true);
            AMapLocationClient.updatePrivacyAgree(appContext,true);
            //初始化定位
            mLocationClient = new AMapLocationClient(appContext);
            //异步获取定位结果
            AMapLocationListener mAMapLocationListener = new AMapLocationListener(){
                @Override
                public void onLocationChanged(AMapLocation amapLocation) {
                    if (amapLocation != null) {
                        if (amapLocation.getErrorCode() == 0) {
                            LocationBean info = new LocationBean();
                            //解析定位结果
                            info.setCity(amapLocation.getCity());
                            info.setProvince(amapLocation.getProvince());
                            info.setDistrict(amapLocation.getDistrict());
                            info.setCode(amapLocation.getCityCode());
//                            Log.e("省:",amapLocation.getProvince() + "");
//                            Log.e("市:",amapLocation.getCity() + "");
//                            Log.e("区:",amapLocation.getDistrict() + "");
//                            Log.e("城市编码 + 首页:",amapLocation.getCityCode() + "");
                            //定位完成之后更新数据
//                            TextView text = (TextView) v;
                            ((TextView) v).setText(info.getDistrict());
//                            CityPicker.from((FragmentActivity) mContext).locateComplete(new LocatedCity(info.getDistrict(), info.getProvince(), "101240701"), LocateState.SUCCESS);
                            //定位完成之后更新数据,去查本地db文件得到id
                            //DBManager dbManager = new DBManager(mContext);
                            //LocatedCity locatedCity = dbManager.getLocatedCity(info.getDistrict()).get(0);
//                            Log.e("测试是否获取的code","code->"+locatedCity.getCode());
                            AppSharedPreferences.getInstance(mContext).set("district",info.getDistrict());
                            AppSharedPreferences.getInstance(mContext).set("city",info.getCity());
                            AppSharedPreferences.getInstance(mContext).set("code",locatedCity.getCode());
                        }else{
                            Log.e("高德地图调试:","错误码" + amapLocation.getErrorCode() + "");
                            Log.e("高德地图调试:","错误信息" + amapLocation.getErrorInfo() + "");
                            Log.e("高德地图调试:","错误描述" + amapLocation.getLocationDetail() + "");
                        }
                    }else{
                        ToastUtils.showShort("定位失败 ");
                    }
//                    //停止定位
//                    stopLocation();
                }
            };
            //设置定位回调监听
            mLocationClient.setLocationListener(mAMapLocationListener);
            //启动定位
            mLocationClient.startLocation();
            isSartLocation = true;
        }catch (Exception e){
            e.printStackTrace();
        }

    }


----------------------------以下代码是创建后台定位通知栏的,可以不用-------------------------

    /**
     * 获取客户的
     */
    public static AMapLocationClient getClient(){
        return mLocationClient;
    }

    /**
     * 停止定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private static void stopLocation(){
        try {
            // 停止定位
            mLocationClient.stopLocation();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 销毁定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    public static void destroyLocation(){
        if (null != mLocationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的,
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            mLocationClient.onDestroy();
            mLocationClient = null;
            mLocationClient = null;
        }
        isSartLocation = false;
    }

    public static final int NOTIFY_ID = 2001;
    private static final String NOTIFICATION_CHANNEL_NAME = "AMapBackgroundLocation";
    private static NotificationManager notificationManager = null;
    private static boolean isCreatedChannel = false;

    /**
     * 创建一个通知栏,API>=26时才有效
     * @param context
     * @return
     */
    public static Notification buildNotification(Context context) {
        try {
            Context mContext = context.getApplicationContext();
            Notification.Builder builder = null;
            Notification notification = null;
            if (android.os.Build.VERSION.SDK_INT >= 26) {
                //Android O上对Notification进行了修改,如果设置的targetSDKVersion>=26建议使用此种方式创建通知栏
                if (null == notificationManager) {
                    notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
                }
                String channelId = mContext.getPackageName();
                if (!isCreatedChannel) {
                    NotificationChannel notificationChannel = new NotificationChannel(channelId,
                            NOTIFICATION_CHANNEL_NAME,
                            NotificationManager.IMPORTANCE_DEFAULT);
                    notificationChannel.enableLights(true);//是否在桌面icon右上角展示小圆点
                    notificationChannel.setLightColor(Color.BLUE); //小圆点颜色
                    notificationChannel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
                    notificationManager.createNotificationChannel(notificationChannel);
                    isCreatedChannel = true;
                }
                builder = new Notification.Builder(mContext, channelId);
            } else {
                builder = new Notification.Builder(mContext);
            }

            builder.setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(getAppName(mContext))
                    .setContentText("正在后台运行")
                    .setWhen(System.currentTimeMillis());

            notification = builder.build();
            return notification;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取app的名称
     * @param context
     * @return
     */
    public static String getAppName(Context context) {
        String appName = "";
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            appName =  context.getResources().getString(labelRes);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return appName;
    }

}

缓存工具类

public class AppSharedPreferences {

    private SharedPreferences sharedPreferences;
    private static AppSharedPreferences appSharedPreferences;

    private AppSharedPreferences(Context context) {
        sharedPreferences = context.getSharedPreferences("information", Activity.MODE_PRIVATE);
    }

    public static AppSharedPreferences getInstance(Context context) {
        if (null == appSharedPreferences) {
            appSharedPreferences = new AppSharedPreferences(context);
        }
        return appSharedPreferences;
    }

    public String get(String key) {
        if (null == sharedPreferences) {
            return "";
        }
        String result = sharedPreferences.getString(key, null);
        if (!TextUtils.isEmpty(result)) {
            return result;
        }
        return null;
    }


    public boolean getBoolen(String key){
        if (null == sharedPreferences) {
            return false;
        }
        boolean result = sharedPreferences.getBoolean(key, false);
        return result;
    }

    public int getInt(String key) {
        if (null == sharedPreferences) {
            return -1;
        }
        int result = sharedPreferences.getInt(key, -1);
        return result;
    }
    public String getToken(){
        if (null == sharedPreferences) {
            return null;
        }
        String result = sharedPreferences.getString(Constant.TOKEN, null);
        return result;
    }

    public String getInviteCode(){
        if (null == sharedPreferences) {
            return null;
        }
        String result = sharedPreferences.getString(Constant.INVITECODE, null);
        return result;
    }



    public boolean getLoginStatus(){
        if (null == sharedPreferences) {
            return false;
        }
        boolean b = sharedPreferences.getBoolean(Constant.ISLOGIN, false);
        return b;
    }

    public boolean getIsFirst(){
        if (null == sharedPreferences) {
            return true;
        }
        boolean b = sharedPreferences.getBoolean(Constant.ISFIRST, true);
        return b;
    }


    public void set(String key, String value) {
        if (null != sharedPreferences) {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString(key, value);
            editor.apply();
        }
    }
    public void set(String key, int value) {
        if (null != sharedPreferences) {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putInt(key, value);
            editor.apply();
        }
    }
    public void set(String key, boolean value) {
        if (null != sharedPreferences) {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putBoolean(key, value);
            editor.apply();
        }
    }

    public void remove(String... key) {
        for (String k : key) {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.remove(k);
            editor.apply();
        }
    }

    public void clear(){
        if (null != sharedPreferences) {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            Map<String, ?> all = sharedPreferences.getAll();
            for (String key : all.keySet()) {
                    editor.remove(key);
            }
            editor.apply();
        }
    }

}

相关文章

网友评论

    本文标题:Android集成高德定位SDK

    本文链接:https://www.haomeiwen.com/subject/inltertx.html