修改项目(app)的build.gradle
/*
* exel导入导出
* */
implementation group: 'net.sourceforge.jexcelapi', name: 'jxl', version: '2.6.12'
/*
* libaums
* https://github.com/magnusja/libaums#using-buffered-streams-for-more-efficency
* */
implementation 'com.github.mjdev:libaums:0.6.0'
/**
* @description OTG广播,监听U盘的插入及拔出
* @author ldm
* @time 2017/9/1 17:20
* @param
*/
private BroadcastReceiver mOtgReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
case ACTION_USB_PERMISSION://接受到自定义广播
UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
//允许权限申请
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (usbDevice != null) {
//用户已授权,可以进行读取操作
readDevice(getUsbMass(usbDevice));
} else {
TastyToast.makeText(MYCuttingMachineService.this, getResources().getString(R.string.meiyou_charu_u_pan),
TastyToast.LENGTH_SHORT, TastyToast.INFO).show();
}
} else {
TastyToast.makeText(MYCuttingMachineService.this, getResources().getString(R.string.weihuoqu_u_quanxian),
TastyToast.LENGTH_SHORT, TastyToast.INFO).show();
}
break;
case UsbManager.ACTION_USB_DEVICE_ATTACHED://接收到U盘设备插入广播
UsbDevice device_add = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device_add != null) {
//接收到U盘插入广播,尝试读取U盘设备数据
readUDiskDevsList();
}
//showBackUpDialog();
//显示备份对话框
EventBus.getDefault().post(new EventBusCarrier(EventType.SHOW_BACK_UP_DIALOG));
break;
case UsbManager.ACTION_USB_DEVICE_DETACHED://接收到U盘设设备拔出广播
TastyToast.makeText(MYCuttingMachineService.this, getResources().getString(R.string.u_pan_yibachu), TastyToast.LENGTH_SHORT,
TastyToast.INFO).show();
//uDiskDialog.dismiss();
EventBus.getDefault().post(new EventBusCarrier(EventType.CLOSE_BACK_UP_DIALOG));
break;
}
}
};
//显示备份页面
private void showBackUpDialog() {
final View inflate = mLayoutInflater.inflate(R.layout.item_backup_dialog, null);
uDiskDialog = new MaterialDialog.Builder(this).autoDismiss(false)
.customView(inflate, true).build();
Window window = uDiskDialog.getWindow();
window.setGravity(Gravity.CENTER);
WindowManager.LayoutParams attributes = window.getAttributes();
attributes.width = 800;
attributes.height = 500;
window.setAttributes(attributes);
uDiskDialog.show();
final boolean[] isAppend = {
true};
final Drawable drawableOn = Main2Activity.this.getResources().getDrawable(R.drawable.rb_on);
final Drawable drawableOff =
Main2Activity.this.getResources().getDrawable(R.drawable.rb_off);
final ImageView ivCover = (ImageView) inflate.findViewById(R.id.iv_backup_cover_config);
final ImageView ivAppend = (ImageView) inflate.findViewById(R.id.iv_backup_append_config);
View.OnClickListener coverClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
ivCover.setBackground(drawableOn);
ivAppend.setBackground(drawableOff);
isAppend[0] = false;
}
};
ivCover.setOnClickListener(coverClickListener);
inflate.findViewById(R.id.tv_backup_cover_config).setOnClickListener(coverClickListener);
View.OnClickListener appendClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
ivCover.setBackground(drawableOff);
ivAppend.setBackground(drawableOn);
isAppend[0] = true;
}
};
ivAppend.setOnClickListener(appendClickListener);
inflate.findViewById(R.id.tv_backup_append_config).setOnClickListener(appendClickListener);
//导入配置
inflate.findViewById(R.id.btn_import_config).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ProcessDialogUtils.setTitle(getResources().getString(R.string.daoru_peizhi_zhong));
ProcessDialogUtils.setContent(getResources().getString(R.string.qing_dengdai));
ProcessDialogUtils.show();
new Thread(new Runnable() {
@Override
public void run() {
importSetting(isAppend[0]);
ProcessDialogUtils.dismiss();
}
}).start();
}
});
//备份配置
inflate.findViewById(R.id.btn_backup_config).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ProcessDialogUtils.setTitle(getResources().getString(R.string.beifen_peizhi_zhong));
ProcessDialogUtils.setContent(getResources().getString(R.string.qing_dengdai));
ProcessDialogUtils.show();
new Thread(new Runnable() {
@Override
public void run() {
exportSetting();
ProcessDialogUtils.dismiss();
}
}).start();
}
});
inflate.findViewById(R.id.btn_backup_print_log).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ProcessDialogUtils.setTitle(getResources().getString(R.string.beifen_dayinjilu_zhong));
ProcessDialogUtils.setContent(getResources().getString(R.string.qing_dengdai));
ProcessDialogUtils.show();
new Thread(new Runnable() {
@Override
public void run() {
//exportLog();
exportDataBase();
ProcessDialogUtils.dismiss();
}
}).start();
}
});
inflate.findViewById(R.id.btn_backup_confirm).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uDiskDialog.dismiss();
//exportLog();
}
});
}
/**
* @description OTG广播注册
* @author ldm
* @time 2017/9/1 17:19
*/
private void registerUDiskReceiver() {
//监听otg插入 拔出
IntentFilter usbDeviceStateFilter = new IntentFilter();
usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(mOtgReceiver, usbDeviceStateFilter);
//注册监听自定义广播
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mOtgReceiver, filter);
}
/**
* @description U盘设备读取
* @author ldm
* @time 2017/9/1 17:20
*/
private void readUDiskDevsList() {
//设备管理器
UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
//获取U盘存储设备
storageDevices = UsbMassStorageDevice.getMassStorageDevices(this);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
new Intent(ACTION_USB_PERMISSION), 0);
//一般手机只有1个OTG插口
for (UsbMassStorageDevice device : storageDevices) {
//读取设备是否有权限
if (usbManager.hasPermission(device.getUsbDevice())) {
readDevice(device);
} else {
//没有权限,进行申请
usbManager.requestPermission(device.getUsbDevice(), pendingIntent);
}
}
if (storageDevices.length == 0) {
TastyToast.makeText(MYCuttingMachineService.this, getResources().getString(R.string.qingcharu_keyong_Upan), TastyToast.LENGTH_SHORT,
TastyToast.INFO).show();
}
}
private void readDevice(UsbMassStorageDevice device) {
try {
device.init();//初始化
//设备分区
Partition partition = device.getPartitions().get(0);
//文件系统
FileSystem currentFs = partition.getFileSystem();
currentFs.getVolumeLabel();//可以获取到设备的标识
//通过FileSystem可以获取当前U盘的一些存储信息,包括剩余空间大小,容量等等
/* Log.e("Capacity: ", currentFs.getCapacity() + "");
Log.e("Occupied Space: ", currentFs.getOccupiedSpace() + "");
Log.e("Free Space: ", currentFs.getFreeSpace() + "");
Log.e("Chunk size: ", currentFs.getChunkSize() + "");*/
cFolder = currentFs.getRootDirectory();//设置当前文件对象为根目录
} catch (final Exception e) {
TastyToast.makeText(MYCuttingMachineService.this, e.toString(), TastyToast.LENGTH_SHORT,
TastyToast.ERROR).show();
e.printStackTrace();
}
}
private UsbMassStorageDevice getUsbMass(UsbDevice usbDevice) {
for (UsbMassStorageDevice device : storageDevices) {
if (usbDevice.equals(device.getUsbDevice())) {
return device;
}
}
return null;
}
public class ExcelUtil {
private static WritableFont arial14font = null;
private static WritableCellFormat arial14format = null;
private static WritableFont arial10font = null;
private static WritableCellFormat arial10format = null;
private static WritableFont arial12font = null;
private static WritableCellFormat arial12format = null;
private final static String UTF8_ENCODING = "UTF-8";
/**
* 单元格的格式设置 字体大小 颜色 对齐方式、背景颜色等...
*/
private static void format() {
try {
arial14font = new WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD);
arial14font.setColour(Colour.LIGHT_BLUE);
arial14format = new WritableCellFormat(arial14font);
arial14format.setAlignment(jxl.format.Alignment.CENTRE);
arial14format.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
arial14format.setBackground(Colour.VERY_LIGHT_YELLOW);
arial10font = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
arial10format = new WritableCellFormat(arial10font);
arial10format.setAlignment(jxl.format.Alignment.CENTRE);
arial10format.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
arial10format.setBackground(Colour.GRAY_25);
arial12font = new WritableFont(WritableFont.ARIAL, 10);
arial12format = new WritableCellFormat(arial12font);
//对齐格式
arial10format.setAlignment(jxl.format.Alignment.CENTRE);
//设置边框
arial12format.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
} catch (WriteException e) {
e.printStackTrace();
}
}
/**
* 初始化Excel表格
*
* @param filePath 存放excel文件的路径(path/demo.xls)
* @param sheetName Excel表格的表名
* @param colName excel中包含的列名(可以有多个)
*/
public static void initExcel(String filePath, String sheetName, String[] colName) {
format();
WritableWorkbook workbook = null;
try {
File fileTemp = new File(filePath);
if (fileTemp.exists()) {
fileTemp.delete();
}
File file = new File(filePath);
file.createNewFile();
workbook = Workbook.createWorkbook(file);
//设置表格的名字
WritableSheet sheet = workbook.createSheet(sheetName, 0);
//创建标题栏
sheet.addCell((WritableCell) new Label(0, 0, filePath, arial14format));
for (int col = 0; col < colName.length; col++) {
sheet.addCell(new Label(col, 0, colName[col], arial10format));
}
//设置行高
sheet.setRowView(0, 340);
workbook.write();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (workbook != null) {
try {
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 将制定类型的List写入Excel中
*
* @param objList 待写入的list
* @param fileName
* @param c
* @param
*/
@SuppressWarnings("unchecked")
public static <T> void writeObjListToExcel(List<T> objList, String fileName, final int type) {
if (objList != null && objList.size() > 0) {
WritableWorkbook writebook = null;
InputStream in = null;
try {
int maxLength = 60000;
//表格数
int sheetAmount = objList.size() / maxLength;
if (objList.size() % maxLength != 0) {
sheetAmount++;
}
WorkbookSettings setEncode = new WorkbookSettings();
setEncode.setEncoding(UTF8_ENCODING);
in = new FileInputStream(new File(fileName));
Workbook workbook = Workbook.getWorkbook(in);
writebook = Workbook.createWorkbook(new File(fileName), workbook);
WritableSheet sheet = writebook.getSheet(0);
for (int j = 0; j < objList.size(); j++) {
List<String> list = new ArrayList<>();
switch (type) {
case 1:
SettingExcelBean settingExcelBean = (SettingExcelBean) objList.get(j);
list.add(settingExcelBean.getName());
list.add(settingExcelBean.getType());
break;
case 2:
PrintLog printLog = (PrintLog) objList.get(j);
list.add(printLog.getPtId() + "");
list.add(printLog.getPtDate() + "");
list.add(printLog.getSterilizationDate() + "");
list.add(printLog.getNvalidDate() + "");
list.add(printLog.getSterilizationBatch() + "");
list.add(printLog.getSterilizationDeviceNumber() + "");
list.add(printLog.getOperator() + "");
list.add(printLog.getDepartmentName() + "");
list.add(printLog.getGoodName() + "");
list.add(printLog.getCustomContent() + "");
list.add(printLog.getTemperature() + "");
list.add(printLog.getPressure() + "");
list.add(printLog.getNumber() + "");
break;
}
/* DemoBean demoBean = (DemoBean) objList.get(j);
list.add(demoBean.getName());
list.add(String.valueOf(demoBean.getAge()));
list.add(String.valueOf(demoBean.isBoy()));*/
for (int i = 0; i < list.size(); i++) {
sheet.addCell(new Label(i, j + 1, list.get(i), arial12format));
if (list.get(i).length() <= 4) {
//设置列宽
sheet.setColumnView(i, list.get(i).length() + 8);
} else {
//设置列宽
sheet.setColumnView(i, list.get(i).length() + 5);
}
}
//设置行高
sheet.setRowView(j + 1, 350);
}
writebook.write();
workbook.close();
/* c.runOnUiThread(new Runnable() {
@Override
public void run() {
switch (type) {
case 1:
TastyToast.makeText(c, "导出配置信息成功!", Toast.LENGTH_SHORT, TastyToast.SUCCESS).show();
break;
case 2:
TastyToast.makeText(c, "导出打印记录成功!", Toast.LENGTH_SHORT, TastyToast.SUCCESS).show();
break;
}
}
});*/
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writebook != null) {
try {
writebook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}