草庐IT

Android集成高德定位SDK

SeekLife0 2023-03-28 原文

参考入门指南: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的更多相关文章

  1. ruby - 我可以使用 aws-sdk-ruby 在 AWS S3 上使用事务性文件删除/上传吗? - 2

    我发现ActiveRecord::Base.transaction在复杂方法中非常有效。我想知道是否可以在如下事务中从AWSS3上传/删除文件:S3Object.transactiondo#writeintofiles#raiseanexceptionend引发异常后,每个操作都应在S3上回滚。S3Object这可能吗?? 最佳答案 虽然S3API具有批量删除功能,但它不支持事务,因为每个删除操作都可以独立于其他操作成功/失败。该API不提供任何批量上传功能(通过PUT或POST),因此每个上传操作都是通过一个独立的API调用完成的

  2. ruby-on-rails - 如何使辅助方法在 Rails 集成测试中可用? - 2

    我在app/helpers/sessions_helper.rb中有一个帮助程序文件,其中包含一个方法my_preference,它返回当前登录用户的首选项。我想在集成测试中访问该方法。例如,这样我就可以在测试中使用getuser_path(my_preference)。在其他帖子中,我读到这可以通过在测试文件中包含requiresessions_helper来实现,但我仍然收到错误NameError:undefinedlocalvariableormethod'my_preference'.我做错了什么?require'test_helper'require'sessions_hel

  3. ruby-on-rails - 我如何将 Hoptoad 与 DelayedJob 和 DaemonSpawn 集成? - 2

    我一直很高兴地使用DelayedJob习惯用法:foo.send_later(:bar)这会调用DelayedJob进程中对象foo的方法bar。我一直在使用DaemonSpawn在我的服务器上启动DelayedJob进程。但是...如果foo抛出异常,Hoptoad不会捕获它。这是任何这些包中的错误...还是我需要更改某些配置...或者我是否需要在DS或DJ中插入一些异常处理来调用Hoptoad通知程序?回应下面的第一条评论。classDelayedJobWorker 最佳答案 尝试monkeypatchingDelayed::W

  4. 「Python|Selenium|场景案例」如何定位iframe中的元素? - 2

    本文主要介绍在使用Selenium进行自动化测试或者任务时,对于使用了iframe的页面,如何定位iframe中的元素文章目录场景描述解决方案具体代码场景描述当我们在使用Selenium进行自动化测试的时候,可能会遇到一些界面或者窗体是使用HTML的iframe标签进行承载的。对于iframe中的标签,如果直接查找是无法找到的,会抛出没有找到元素的异常。比如近在咫尺的例子就是,CSDN的登录窗体就是使用的iframe,大家可以尝试通过F12开发者模式查看到的tag_name,class_name,id或者xpath来定位中的页面元素,会抛出NoSuchElementException异常。解决

  5. jenkins部署1--jenkins+gitee持续集成 - 2

    前置步骤我们都操作完了,这篇开始介绍jenkins的集成。话不多说,看操作1、登录进入jenkins后会让你选择安装插件,选择第一个默认的就行。安装完成后设置账号密码,重新登录。2、配置JDK和Git都需要执行路径,所以需要先把执行路径找到,先进入服务器的docker容器,2.1JDK的路径root@69eef9ee86cf:/usr/bin#echo$JAVA_HOME/usr/local/openjdk-82.2Git的路径root@69eef9ee86cf:/#whichgit/usr/bin/git3、先配置JDK和Git。点击:ManageJenkins>>GlobalToolCon

  6. 安卓apk修改(Android反编译apk) - 2

    最近因为项目需要,需要将Android手机系统自带的某个系统软件反编译并更改里面某个资源,并重新打包,签名生成新的自定义的apk,下面我来介绍一下我的实现过程。APK修改,分为以下几步:反编译解包,修改,重打包,修改签名等步骤。安卓apk修改准备工作1.系统配置好JavaJDK环境变量2.需要root权限的手机(针对系统自带apk,其他软件免root)3.Auto-Sign签名工具4.apktool工具安卓apk修改开始反编译本文拿Android系统里面的Settings.apk做demo,具体如何将apk获取出来在此就不过多介绍了,直接进入主题:按键win+R输入cmd,打开命令窗口,并将路

  7. 三分钟集成 TapTap 防沉迷 SDK(Unity 版) - 2

    三分钟集成Tap防沉迷SDK(Unity版)一、SDK介绍基于国家对上线所有游戏必须增加防沉迷功能的政策下,TapTap推出防沉迷SDK,供游戏开发者进行接入;允许未成年用户在周五、六、日以及法定节假日晚上8:00-9:00进行游戏,防沉谜时间段进入游戏会弹窗进行提示!开发环境要求:Unity2019.4或更高版本iOS10或更高版本Android5.0(APIlevel21)或更高版本🔗Unity集成Demo参考链接🔗UnityTapSDK功能体验APK下载链接二、集成前准备1.创建应用进入开发者后台,按照提示开始创建应用;2.开通服务在使用TDS实名认证和防沉迷服务之前,需要在上面创建的应

  8. ruby - 如何使用适用于 ruby​​ 的 aws sdk 创建 route53 记录集? - 2

    EC2会在实例停止然后重新启动时为其提供新的IP地址,因此我需要能够自动管理route53记录集,以便我可以一致地访问内容。遗憾的是,sdk的route53部分的文档远不如ec2的文档那么健壮(可以理解),所以我有点卡住了。到目前为止,从我所看到的情况来看,似乎change_resource_record_sets(link)是可行的方法,但我对:chages需要什么感到困惑>因为它提到了一个Change对象,但没有提供指向所述对象描述的链接。这是我的代码目前的样子:r53.client.change_resource_record_sets(:hosted_zone_id=>'MY_

  9. ruby-on-rails - RailsTutorial - 第 8.4.3 章 - 在集成测试中添加用户后未清除测试数据库 - 2

    我被这个难住了。到目前为止教程中的一切都进行得很顺利,但是当我将这段代码添加到我的/spec/requests/users_spec.rb文件中时,事情开始变得糟糕:describe"success"doit"shouldmakeanewuser"dolambdadovisitsignup_pathfill_in"Name",:with=>"ExampleUser"fill_in"Email",:with=>"ryan@example.com"fill_in"Password",:with=>"foobar"fill_in"Confirmation",:with=>"foobar"cl

  10. ruby-on-rails - 将 Angular JS 与 Rails 集成 - 2

    我需要一些指导来了解如何将Angular整合到rails中。选择Rails的原因:我喜欢他们偏执的做事方式。还有迁移,gem真的很酷。使用angular的原因:我正在研究和寻找最适合SPA的框架。Backbone似乎太抽象了。我不得不在Angular和Ember之间做出选择。我首先开始阅读Angular,它对我来说很有意义。所以我从来没有去读过关于ember的文章。使用Angular和Rails的原因:我研究并尝试使用小型框架,例如grape、slim(是的,我也使用php)。但我觉得需要坚持项目的长期范围。我个人喜欢用Rails的方式做事。这就是我需要帮助的地方,我在Rails4中有

随机推荐