zoukankan      html  css  js  c++  java
  • 获取百度定位

    已经下载Demo的可以直接到第五步,已经配置好的并可以运行的可以直接到第七步。

    1.在浏览器搜索 ” 百度定位API “,点击下面这个链接

    2.翻到最下面找到并点击 ” Android定位SDK “

    3.在左侧导航找到 " 产品下载"

     4.点击DEMO下载,这个DEMO就开始下载了

     5.从文件夹打开并解压

     6.此时的文件还不能用自己的Android Atudio打开,需要配置一些参数

    配置参数教程

    7.可以此时项目能够打开,但是要实现定位功能还需要获取ak鉴权

    从16分56秒开始   ak鉴权获取教程

     获取SHA1代码

    复制代码
    public static String sHA1(Context context) {
                try {
                    PackageInfo info = context.getPackageManager().getPackageInfo(
                            context.getPackageName(), PackageManager.GET_SIGNATURES);
                    byte[] cert = info.signatures[0].toByteArray();
                    MessageDigest md = MessageDigest.getInstance("SHA1");
                    byte[] publicKey = md.digest(cert);
                    StringBuffer hexString = new StringBuffer();
                    for (int i = 0; i < publicKey.length; i++) {
                        String appendString = Integer.toHexString(0xFF & publicKey[i])
                                .toUpperCase(Locale.US);
                        if (appendString.length() == 1)
                            hexString.append("0");
                        hexString.append(appendString);
                        hexString.append(":");
                    }
                    String result = hexString.toString();
                    System.out.println("SHA1:"+result);
                    return result;
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
                return null;
            }
    复制代码

    8.Android Atudio打开文件后就可以正常运行啦

     9.抽取上面提到的功能

    通过MainActivity.java找到需要实现的功能的代码

    然后将lib文件夹、servlet文件夹、LocationService.java、AndroidManifest.xml复制到自己的项目中,调试一下基本就可以运行了。

    10.代码

    MainActivity.java

    复制代码
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.Manifest;
    import android.annotation.TargetApi;
    import android.content.SharedPreferences;
    import android.content.pm.PackageManager;
    import android.os.Build;
    import android.os.Bundle;
    import android.text.method.ScrollingMovementMethod;
    import android.view.View;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.ListView;
    import android.widget.TextView;
    
    import com.baidu.baidulocationdemo.R;
    import com.baidu.location.BDAbstractLocationListener;
    import com.baidu.location.BDLocation;
    import com.baidu.location.Poi;
    import com.baidu.location.PoiRegion;
    import com.example.locationdemo.service.LocationService;
    
    import java.util.ArrayList;
    
    public class MainActivity extends AppCompatActivity {
        private final int SDK_PERMISSION_REQUEST = 127;
        private LocationService locationService;
        private String permissionInfo;
        private TextView LocationResult;
        private Button startLocation;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            // sHA1(this);    //获取AK
            getPersimmions();  //获取定位权限
            LocationResult = (TextView) findViewById(R.id.locationResult);
            startLocation = (Button) findViewById(R.id.startLocation);
            initUiti();
        }
    
        private void initUiti() {
            startLocation.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    locationService.start();
                }
            });
        }
    
        protected void onStart() {
            // TODO Auto-generated method stub
            super.onStart();
            // -----------location config ------------
            locationService = ((LocationApplication) getApplication()).locationService;
            //获取locationservice实例,建议应用中只初始化1个location实例,然后使用,可以参考其他示例的activity,都是通过此种方式获取locationservice实例的
            locationService.registerListener(mListener);
            //注册监听
            int type = getIntent().getIntExtra("from", 0);
            if (type == 0) {
                locationService.setLocationOption(locationService.getDefaultLocationClientOption());
            } else if (type == 1) {
                locationService.start();
            }
            startLocation.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    if (startLocation.getText().toString().equals("开始定位")) {
                        locationService.start();// 定位SDK
                        // start之后会默认发起一次定位请求,开发者无须判断isstart并主动调用request
                        startLocation.setText("停止定位");
                    } else {
                        locationService.stop();
                        startLocation.setText("开始定位");
                    }
                }
            });
        }
    
        /***
         * Stop location service
         */
        @Override
        protected void onStop() {
            // TODO Auto-generated method stub
            locationService.unregisterListener(mListener); //注销掉监听
            locationService.stop(); //停止定位服务
            super.onStop();
        }
    
        private final BDAbstractLocationListener mListener = new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                    if(location.getAddrStr()!=null){
                        LocationResult.setText(location.getAddrStr());
                        locationService.stop();
                    }
                }
            }
        };
    
    
        @TargetApi(23)
        private void getPersimmions() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                ArrayList<String> permissions = new ArrayList<String>();
                /***
                 * 定位权限为必须权限,用户如果禁止,则每次进入都会申请
                 */
                // 定位精确位置
                if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
                }
                if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
                }
                /*
                 * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次,用户同意或者禁止,只会弹一次
                 */
                // 读写权限
                if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny 
    ";
                }
                if (permissions.size() > 0) {
                    requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
                }
            }
        }
    
        @TargetApi(23)
        private boolean addPermission(ArrayList<String> permissionsList, String permission) {
            // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                if (shouldShowRequestPermissionRationale(permission)) {
                    return true;
                } else {
                    permissionsList.add(permission);
                    return false;
                }
            } else {
                return true;
            }
        }
    
        public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
            // TODO Auto-generated method stub
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    
          /* public static String sHA1(Context context) {
                try {
                    PackageInfo info = context.getPackageManager().getPackageInfo(
                            context.getPackageName(), PackageManager.GET_SIGNATURES);
                    byte[] cert = info.signatures[0].toByteArray();
                    MessageDigest md = MessageDigest.getInstance("SHA1");
                    byte[] publicKey = md.digest(cert);
                    StringBuffer hexString = new StringBuffer();
                    for (int i = 0; i < publicKey.length; i++) {
                        String appendString = Integer.toHexString(0xFF & publicKey[i])
                                .toUpperCase(Locale.US);
                        if (appendString.length() == 1)
                            hexString.append("0");
                        hexString.append(appendString);
                        hexString.append(":");
                    }
                    String result = hexString.toString();
                    System.out.println("SHA1:"+result);
                    return result;
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
                return null;
            }
    
            */
    
    
    }
    复制代码

    activity_main.xml

    复制代码
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
        <TextView
            android:id="@+id/locationResult"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
        <Button
            android:id="@+id/startLocation"
            android:text="开始定位"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>
    
    </LinearLayout>
    复制代码

    AndroidManifest.xml

    复制代码
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.baidu.baidulocationdemo">
    
    <!-- 这个权限用于进行网络定位-->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <!-- 这个权限用于访问GPS定位-->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <!-- 用于访问wifi网络信息,wifi信息会用于进行网络定位-->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <!-- 获取运营商信息,用于支持提供运营商信息相关的接口-->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <!-- 这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位-->
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
    <!-- 写入扩展存储,向扩展卡写入数据,用于写入离线定位数据-->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <!-- 访问网络,网络定位需要上网 -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <!-- 允许挂载和反挂载文件系统可移动存储 -->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <!-- 允许程序读取底层系统日志文件 -->
    <uses-permission android:name="android.permission.READ_LOGS"/>
    <!-- 允许访问振动设备 -->
    <uses-permission android:name="android.permission.VIBRATE"/>
    <!-- 允许使用PowerManager的 WakeLocks保持进程在休眠时从屏幕消失 -->
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <!-- 允许程序读取或写入系统设置 -->
    <uses-permission android:name="android.permission.WRITE_SETTINGS"/>
    <!-- android 9.0上使用前台服务,需要添加权限 -->
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <!-- 用于读取手机当前的状态 -->
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <!-- 读取缓存数据 -->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <!-- 获取模拟定位信息 -->
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
    
    <application
        android:requestLegacyExternalStorage="true"
        android:name="com.example.locationdemo.LocationApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <!-- 声明service组件 -->
        <service
            android:name="com.baidu.location.f"
            android:enabled="true"
            android:process=":remote"/>
        <!-- AK鉴权 -->
        <meta-data
            android:name="com.baidu.lbsapi.API_KEY"
            android:value="2N8xydK1CHyShBGxYhMkzTP0jRsVv9Lh" /> <!-- http://lbsyun.baidu.com/apiconsole/key -->
    
        <activity
            android:name="com.example.locationdemo.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    
    </manifest>
    复制代码
  • 相关阅读:
    树状数组
    1424:【例题3】喷水装置
    Matrix (二分套二分
    素数筛
    快速幂
    CentOS6/7-防火墙管理
    Ubuntu15.04 python升级到python-3.6.x
    查看Linux系统用户登录日志
    [shell]查找网段内可用IP地址
    最小化安装Linux的常用配置整理
  • 原文地址:https://www.cnblogs.com/jz-no-bug/p/14907698.html
Copyright © 2011-2022 走看看