一、今日学习内容
今天学习了关于在安卓开发中引用百度定位的方法
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.tiwen">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" /> <!-- 这个权限用于进行网络定位 -->
<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" />
<uses-permission
android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"
tools:ignore="ProtectedPermissions" />
需加入相关权限
package com.example.tiwen;
import android.app.Service;
import android.os.Vibrator;
import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import org.litepal.LitePalApplication;
/**
* 主Application,所有百度定位SDK的接口说明请参考线上文档:http://developer.baidu.com/map/loc_refer/index.html
*
* 百度定位SDK官方网站:http://developer.baidu.com/map/index.php?title=android-locsdk
*
* 直接拷贝com.baidu.location.service包到自己的工程下,简单配置即可获取定位结果,也可以根据demo内容自行封装
*/
public class LocationApplication extends LitePalApplication {
public LocationService locationService;
public Vibrator mVibrator;
@Override
public void onCreate() {
super.onCreate();
/***
* 初始化定位sdk,建议在Application中创建
*/
locationService = new LocationService(getApplicationContext());
mVibrator =(Vibrator)getApplicationContext().getSystemService(Service.VIBRATOR_SERVICE);
SDKInitializer.initialize(getApplicationContext());
SDKInitializer.setCoordType(CoordType.BD09LL);
}
}
package com.example.tiwen;
import android.content.Context;
import android.webkit.WebView;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
/**
* 定位服务LocationClient 相关
*
* @author baidu
*/
public class LocationService {
private static LocationClient client = null;
private static LocationClientOption mOption;
private static LocationClientOption DIYoption;
private Object objLock;
/***
* 初始化 LocationClient
*
* @param locationContext
*/
public LocationService(Context locationContext) {
objLock = new Object();
synchronized (objLock) {
if (client == null) {
client = new LocationClient(locationContext);
client.setLocOption(getDefaultLocationClientOption());
}
}
}
/***
* 注册定位监听
*
* @param listener
* @return
*/
public boolean registerListener(BDAbstractLocationListener listener) {
boolean isSuccess = false;
if (listener != null) {
client.registerLocationListener(listener);
isSuccess = true;
}
return isSuccess;
}
public void unregisterListener(BDAbstractLocationListener listener) {
if (listener != null) {
client.unRegisterLocationListener(listener);
}
}
/**
* @return 获取sdk版本
*/
public String getSDKVersion() {
if (client != null) {
String version = client.getVersion();
return version;
}
return null;
}
/***
* 设置定位参数
*
* @param option
* @return isSuccessSetOption
*/
public static boolean setLocationOption(LocationClientOption option) {
boolean isSuccess = false;
if (option != null) {
if (client.isStarted()) {
client.stop();
}
DIYoption = option;
client.setLocOption(option);
}
return isSuccess;
}
/**
* 开发者应用如果有H5页面使用了百度JS接口,该接口可以辅助百度JS更好的进行定位
*
* @param webView 传入webView控件
*/
public void enableAssistanLocation(WebView webView) {
if (client != null) {
client.enableAssistantLocation(webView);
}
}
/**
* 停止H5辅助定位
*/
public void disableAssistantLocation() {
if (client != null) {
client.disableAssistantLocation();
}
}
/***
*
* @return DefaultLocationClientOption 默认O设置
*/
public LocationClientOption getDefaultLocationClientOption() {
if (mOption == null) {
mOption = new LocationClientOption();
mOption.setAddrType("all");
mOption.setLocationMode(LocationMode.Hight_Accuracy); // 可选,默认高精度,设置定位模式,高精度,低功耗,仅设备
mOption.setCoorType( "bd09ll" ); // 可选,默认gcj02,设置返回的定位结果坐标系,如果配合百度地图使用,建议设置为bd09ll;
mOption.setScanSpan(3000); // 可选,默认0,即仅定位一次,设置发起连续定位请求的间隔需要大于等于1000ms才是有效的
mOption.setIsNeedAddress(true); // 可选,设置是否需要地址信息,默认不需要
mOption.setIsNeedLocationDescribe(true); // 可选,设置是否需要地址描述
mOption.setNeedDeviceDirect(true); // 可选,设置是否需要设备方向结果
mOption.setLocationNotify(true); // 可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果
mOption.setIgnoreKillProcess(true); // 可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop
mOption.setIsNeedLocationDescribe(true); // 可选,默认false,设置是否需要位置语义化结果,可以在BDLocation
mOption.setIsNeedLocationPoiList(true); // 可选,默认false,设置是否需要POI结果,可以在BDLocation
mOption.SetIgnoreCacheException(true); // 可选,默认false,设置是否收集CRASH信息,默认收集
mOption.setOpenGps(true); // 可选,默认false,设置是否开启Gps定位
mOption.setIsNeedAltitude(true); // 可选,默认false,设置定位时是否需要海拔信息,默认不需要,除基础定位版本都可用
}
return mOption;
}
/**
* @return DIYOption 自定义Option设置
*/
public LocationClientOption getOption() {
if (DIYoption == null) {
DIYoption = new LocationClientOption();
}
return DIYoption;
}
public void start() {
synchronized (objLock) {
if (client != null && !client.isStarted()) {
client.start();
}
}
}
public void requestLocation() {
if (client != null) {
client.requestLocation();
}
}
public void stop() {
synchronized (objLock) {
if (client != null && client.isStarted()) {
client.stop();
}
}
}
public boolean isStart() {
return client.isStarted();
}
public boolean requestHotSpotState() {
return client.requestHotSpotState();
}
}
package com.example.tiwen;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.Poi;
import org.litepal.LitePal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class FirstActivity extends AppCompatActivity {
private final int SDK_PERMISSION_REQUEST = 127;
private String permissionInfo;
private LocationService locationService;
private TextView address_text;
private CheckBox cb1,cb2,cb3,cb4;
private EditText etName,etDate,etId,etTiwen,etClass1,etCb2;
String Address,name,date,tiwen,ID1,class1,cbb1,cbb2,cbb3,cbb4,s1,ot2,date1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
etName = (EditText) findViewById(R.id.name_edit_text);
etDate = (EditText) findViewById(R.id.date_edit_text);
etDate.setText(getDate());
etId = (EditText) findViewById(R.id.ID_edit_text);
etClass1=(EditText) findViewById(R.id.class1_edit_text);
etTiwen = (EditText) findViewById(R.id.tiwen_edit_text);
LitePal.getDatabase();
List<Judge> judge= LitePal.findAll(Judge.class);
for(Judge j:judge){
name=j.getName();
ID1=j.getID1();
class1=j.getClass1();
}
etName.setText(name);
etId.setText(ID1);
etClass1.setText(class1);
address_text=(TextView) findViewById(R.id.address_text);
//startLocation = (Button) findViewById(R.id.button_2);
cb1 = (CheckBox)findViewById(R.id.ot1);
cb2 = (CheckBox)findViewById(R.id.ot2);
cb3 = (CheckBox)findViewById(R.id.ot3);
cb4 = (CheckBox)findViewById(R.id.ot4);
getPersimmions();
Button button1=(Button)findViewById(R.id.button_1);
button1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
cbb1=cb1.getText().toString().trim();
cbb2=cb2.getText().toString().trim();
cbb3=cb3.getText().toString().trim();
cbb4=cb4.getText().toString().trim();
StringBuffer sb1 = new StringBuffer(256);
if(cb1.isChecked()){
cb2.setChecked(false);
cb3.setChecked(false);
cb4.setChecked(false);
sb1.append(cbb1);
}
if(cb2.isChecked()){
sb1.append(cbb2);
etCb2=(EditText) findViewById(R.id.ot2_1);
ot2=etCb2.getText().toString().trim();
sb1.append(" 备注:"+ot2);
}
if(cb3.isChecked()){
sb1.append(cbb3);
}
if(cb4.isChecked()){
sb1.append(cbb4);
}
s1 = sb1.toString().trim();
name = etName.getText().toString().trim();
ID1 = etId.getText().toString().trim();
class1 = etClass1.getText().toString().trim();
date = etDate.getText().toString().trim();
date1 = date.substring(0, 10);
tiwen = etTiwen.getText().toString().trim();
List<TiWen> tiwen1 = (List<TiWen>) LitePal.where("ID1 = ? and date1 = ?", ID1, date1).find(TiWen.class);
if (null != tiwen1 && tiwen1.size() != 0) {
Toast.makeText(FirstActivity.this, "已提交", Toast.LENGTH_SHORT).show();
} else {
TiWen t = new TiWen();
t.setName(name);
t.setID1(ID1);
t.setClass1(class1);
t.setDate(date);
t.setAddress(Address);
t.setTiwen(tiwen);
t.setS(s1);
t.setDate1(date1);
t.save();
if (t.save()) {
Toast.makeText(FirstActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(FirstActivity.this, "提交失败", Toast.LENGTH_SHORT).show();
}
}
}
});
}
@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 \n";
}
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;
}
}
@TargetApi(23)
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
// TODO Auto-generated method stub
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
/***
* Stop location service
*/
@Override
protected void onStop() {
// TODO Auto-generated method stub
locationService.unregisterListener(mListener); //注销掉监听
locationService.stop(); //停止定位服务
super.onStop();
}
@Override
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("获取定位");
// }
//}
//});
}
private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {
/**
* 定位请求回调函数
*
* @param location 定位结果
*/
@Override
public void onReceiveLocation(BDLocation location) {
// TODO Auto-generated method stub
if (null != location && location.getLocType() != BDLocation.TypeServerError) {
StringBuffer sb = new StringBuffer(256);
sb.append(location.getAddrStr());
sb.append(location.getStreetNumber());
if (location.getPoiList() != null && !location.getPoiList().isEmpty()) {
Poi poi = (Poi) location.getPoiList().get(0);
sb.append(poi.getName());
}
Address=sb.toString().trim();
address_text.setText(Address);
//Address=location.getAddrStr();
if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
Toast.makeText(FirstActivity.this, "GPS定位成功", Toast.LENGTH_SHORT).show();
locationService.stop();
} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
// 运营商信息
Toast.makeText(FirstActivity.this, "网络定位成功", Toast.LENGTH_SHORT).show();
locationService.stop();
} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
Toast.makeText(FirstActivity.this, "离线定位成功,离线定位结果也是有效的", Toast.LENGTH_SHORT).show();
locationService.stop();
} else if (location.getLocType() == BDLocation.TypeServerError) {
Toast.makeText(FirstActivity.this, "服务端网络定位失败", Toast.LENGTH_SHORT).show();
//sb.append("服务端网络定位失败,可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com,会有人追查原因");
} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
Toast.makeText(FirstActivity.this, "网络不通导致定位失败,请检查网络是否通畅", Toast.LENGTH_SHORT).show();
} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
Toast.makeText(FirstActivity.this, "无法获取有效定位依据导致定位失败,可以重启手机", Toast.LENGTH_SHORT).show();
//sb.append("无法获取有效定位依据导致定位失败,一般是由于手机的原因,处于飞行模式下一般会造成这种结果,可以试着重启手机");
}
}
}
};
private String getDate() {
SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return date_format.format(new Date());
}
private String getDate1() {
SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd");
return date_format.format(new Date());
}
//private String getTime() {
// SimpleDateFormat time_format = new SimpleDateFormat("HH:mm:ss");
//return time_format.format(new Date());
// }
}
此外,连接数据库用到的方法是LitePal
二、遇到的问题
在进行百度定位的时候,开始一直定位失败,显示null,null,在经过网上查阅相关资料,是因为少了关于申请权限的相关代码
三、明日计划
明天对体温上报软件进行总结汇总
一、今日学习内容
今天学习了关于在安卓开发中引用百度定位的方法
相关教程:https://www.bilibili.com/video/BV1ca411c7uK?p=1
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.tiwen">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" /> <!-- 这个权限用于进行网络定位 -->
<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" />
<uses-permission
android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"
tools:ignore="ProtectedPermissions" />
需加入相关权限
package com.example.tiwen;
import android.app.Service;
import android.os.Vibrator;
import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import org.litepal.LitePalApplication;
/**
* 主Application,所有百度定位SDK的接口说明请参考线上文档:http://developer.baidu.com/map/loc_refer/index.html
*
* 百度定位SDK官方网站:http://developer.baidu.com/map/index.php?title=android-locsdk
*
* 直接拷贝com.baidu.location.service包到自己的工程下,简单配置即可获取定位结果,也可以根据demo内容自行封装
*/
public class LocationApplication extends LitePalApplication {
public LocationService locationService;
public Vibrator mVibrator;
@Override
public void onCreate() {
super.onCreate();
/***
* 初始化定位sdk,建议在Application中创建
*/
locationService = new LocationService(getApplicationContext());
mVibrator =(Vibrator)getApplicationContext().getSystemService(Service.VIBRATOR_SERVICE);
SDKInitializer.initialize(getApplicationContext());
SDKInitializer.setCoordType(CoordType.BD09LL);
}
}
package com.example.tiwen;
import android.content.Context;
import android.webkit.WebView;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
/**
* 定位服务LocationClient 相关
*
* @author baidu
*/
public class LocationService {
private static LocationClient client = null;
private static LocationClientOption mOption;
private static LocationClientOption DIYoption;
private Object objLock;
/***
* 初始化 LocationClient
*
* @param locationContext
*/
public LocationService(Context locationContext) {
objLock = new Object();
synchronized (objLock) {
if (client == null) {
client = new LocationClient(locationContext);
client.setLocOption(getDefaultLocationClientOption());
}
}
}
/***
* 注册定位监听
*
* @param listener
* @return
*/
public boolean registerListener(BDAbstractLocationListener listener) {
boolean isSuccess = false;
if (listener != null) {
client.registerLocationListener(listener);
isSuccess = true;
}
return isSuccess;
}
public void unregisterListener(BDAbstractLocationListener listener) {
if (listener != null) {
client.unRegisterLocationListener(listener);
}
}
/**
* @return 获取sdk版本
*/
public String getSDKVersion() {
if (client != null) {
String version = client.getVersion();
return version;
}
return null;
}
/***
* 设置定位参数
*
* @param option
* @return isSuccessSetOption
*/
public static boolean setLocationOption(LocationClientOption option) {
boolean isSuccess = false;
if (option != null) {
if (client.isStarted()) {
client.stop();
}
DIYoption = option;
client.setLocOption(option);
}
return isSuccess;
}
/**
* 开发者应用如果有H5页面使用了百度JS接口,该接口可以辅助百度JS更好的进行定位
*
* @param webView 传入webView控件
*/
public void enableAssistanLocation(WebView webView) {
if (client != null) {
client.enableAssistantLocation(webView);
}
}
/**
* 停止H5辅助定位
*/
public void disableAssistantLocation() {
if (client != null) {
client.disableAssistantLocation();
}
}
/***
*
* @return DefaultLocationClientOption 默认O设置
*/
public LocationClientOption getDefaultLocationClientOption() {
if (mOption == null) {
mOption = new LocationClientOption();
mOption.setAddrType("all");
mOption.setLocationMode(LocationMode.Hight_Accuracy); // 可选,默认高精度,设置定位模式,高精度,低功耗,仅设备
mOption.setCoorType( "bd09ll" ); // 可选,默认gcj02,设置返回的定位结果坐标系,如果配合百度地图使用,建议设置为bd09ll;
mOption.setScanSpan(3000); // 可选,默认0,即仅定位一次,设置发起连续定位请求的间隔需要大于等于1000ms才是有效的
mOption.setIsNeedAddress(true); // 可选,设置是否需要地址信息,默认不需要
mOption.setIsNeedLocationDescribe(true); // 可选,设置是否需要地址描述
mOption.setNeedDeviceDirect(true); // 可选,设置是否需要设备方向结果
mOption.setLocationNotify(true); // 可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果
mOption.setIgnoreKillProcess(true); // 可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop
mOption.setIsNeedLocationDescribe(true); // 可选,默认false,设置是否需要位置语义化结果,可以在BDLocation
mOption.setIsNeedLocationPoiList(true); // 可选,默认false,设置是否需要POI结果,可以在BDLocation
mOption.SetIgnoreCacheException(true); // 可选,默认false,设置是否收集CRASH信息,默认收集
mOption.setOpenGps(true); // 可选,默认false,设置是否开启Gps定位
mOption.setIsNeedAltitude(true); // 可选,默认false,设置定位时是否需要海拔信息,默认不需要,除基础定位版本都可用
}
return mOption;
}
/**
* @return DIYOption 自定义Option设置
*/
public LocationClientOption getOption() {
if (DIYoption == null) {
DIYoption = new LocationClientOption();
}
return DIYoption;
}
public void start() {
synchronized (objLock) {
if (client != null && !client.isStarted()) {
client.start();
}
}
}
public void requestLocation() {
if (client != null) {
client.requestLocation();
}
}
public void stop() {
synchronized (objLock) {
if (client != null && client.isStarted()) {
client.stop();
}
}
}
public boolean isStart() {
return client.isStarted();
}
public boolean requestHotSpotState() {
return client.requestHotSpotState();
}
}
package com.example.tiwen;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.Poi;
import org.litepal.LitePal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class FirstActivity extends AppCompatActivity {
private final int SDK_PERMISSION_REQUEST = 127;
private String permissionInfo;
private LocationService locationService;
private TextView address_text;
private CheckBox cb1,cb2,cb3,cb4;
private EditText etName,etDate,etId,etTiwen,etClass1,etCb2;
String Address,name,date,tiwen,ID1,class1,cbb1,cbb2,cbb3,cbb4,s1,ot2,date1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
etName = (EditText) findViewById(R.id.name_edit_text);
etDate = (EditText) findViewById(R.id.date_edit_text);
etDate.setText(getDate());
etId = (EditText) findViewById(R.id.ID_edit_text);
etClass1=(EditText) findViewById(R.id.class1_edit_text);
etTiwen = (EditText) findViewById(R.id.tiwen_edit_text);
LitePal.getDatabase();
List<Judge> judge= LitePal.findAll(Judge.class);
for(Judge j:judge){
name=j.getName();
ID1=j.getID1();
class1=j.getClass1();
}
etName.setText(name);
etId.setText(ID1);
etClass1.setText(class1);
address_text=(TextView) findViewById(R.id.address_text);
//startLocation = (Button) findViewById(R.id.button_2);
cb1 = (CheckBox)findViewById(R.id.ot1);
cb2 = (CheckBox)findViewById(R.id.ot2);
cb3 = (CheckBox)findViewById(R.id.ot3);
cb4 = (CheckBox)findViewById(R.id.ot4);
getPersimmions();
Button button1=(Button)findViewById(R.id.button_1);
button1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
cbb1=cb1.getText().toString().trim();
cbb2=cb2.getText().toString().trim();
cbb3=cb3.getText().toString().trim();
cbb4=cb4.getText().toString().trim();
StringBuffer sb1 = new StringBuffer(256);
if(cb1.isChecked()){
cb2.setChecked(false);
cb3.setChecked(false);
cb4.setChecked(false);
sb1.append(cbb1);
}
if(cb2.isChecked()){
sb1.append(cbb2);
etCb2=(EditText) findViewById(R.id.ot2_1);
ot2=etCb2.getText().toString().trim();
sb1.append(" 备注:"+ot2);
}
if(cb3.isChecked()){
sb1.append(cbb3);
}
if(cb4.isChecked()){
sb1.append(cbb4);
}
s1 = sb1.toString().trim();
name = etName.getText().toString().trim();
ID1 = etId.getText().toString().trim();
class1 = etClass1.getText().toString().trim();
date = etDate.getText().toString().trim();
date1 = date.substring(0, 10);
tiwen = etTiwen.getText().toString().trim();
List<TiWen> tiwen1 = (List<TiWen>) LitePal.where("ID1 = ? and date1 = ?", ID1, date1).find(TiWen.class);
if (null != tiwen1 && tiwen1.size() != 0) {
Toast.makeText(FirstActivity.this, "已提交", Toast.LENGTH_SHORT).show();
} else {
TiWen t = new TiWen();
t.setName(name);
t.setID1(ID1);
t.setClass1(class1);
t.setDate(date);
t.setAddress(Address);
t.setTiwen(tiwen);
t.setS(s1);
t.setDate1(date1);
t.save();
if (t.save()) {
Toast.makeText(FirstActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(FirstActivity.this, "提交失败", Toast.LENGTH_SHORT).show();
}
}
}
});
}
@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 \n";
}
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;
}
}
@TargetApi(23)
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
// TODO Auto-generated method stub
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
/***
* Stop location service
*/
@Override
protected void onStop() {
// TODO Auto-generated method stub
locationService.unregisterListener(mListener); //注销掉监听
locationService.stop(); //停止定位服务
super.onStop();
}
@Override
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("获取定位");
// }
//}
//});
}
private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {
/**
* 定位请求回调函数
*
* @param location 定位结果
*/
@Override
public void onReceiveLocation(BDLocation location) {
// TODO Auto-generated method stub
if (null != location && location.getLocType() != BDLocation.TypeServerError) {
StringBuffer sb = new StringBuffer(256);
sb.append(location.getAddrStr());
sb.append(location.getStreetNumber());
if (location.getPoiList() != null && !location.getPoiList().isEmpty()) {
Poi poi = (Poi) location.getPoiList().get(0);
sb.append(poi.getName());
}
Address=sb.toString().trim();
address_text.setText(Address);
//Address=location.getAddrStr();
if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
Toast.makeText(FirstActivity.this, "GPS定位成功", Toast.LENGTH_SHORT).show();
locationService.stop();
} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
// 运营商信息
Toast.makeText(FirstActivity.this, "网络定位成功", Toast.LENGTH_SHORT).show();
locationService.stop();
} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
Toast.makeText(FirstActivity.this, "离线定位成功,离线定位结果也是有效的", Toast.LENGTH_SHORT).show();
locationService.stop();
} else if (location.getLocType() == BDLocation.TypeServerError) {
Toast.makeText(FirstActivity.this, "服务端网络定位失败", Toast.LENGTH_SHORT).show();
//sb.append("服务端网络定位失败,可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com,会有人追查原因");
} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
Toast.makeText(FirstActivity.this, "网络不通导致定位失败,请检查网络是否通畅", Toast.LENGTH_SHORT).show();
} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
Toast.makeText(FirstActivity.this, "无法获取有效定位依据导致定位失败,可以重启手机", Toast.LENGTH_SHORT).show();
//sb.append("无法获取有效定位依据导致定位失败,一般是由于手机的原因,处于飞行模式下一般会造成这种结果,可以试着重启手机");
}
}
}
};
private String getDate() {
SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return date_format.format(new Date());
}
private String getDate1() {
SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd");
return date_format.format(new Date());
}
//private String getTime() {
// SimpleDateFormat time_format = new SimpleDateFormat("HH:mm:ss");
//return time_format.format(new Date());
// }
}
此外,连接数据库用到的方法是LitePal
二、遇到的问题
在进行百度定位的时候,开始一直定位失败,显示null,null,在经过网上查阅相关资料,是因为少了关于申请权限的相关代码
三、明日计划
明天对体温上报软件进行总结汇总