Android U盘读写
生活随笔
收集整理的這篇文章主要介紹了
Android U盘读写
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
修改項目(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() {@Overridepublic 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() {@Overridepublic 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() {@Overridepublic 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() {@Overridepublic void run() {importSetting(isAppend[0]);ProcessDialogUtils.dismiss();}}).start();}});//備份配置inflate.findViewById(R.id.btn_backup_config).setOnClickListener(new View.OnClickListener() {@Overridepublic 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() {@Overridepublic void run() {exportSetting();ProcessDialogUtils.dismiss();}}).start();}});inflate.findViewById(R.id.btn_backup_print_log).setOnClickListener(new View.OnClickListener() {@Overridepublic 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() {@Overridepublic void run() {//exportLog();exportDataBase();ProcessDialogUtils.dismiss();}}).start();}});inflate.findViewById(R.id.btn_backup_confirm).setOnClickListener(new View.OnClickListener() {@Overridepublic 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 <T>*/@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() {@Overridepublic 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();}}}}}}總結
以上是生活随笔為你收集整理的Android U盘读写的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 车道偏离报警系统
- 下一篇: 机器视觉光源的分类及各种光源的特点