Storage.java
22.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
package com.sw.laryngoscope.manager;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.os.storage.StorageManager;
import android.util.Log;
import androidx.annotation.RequiresApi;
import androidx.core.os.EnvironmentCompat;
import com.sw.laryngoscope.utils.Logger;
public class Storage {
private static final String TAG = "Storage";
public static final long UNAVAILABLE = -1L;
public static final long PREPARING = -2L;
public static final long UNKNOWN_SIZE = -3L;
/**
* @param filepath
* @return 检测文件是否存在
*/
public static boolean isCheckExist(String filepath) {
try {
if ( null == filepath || filepath.isEmpty() ) {
return false;
}
File file = new File(filepath);
return file.exists();
}catch(Exception ex) {
ex.printStackTrace();
}
return false;
}
public static void writeFile(String path, byte[] data) {
FileOutputStream out = null;
try {
out = new FileOutputStream(path);
out.write(data);
} catch (Exception e) {
Log.e(TAG, "Failed to write data", e);
} finally {
try {
out.close();
} catch (Exception e) {
Log.e(TAG, "Failed to close file after write", e);
}
}
}
public static long getUDiskTotalSpace(Context mContext) {
BufferedReader br = null;
String str = null;
boolean ret = false;
/*List<VolumeInfo> list = mStorageManager.getVolumes();
for (VolumeInfo volumeInfo : list) {
if (volumeInfo.getType() == 0) {
DiskInfo diskInfo = volumeInfo.getDisk();
if (diskInfo != null && (diskInfo.isUsb())) {
int i = volumeInfo.getState();
//volumeInfo.getPath()通过这个方法就能取得路径
//这里的Volume就是U盘的信息了
}
}
}*/
String path = getStoragePath(mContext, "usb") + "test";
/*StorageManager mStorageManager = (StorageManager) mContext
.getSystemService(Context.STORAGE_SERVICE);
Class<?> storageVolumeClazz = null;
Class<?> diskInfoClazz = null;
try {
storageVolumeClazz = Class.forName("android.os.storage.VolumeInfo");
diskInfoClazz = Class.forName("android.os.storage.DiskInfo");
Method getVolumeList = mStorageManager.getClass().getMethod("getVolumes");
Object result = getVolumeList.invoke(mStorageManager);
Log.d(TAG,"getVolumeList =" + result);
final int length = ((List)result).size();
Method getDisk = storageVolumeClazz.getMethod("getDisk");
Method getType = storageVolumeClazz.getMethod("getType");
Method getPath = storageVolumeClazz.getMethod("getPath");
for (int i = 0; i < length; i++) {
Object storageVolumeElement = ((List)result).get(i);
Log.d(TAG,"getType =" + getType.invoke(storageVolumeElement));
int type = (int)getType.invoke(storageVolumeElement);
if ( type == 0 ) {
Method isUsb = diskInfoClazz.getMethod("isUsb");
Object resDiskInfo = getDisk.invoke(storageVolumeElement);
Log.d(TAG,"isUsb =" + isUsb.invoke(resDiskInfo));
Log.d(TAG,"getPath =" + getPath.invoke(storageVolumeElement));
boolean IsUsb = (boolean)isUsb.invoke(resDiskInfo);
if ( resDiskInfo != null && IsUsb ) {
path = (String)getPath.invoke(storageVolumeElement);
}
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}*/
Log.d(TAG,"path is " + path);
File dirPath = new File(path);
dirPath.mkdirs();
if (!dirPath.isDirectory() || !dirPath.canWrite()) {
Log.d(TAG,dirPath.canWrite() + "=" + dirPath.isDirectory());
return UNAVAILABLE;
} else {
return 1;
/*try {
br = new BufferedReader(new FileReader(new File("/proc/mounts")));
while((str = br.readLine()) != null) {
if(str.contains("/mnt/usbhost")) {
ret = true;
break;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if(ret == false)
return UNAVAILABLE;
File dir = new File(UDISK_DIRECTORY);
dir.mkdirs();
if (!dir.isDirectory() || !dir.canWrite()) {
Log.d(TAG,dir.canWrite() + "=" + dir.isDirectory());
return UNAVAILABLE;
}
try {
StatFs stat = new StatFs(UDISK_DIRECTORY);
return stat.getBlockCount() * (long) stat.getBlockSize();
} catch (Exception e) {
Log.i(TAG, "Fail to access external storage", e);
}
return UNKNOWN_SIZE;
*/
}
}
/**
* 6.0获取外置sdcard和U盘路径,并区分
* @param
* @param keyword SD = "内部存储"; EXT = "SD卡"; USB = "U盘"
* @return
*/
public static String getStoragePath(Context pContext, String keyword) {
final StorageManager storageManager = (StorageManager) pContext.getSystemService(Context.STORAGE_SERVICE);
try {
//得到StorageManager中的getVolumeList()方法的对象
final Method getVolumeList = storageManager.getClass().getMethod("getVolumeList");
//---------------------------------------------------------------------
//得到StorageVolume类的对象
final Class<?> storageValumeClazz = Class.forName("android.os.storage.StorageVolume");
//---------------------------------------------------------------------
//获得StorageVolume中的一些方法
final Method getPath = storageValumeClazz.getMethod("getPath");
Method isRemovable = storageValumeClazz.getMethod("isRemovable");
Method mGetState = null;
//getState 方法是在4.4_r1之后的版本加的,之前版本(含4.4_r1)没有
// (http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.4_r1/android/os/Environment.java/)
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
try {
mGetState = storageValumeClazz.getMethod("getState");
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
//---------------------------------------------------------------------
//哈哈哈
Method getUserLabel = storageValumeClazz.getMethod("getUserLabel");
//哈哈哈
//调用getVolumeList方法,参数为:“谁”中调用这个方法
final Object invokeVolumeList = getVolumeList.invoke(storageManager);
//---------------------------------------------------------------------
final int length = Array.getLength(invokeVolumeList);
for (int i = 0; i < length; i++) {
final Object storageValume = Array.get(invokeVolumeList, i);//得到StorageVolume对象
final String path = (String) getPath.invoke(storageValume);
final boolean removable = (Boolean) isRemovable.invoke(storageValume);
String state = null;
if (mGetState != null) {
state = (String) mGetState.invoke(storageValume);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
state = Environment.getStorageState(new File(path));
} else {
if (removable) {
state = EnvironmentCompat.getStorageState(new File(path));
} else {
//不能移除的存储介质,一直是mounted
state = Environment.MEDIA_MOUNTED;
}
final File externalStorageDirectory = Environment.getExternalStorageDirectory();
Log.e(TAG, "externalStorageDirectory==" + externalStorageDirectory);
}
}
long totalSize = 0;
long availaleSize = 0;
if (Environment.MEDIA_MOUNTED.equals(state)) {
totalSize = Storage.getTotalSize(path);
availaleSize = Storage.getAvailableSize(path);
}
//
String userLabel = (String) getUserLabel.invoke(storageValume);
final String msg = "path==" + path
+ " ,removable==" + removable
+ ",state==" + state
+ ",total size==" + totalSize + "(" + Storage.fmtSpace(totalSize) + ")"
+ ",availale size==" + availaleSize + "(" + Storage.fmtSpace(availaleSize) + ")";
Log.e(TAG, msg + " , userLabel= " + userLabel);
if ( keyword.contains("SD") ) {
if( userLabel.contains(keyword) ) {
return path+"/";
}
} else if ( keyword.contains("usb") ) {
/*File apkPath = new File(path + "/" + CTConstant.apkName);*/
Log.d(TAG, "========"
+ userLabel.contains("内部存储") +
userLabel.contains("Intern") + userLabel.contains("SD") );
if( !userLabel.contains("内部存储")
&& !userLabel.contains("Intern")
&& !userLabel.contains("SD") ){
return path+"/";
}
}
}
return null;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static long getTotalSize(String path) {
try {
final StatFs statFs = new StatFs(path);
long blockSize = 0;
long blockCountLong = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
blockSize = statFs.getBlockSizeLong();
blockCountLong = statFs.getBlockCountLong();
} else {
blockSize = statFs.getBlockSize();
blockCountLong = statFs.getBlockCount();
}
return blockSize * blockCountLong;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public static long getAvailableSize(String path) {
try {
final StatFs statFs = new StatFs(path);
long blockSize = 0;
long availableBlocks = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
blockSize = statFs.getBlockSizeLong();
availableBlocks = statFs.getAvailableBlocksLong();
} else {
blockSize = statFs.getBlockSize();
availableBlocks = statFs.getAvailableBlocks();
}
return availableBlocks * blockSize;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public static final long A_GB = 1073741824;
public static final long A_MB = 1048576;
public static final int A_KB = 1024;
public static String fmtSpace(long space) {
if (space <= 0) {
return "0";
}
double gbValue = (double) space / A_GB;
if (gbValue >= 1) {
return String.format("%.2fGB", gbValue);
} else {
double mbValue = (double) space / A_MB;
Log.e("GB", "gbvalue=" + mbValue);
if (mbValue >= 1) {
return String.format("%.2fMB", mbValue);
} else {
final double kbValue = space / A_KB;
return String.format("%.2fKB", kbValue);
}
}
}
/*public void getPath() {
StorageManager mStorageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
List<VolumeInfo> vols = mStorageManager.getVolumes();
for (int i = 0; i < vols.length; i++) {
DiskInfo disk = vols.get(i).getDisk();
String path = vols.get(i).path;
boolean sd = false;
boolean usb = false;
if (disk != null) {
if (disk.isSd()) {
String sdPath = path;
}else if (disk.isUsb()) {
String usbPath = path;
}
}
}
}*/
@RequiresApi(api = Build.VERSION_CODES.N)
public static String getSDPath(Context context) {
String path = "";
@SuppressLint("ServiceCast")
UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
if (usbManager != null) {
HashMap<String, UsbDevice> deviceHashMap = usbManager.getDeviceList();
Log.d(TAG, "device name: " + deviceHashMap.size());
if (deviceHashMap.isEmpty()) {
//return path;
}
for (UsbDevice device : deviceHashMap.values()) {
Log.d(TAG, "device name: " + device.getDeviceName() + "\nvendor id:" + device.getVendorId());
//dispatchAttachedListener();
}
}
return path;
}
public static String getStoragePath1(Context pContext, String keyword) {
final StorageManager storageManager = (StorageManager) pContext.getSystemService(Context.STORAGE_SERVICE);
try {
//得到StorageManager中的getVolumeList()方法的对象
final Method getVolumeList = storageManager.getClass().getMethod("getVolumeList");
//---------------------------------------------------------------------
//得到StorageVolume类的对象
final Class<?> storageValumeClazz = Class.forName("android.os.storage.StorageVolume");
//---------------------------------------------------------------------
//获得StorageVolume中的一些方法
final Method getPath = storageValumeClazz.getMethod("getPath");
Method isRemovable = storageValumeClazz.getMethod("isRemovable");
Method mGetState = null;
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
try {
mGetState = storageValumeClazz.getMethod("getState");
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
Method getUserLabel = storageValumeClazz.getMethod("getUserLabel");
//调用getVolumeList方法,参数为:“谁”中调用这个方法
final Object invokeVolumeList = getVolumeList.invoke(storageManager);
final int length = Array.getLength(invokeVolumeList);
for (int i = 0; i < length; i++) {
final Object storageValume = Array.get(invokeVolumeList, i);//得到StorageVolume对象
final String path = (String) getPath.invoke(storageValume);
final boolean removable = (Boolean) isRemovable.invoke(storageValume);
String state = null;
if (mGetState != null) {
state = (String) mGetState.invoke(storageValume);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
state = Environment.getStorageState(new File(path));
} else {
if (removable) {
state = EnvironmentCompat.getStorageState(new File(path));
} else {
//不能移除的存储介质,一直是mounted
state = Environment.MEDIA_MOUNTED;
}
final File externalStorageDirectory = Environment.getExternalStorageDirectory();
}
}
//
String userLabel = (String) getUserLabel.invoke(storageValume);
if (keyword.contains("usb")) {
//return path + "/";
}
//Logger.d("path " + path + " keyword " + keyword + " userLabel " + URLEncoder.encode(userLabel,"UTF-8"));
Logger.d("path " + path + " keyword " + keyword + " userLabel " + userLabel);
}
return null;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 获取U盘的路径和名称
*/
public static String getUName(Context pContext) {
String uname = "";
StorageManager mStorageManager;
mStorageManager = (StorageManager) pContext.getSystemService(Activity.STORAGE_SERVICE);
Class<?> volumeInfoClazz = null;
Method getDescriptionComparator = null;
Method getBestVolumeDescription = null;
Method getVolumes = null;
Method isMountedReadable = null;
Method getType = null;
Method getPath = null;
List<?> volumes = null;
try {
volumeInfoClazz = Class.forName("android.os.storage.VolumeInfo");
getDescriptionComparator = volumeInfoClazz.getMethod("getDescriptionComparator");
getBestVolumeDescription = StorageManager.class.getMethod("getBestVolumeDescription", volumeInfoClazz);
getVolumes = StorageManager.class.getMethod("getVolumes");
isMountedReadable = volumeInfoClazz.getMethod("isMountedReadable");
getType = volumeInfoClazz.getMethod("getType");
getPath = volumeInfoClazz.getMethod("getPath");
volumes = (List<?>) getVolumes.invoke(mStorageManager);
for (Object vol : volumes) {
//Log.d(TAG, "-----------path0-----------------" + getType.invoke(vol) + " - " + ((File) getPath.invoke(vol)).getPath());
if (vol != null && (boolean) isMountedReadable.invoke(vol) && (int) getType.invoke(vol) == 0) {
File path2 = (File) getPath.invoke(vol);
uname = (String) getBestVolumeDescription.invoke(mStorageManager, vol);
String p2 = path2.getPath();
Log.d(TAG, "-----------path1-----------------" + uname); //打印U盘卷标名称
Log.d(TAG, "-----------path2 @@@@@-----------------" + p2); //打印U盘路径
return uname;
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return uname;
}
public static String getUPath(Context pContext) {
String upath = "123";
StorageManager mStorageManager;
mStorageManager = (StorageManager) pContext.getSystemService(Activity.STORAGE_SERVICE);
Class<?> volumeInfoClazz = null;
Method getDescriptionComparator = null;
Method getBestVolumeDescription = null;
Method getVolumes = null;
Method isMountedReadable = null;
Method getType = null;
Method getPath = null;
List<?> volumes = null;
try {
volumeInfoClazz = Class.forName("android.os.storage.VolumeInfo");
getDescriptionComparator = volumeInfoClazz.getMethod("getDescriptionComparator");
getBestVolumeDescription = StorageManager.class.getMethod("getBestVolumeDescription", volumeInfoClazz);
getVolumes = StorageManager.class.getMethod("getVolumes");
isMountedReadable = volumeInfoClazz.getMethod("isMountedReadable");
getType = volumeInfoClazz.getMethod("getType");
getPath = volumeInfoClazz.getMethod("getPath");
volumes = (List<?>) getVolumes.invoke(mStorageManager);
for (Object vol : volumes) {
//Log.d(TAG, "-----------path0-----------------" + getType.invoke(vol) + " - " + ((File) getPath.invoke(vol)).getPath());
if (vol != null && (boolean) isMountedReadable.invoke(vol) && (int) getType.invoke(vol) == 0) {
File path2 = (File) getPath.invoke(vol);
String p1 = (String) getBestVolumeDescription.invoke(mStorageManager, vol);
upath = path2.getPath();
Log.d(TAG, "-----------path1-----------------" + p1); //打印U盘卷标名称
Log.d(TAG, "-----------path2 @@@@@-----------------" + upath); //打印U盘路径
return upath + "/";
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return upath + "/";
}
}