android之使用百度地图(1)
实现功能:
定位自己的位置
Activity_main.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:orientation="vertical" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent"> 6 7 <TextView 8 android:layout_width="wrap_content" 9 android:layout_height="wrap_content" 10 android:id="@+id/tv_positionTextView"/> 11 12 </LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="acticitytest.exapmle.com.lbstest"> <!-- 这个权限用于进行网络定位--> <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.READ_PHONE_STATE"/> <!--写入拓展存储,向拓展卡写入数据--> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <!--访问网络,因为网络定位需要上网--> <uses-permission android:name="android.permission.INTERNET"/> <!--SD卡读取权限--> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <!--允许用户读取低级别的系统日志--> <uses-permission android:name="android.permission.WAKE_LOCK"/> <application 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"> <meta-data android:name="com.baidu.lbsapi.API_KEY" android:value="SvxVofWKmGx9PaizUrIk3q4TSaxlUv4A"/> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name="com.baidu.location.f" android:enabled="true" android:process=":remote"> </service> </application> </manifest>
MainActivity.java
1 package acticitytest.exapmle.com.lbstest; 2 3 import android.Manifest; 4 import android.content.pm.PackageManager; 5 import android.support.annotation.NonNull; 6 import android.support.v4.app.ActivityCompat; 7 import android.support.v4.content.ContextCompat; 8 import android.support.v7.app.AppCompatActivity; 9 import android.os.Bundle; 10 import android.widget.TextView; 11 import android.widget.Toast; 12 13 import com.baidu.location.BDLocation; 14 import com.baidu.location.BDLocationListener; 15 import com.baidu.location.LocationClient; 16 import com.baidu.location.LocationClientOption; 17 18 import java.util.ArrayList; 19 import java.util.List; 20 21 public class MainActivity extends AppCompatActivity { 22 public LocationClient mLocationClient; 23 private TextView postionText; 24 25 @Override 26 protected void onCreate(Bundle savedInstanceState) { 27 super.onCreate(savedInstanceState); 28 setContentView(R.layout.activity_main); 29 mLocationClient=new LocationClient(getApplicationContext()); 30 mLocationClient.registerLocationListener(new MyLocationListener()); 31 setContentView(R.layout.activity_main); 32 postionText=(TextView)findViewById(R.id.tv_positionTextView); 33 List<String> permissionList=new ArrayList<>(); 34 if(ContextCompat.checkSelfPermission(MainActivity.this, 35 Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){ 36 permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION); 37 } 38 if(ContextCompat.checkSelfPermission(MainActivity.this, 39 Manifest.permission.READ_PHONE_STATE)!=PackageManager.PERMISSION_GRANTED){ 40 permissionList.add(Manifest.permission.READ_PHONE_STATE); 41 } 42 if(ContextCompat.checkSelfPermission(MainActivity.this, 43 Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){ 44 permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); 45 } 46 if(!permissionList.isEmpty()){ 47 String [] permissions=permissionList.toArray(new String[permissionList.size()]); 48 ActivityCompat.requestPermissions(MainActivity.this,permissions,1); 49 }else{ 50 requestLocation(); 51 } 52 } 53 54 public void requestLocation(){ 55 initLocation(); 56 mLocationClient.start();//开始定位 57 } 58 /**用于更新位置信息*/ 59 private void initLocation(){ 60 LocationClientOption option=new LocationClientOption(); 61 option.setScanSpan(5000);//每五秒更新当前位置 62 option.setIsNeedAddress(true); 63 mLocationClient.setLocOption(option); 64 } 65 66 @Override 67 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { 68 switch (requestCode){ 69 case 1: 70 if(grantResults.length>0){ 71 for (int result :grantResults){ 72 if (result!=PackageManager.PERMISSION_GRANTED){ 73 Toast.makeText(this,"必须同意所有权限才能使用本程序",Toast.LENGTH_SHORT).show(); 74 finish(); 75 return; 76 } 77 } 78 requestLocation(); 79 }else{ 80 Toast.makeText(this,"未知错误",Toast.LENGTH_SHORT).show(); 81 finish(); 82 } 83 break; 84 default: 85 break; 86 } 87 } 88 89 public class MyLocationListener implements BDLocationListener{ 90 @Override 91 public void onReceiveLocation(BDLocation bdLocation) { 92 StringBuilder currentPostion =new StringBuilder(); 93 currentPostion.append("纬度:").append(bdLocation.getLatitude()).append("\n"); 94 currentPostion.append("经度:").append(bdLocation.getLongitude()).append("\n"); 95 currentPostion.append("国家:").append(bdLocation.getCountry()).append("\n"); 96 currentPostion.append("省份:").append(bdLocation.getProvince()).append("\n"); 97 currentPostion.append("区:").append(bdLocation.getCity()).append("\n"); 98 currentPostion.append("定位方式:"); 99 if (bdLocation.getLocType()==BDLocation.TypeGpsLocation){ 100 currentPostion.append("GPS"); 101 }else if(bdLocation.getLocType()==BDLocation.TypeNetWorkLocation){ 102 currentPostion.append("网络"); 103 }else{ 104 currentPostion.append("未识别"); 105 } 106 postionText.setText(currentPostion); 107 } 108 } 109 110 @Override 111 protected void onDestroy() { 112 super.onDestroy(); 113 mLocationClient.stop();//不断更新时一定要注意,在活动销毁时关闭,否则会一直耗电 114 } 115 }
依赖:bulid.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId "acticitytest.exapmle.com.lbstest"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets{
main(){
jniLibs.srcDirs=['libs']
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
compile files('libs/BaiduLBS_Android.jar')
}