huangcm
2025-04-09 02d4ce54b909bd733f12e9f3fa4c1b03cf2d6f45
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
package com.DeviceTest;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
 
import com.DeviceTest.helper.ConfigUtil;
import com.DeviceTest.helper.ControlButtonUtil;
import com.DeviceTest.helper.StorageInfo;
import com.DeviceTest.helper.SystemInfoUtil;
import com.DeviceTest.helper.SystemUtil;
 
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.ServiceManager;
import android.os.StatFs;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.os.SystemProperties;
import android.text.format.Formatter;
import android.util.Log;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.os.storage.StorageEventListener;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.os.storage.VolumeInfo;
import java.util.Collections;
import android.os.storage.DiskInfo;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
 
public class UsbHostTestActivity extends Activity {
    private static final String TAG = "UsbHostTestActivity";
    private static final String TEST_STRING = "Rockchip UsbHostTest File";
//   private static final String SDCARD_PATH = "/mnt/external_sd";
//  private final static String SDCARD_PATH = "/storage/sdcard1";
    protected static final int BACK_TIME = 2000;
    private static final int SEND_REND_WRITE_SD = 3;
    protected static final int R_PASS = 1;
    protected static final int R_FAIL = 2;
    private String sdcard_path = null;
    private StringBuilder sBuilder;
   // private SdcardReceiver sdcardReceiver = null;
    public String SUCCESS;
    public String FAIL;
    private boolean isFindSd = false;
    private static StorageManager mStorageManager = null;
    private static boolean is_Usb=false;
    TextView mResult;
    private static boolean isSDFirstTest =true;
    public static String flash_dir = Environment.getExternalStorageDirectory().getPath();
    private static StatFs stat=null;
    private StorageInfo mTestStorage;
    protected STORAGE_TYPE mStorageType = STORAGE_TYPE.USB_HOST;
 
    public enum STORAGE_TYPE {
        USB_HOST,
        PCIE,
        SATA,
    }
 
    protected void preData() {
 
    }
 
    protected void childTest(){}
    protected void dealMessage(Message msg) {}
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
 
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
 
        // requestWindowFeature(Window.FEATURE_NO_TITLE);
        // getWindow().addFlags(1152);
        setContentView(R.layout.usbhosttest);
        preData();
        isSDFirstTest =true;
        if (mStorageManager == null) {
            mStorageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
        }
        this.mResult = (TextView) findViewById(R.id.sdresultText);
        this.mResult.setVisibility(View.VISIBLE);
        this.mResult.setGravity(17);
        TextView textTitle = (TextView) findViewById(R.id.textTitle);
        textTitle.setText(getTestTitle());
 
        ControlButtonUtil.initControlButtonView(this);
        SUCCESS = getString(R.string.success);
        FAIL = getString(R.string.fail);
      
    }
 
    @Override
    protected void onResume() {
        super.onResume();
        findViewById(R.id.btn_Pass).setVisibility(View.INVISIBLE);
        findViewById(R.id.btn_Fail).setVisibility(View.INVISIBLE);
        init_StoragePath(this);
       // mStorageManager.registerListener(mStorageListener);
        StorageVolume[] storageVolumes = mStorageManager.getVolumeList();
        Log.d(TAG, " storageVolumes.length= " + storageVolumes.length);
        for(int i=0;i< storageVolumes.length;i++)
            {
                Log.d(TAG, " storageVolumes["+i+"].getPath()=" +storageVolumes[i].getPath());
            }
        /*if(storageVolumes.length >= 2){
            sdcard_path = storageVolumes[1].getPath();*/
      
        //SDCARD_PATH=sdcard_path;
        //Log.d(TAG, "  storageVolumes[1].getPath()= " + SDCARD_PATH + "   "+","+  Environment.getExternalStorageDirectory());
            //Log.d(TAG, "  storageVolumes[0].getPath()= " + storageVolumes[0].getPath());
        //}
        sBuilder = new StringBuilder();
        //String sdState = getSdCardState();
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            isFindSd=true;
 
            mResult.setText(getString(R.string.resume_findSD));
            mHandler.sendEmptyMessageDelayed(SEND_REND_WRITE_SD, 1000);
        }
    }
 
    @Override
    protected void onPause() {
        super.onPause();
        if (mStorageManager != null) {
          //  mStorageManager.unregisterListener(mStorageListener);
        }
    }
    
 
    public void testSdcard() {
        try {
            if (null == mTestStorage || null == mTestStorage.getPath()) {
                sBuilder.append(getNotStoragePathFailTxt()).append("\n");
                mResult.setText(sBuilder.toString());
                mHandler.sendEmptyMessageDelayed(R_FAIL, 3000);
                isFindSd = false;
                return;
            }
           // String externalVolumeState = mStorageManager.getVolumeState(SDCARD_PATH);
            //if (!externalVolumeState.equals(Environment.MEDIA_MOUNTED)) {
              //  sBuilder.append(getString(R.string.SdCardFail)).append("\n");
                //mResult.setText(sBuilder.toString());
                //mHandler.sendEmptyMessageDelayed(R_FAIL, 3000);
                //isFindSd = false;
                //return;
           // }
        } catch (Exception rex) {
             
            rex.printStackTrace();
            isFindSd = false;
            mHandler.sendEmptyMessageDelayed(R_FAIL, 3000);
            return;
        }
 
        File pathFile = new File(mTestStorage.getPath());
        Log.d(TAG, "pathFile = " + pathFile.toString());
        if (!pathFile.exists()) {
            sBuilder.append(getNotStoragePathFailTxt()).append("\n");
            mResult.setText(sBuilder.toString());
            mHandler.sendEmptyMessageDelayed(R_FAIL, 3000);
            isFindSd = false;
            return;
        }
       try {
             stat = new StatFs(pathFile.getPath());
        } catch (Exception e) {
            e.printStackTrace();
            sBuilder.append(getNotStoragePathFailTxt()).append("\n");
        mResult.setText(sBuilder.toString());
        mHandler.sendEmptyMessageDelayed(R_FAIL, 3000);
        isFindSd = false;
        return;
        }
        
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        String totalSize = Formatter.formatFileSize(this, totalBlocks
                * blockSize);
            if ("0.00 B".equals(totalSize)) {
                sBuilder.append(getNotStoragePathFailTxt()).append("\n");
        mResult.setText(sBuilder.toString());
        mHandler.sendEmptyMessageDelayed(R_FAIL, 3000);
        isFindSd = false;
         return; 
            }
        String prix = "";
        if (STORAGE_TYPE.PCIE == mStorageType) {
            prix = getString(R.string.PCIEFind);
        } else if (STORAGE_TYPE.SATA == mStorageType) {
            prix = getString(R.string.SATAFind);
        } else if (STORAGE_TYPE.USB_HOST == mStorageType) {
            prix = getString(R.string.UsbFind);
        }
        sBuilder.append(prix + totalSize).append("\n");
        try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        testReadAndWrite();
       
    }
 
    private String getTestTitle() {
        if (STORAGE_TYPE.PCIE == mStorageType) {
            return getString(R.string.PCIETestTitle);
        } else if (STORAGE_TYPE.SATA == mStorageType) {
            return getString(R.string.SATATestTitle);
        } else if (STORAGE_TYPE.USB_HOST == mStorageType) {
            return getString(R.string.UsbHostTestTitle);
        }
        return "";
    }
 
    private String getNotStoragePathFailTxt() {
        if (STORAGE_TYPE.PCIE == mStorageType) {
            return getString(R.string.PCIETestFail);
        } else if (STORAGE_TYPE.SATA == mStorageType) {
            return getString(R.string.SATATestFail);
        } else if (STORAGE_TYPE.USB_HOST == mStorageType) {
            return getString(R.string.UsbHostTestFail);
        }
        return "";
    }
 
    public void testReadAndWrite() {
        if (isFindSd && dotestReadAndWrite()) {
            sBuilder.append(getTestTitle() + SUCCESS);
            mResult.setText(sBuilder.toString());
            ((Button)findViewById(R.id.btn_Skip)).setClickable(false);
            //((Button)findViewById(R.id.btn_Pass)).setClickable(false);
            ((Button)findViewById(R.id.btn_Fail)).setClickable(false);
            if (STORAGE_TYPE.PCIE == mStorageType) {
                childTest();
            } else if (STORAGE_TYPE.USB_HOST == mStorageType
                && Build.VERSION.SDK_INT == ConfigUtil.ANDROID_SDK_VERSION_R) {
                dotestHostSpeed(mTestStorage.getSysPath());
            } else {
                mHandler.sendEmptyMessageDelayed(R_PASS, BACK_TIME);
            }
        } else {
            sBuilder.append(getTestTitle() + FAIL);
            mResult.setText(sBuilder.toString());
            ((Button)findViewById(R.id.btn_Skip)).setClickable(false);
            ((Button)findViewById(R.id.btn_Pass)).setClickable(false);
            //((Button)findViewById(R.id.btn_Fail)).setClickable(false);
            mHandler.sendEmptyMessageDelayed(R_FAIL, BACK_TIME);
        }
    }
 
    private void dotestHostSpeed(String sysPath) {
        //String test = "/sys//devices/platform/usbhost/fd000000.dwc3/xhci-hcd.0.auto/usb60/6-1/6-1:1.0/host1/target1:0:0/1:0:0:0/block/sda'}";
        Pattern pattern = Pattern.compile(".*/(usb)(\\d+)/\\d-\\d/");
        Matcher matcher = pattern.matcher(sysPath);
        String lastStorageResult = "";
        if (null != mResult.getText() && null != mResult.getText().toString()) {
            lastStorageResult = mResult.getText().toString();
        }
        if (matcher.find()) {
            String strSpeed = SystemUtil.execShellCmd(
                    "cat " + matcher.group() + "speed");
            if ("5000".equals(strSpeed)) {
                mResult.setText(lastStorageResult + "\n\nusb3.0");
            } else if("480".equals(strSpeed)) {
                mResult.setText(lastStorageResult + "\n\nusb2.0");
            } else if ("12".equals(strSpeed)) {
                mResult.setText(lastStorageResult + "\n\nusb1.1");
            } else {
                mResult.setText(lastStorageResult + "\n\n" + strSpeed + ", unknown usb type");
            }
            findViewById(R.id.btn_Pass).setVisibility(View.VISIBLE);
            findViewById(R.id.btn_Pass).setClickable(true);
            findViewById(R.id.btn_Fail).setVisibility(View.VISIBLE);
            findViewById(R.id.btn_Fail).setClickable(true);
        } else {
            mResult.setText(lastStorageResult + "\n\n" + sysPath);
            mHandler.sendEmptyMessageDelayed(R_FAIL, BACK_TIME);
        }
    }
 
    private boolean dotestReadAndWrite() {
       // String directoryName = Environment.getExternalStorageDirectory().toString()+ "/test";
        String directoryName = mTestStorage.getPath() + "/test";
        File directory = new File(directoryName);
        if (!directory.isDirectory()) {
            if (!directory.mkdirs()) {
                sBuilder.append(getString(R.string.MakeDir) + FAIL).append("\n");
                return false;
            } else {
                sBuilder.append(getString(R.string.MakeDir) + SUCCESS).append(
                        "\n");
            }
        }
        File f = new File(directoryName, "SDCard.txt");
        try {
            // Remove stale file if any
            if (f.exists()) {
                f.delete();
            }
            if (!f.createNewFile()) {
                sBuilder.append(getString(R.string.CreateFile) + FAIL).append(
                        "\n");
                return false;
            } else {
                sBuilder.append(getString(R.string.CreateFile) + SUCCESS).append(
                        "\n");
 
                doWriteFile(f.getAbsoluteFile().toString());
 
                if (doReadFile(f.getAbsoluteFile().toString()).equals(
                        TEST_STRING)) {
                    sBuilder.append(getString(R.string.Compare)).append(SUCCESS).append(
                            "\n");
                } else {
                    sBuilder.append(getString(R.string.Compare)).append(FAIL).append(
                            "\n");
                    return false;
                }
            }
 
            sBuilder.append(getString(R.string.FileDel)).append(
                    (f.delete() ? SUCCESS : FAIL)).append("\n");
            sBuilder.append(getString(R.string.DirDel)).append(
                    (directory.delete() ? SUCCESS : FAIL)).append("\n");
            return true;
        } catch (IOException ex) {
            Log.e(TAG, "isWritable : false (IOException)!");
            return false;
        }
    }
 
    public void doWriteFile(String filename) {
        try {
            sBuilder.append(getString(R.string.WriteData)).append("\n");
            OutputStreamWriter osw = new OutputStreamWriter(
                                                            new FileOutputStream(
                                                                                 filename));
            osw.write(TEST_STRING, 0, TEST_STRING.length());
            osw.flush();
            osw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    public String doReadFile(String filename) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader
                    (new FileInputStream(filename)));
            String data = null;
            StringBuilder temp = new StringBuilder();
            sBuilder.append(getString(R.string.ReadData)).append("\n");
            while ((data = br.readLine()) != null) {
                temp.append(data);
            }
            br.close();
            Log.e(TAG, "Readfile " + temp.toString());
            return temp.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
    /*
    public class SdcardReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e(TAG, "onReveive ..... " + intent.getAction());
            if (intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED)) {
                 Log.e(TAG, "239 ..... " + intent.getAction()); 
                testSdcard();
                testReadAndWrite();
            }
        }
    }
   */
/*StorageEventListener mStorageListener = new StorageEventListener() {
        @Override
        public void onStorageStateChanged(String path, String oldState, String newState) {
             Log.d("xxxxxxxxxxxxxxxxxxxxxxxxxxxx","yyyyyyyyyyyyyyyyyyyyyyyyyyyy");
            if (path.equals(SDCARD_PATH) && newState.equals(Environment.MEDIA_MOUNTED)) {
                isFindSd=true;
 
                mResult.setText(getString(R.string.resume_findSD));
                mHandler.sendEmptyMessageDelayed(SEND_REND_WRITE_SD, 100);
            testReadAndWrite();
            }
      }
  };*/
    
    public void TestResult(int result) { 
        if (result == R_PASS) {
           if(isSDFirstTest){
               isSDFirstTest=false;
               ((Button) findViewById(R.id.btn_Pass)).performClick();
               isFindSd = false;
           }
            
        } else if (result == R_FAIL) {
            if(isSDFirstTest){
                isSDFirstTest=false;
                ((Button) findViewById(R.id.btn_Fail)).performClick();
                isFindSd = false;
            }
        }
    }
 
    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case R_PASS:
                    TestResult(R_PASS);
                    break;
                case R_FAIL:
                    TestResult(R_FAIL);
                    break;
              
                case SEND_REND_WRITE_SD:
                
                   testSdcard();
                    break;
                default:
                    dealMessage(msg);
                    break;
            }
        };
    };
    /*
    public static String getSdCardState() {
        try {
            IMountService mMntSvc = null;
            if (mMntSvc == null) {
                mMntSvc = IMountService.Stub.asInterface(ServiceManager
                                                         .getService("mount"));
            }
            return mMntSvc.getVolumeState(USB_PATH);
        } catch (Exception rex) {
            return Environment.MEDIA_REMOVED;
        }
 
    }
   */
    //获取外置sd卡路径
    private static String getStoragePath(Context mContext, boolean is_removale) {  
 
          mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
            Class<?> storageVolumeClazz = null;
            try {
                storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
                Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
                Method getPath = storageVolumeClazz.getMethod("getPath");
                Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
                Object result = getVolumeList.invoke(mStorageManager);
                final int length = Array.getLength(result);
                for (int i = 0; i < length; i++) {
                    Object storageVolumeElement = Array.get(result, i);
                    String path = (String) getPath.invoke(storageVolumeElement);
                    boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
                    if (is_removale == removable) {
                        return path;
                    }
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            return null;
    }
 
    public void init_StoragePath(Context context) {
        mStorageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
        flash_dir = Environment.getExternalStorageDirectory().getPath();
        final List<VolumeInfo> volumes = mStorageManager.getVolumes();
        Collections.sort(volumes, VolumeInfo.getDescriptionComparator());
        for (VolumeInfo vol : volumes) {
            if (vol.getType() != VolumeInfo.TYPE_PUBLIC) {
                continue;
            }
            Log.d(TAG, "Volume path:" + vol.getPath());
            DiskInfo disk = vol.getDisk();
            if (null == disk) {
                continue;
            }
            if (STORAGE_TYPE.PCIE == mStorageType) {
                if (null != disk.sysPath && disk.sysPath.contains(".pcie/")) {
                    StorageVolume sv = vol.buildStorageVolume(context,
                            context.getUserId(), false);
                    mTestStorage = new StorageInfo(sv.getPath(), disk.sysPath);
                    break;
                }
            } else if (STORAGE_TYPE.SATA == mStorageType) {
                if (null != disk.sysPath && disk.sysPath.contains(".sata/")) {
                    StorageVolume sv = vol.buildStorageVolume(context,
                            context.getUserId(), false);
                    mTestStorage = new StorageInfo(sv.getPath(), disk.sysPath);
                    break;
                }
            } else if (STORAGE_TYPE.USB_HOST == mStorageType) {
                if (disk.isUsb() && null != disk.sysPath
                        && !disk.sysPath.contains(".pcie/")
                        && !disk.sysPath.contains(".sata/")) {
                    StorageVolume sv = vol.buildStorageVolume(context,
                            context.getUserId(), false);
                    mTestStorage = new StorageInfo(sv.getPath(), disk.sysPath);
                    break;
                }
            } else if (disk.isSd()) {
 
            }
        }
        Log.d(TAG, "mTestStorageInfo: " + mTestStorage);
    }
//判断sd卡是否挂载
private boolean isSDMounted() {  
      boolean isMounted = false;  
      StorageManager sm = (StorageManager) getSystemService(Context.STORAGE_SERVICE);  
  
      try {  
          Method getVolumList = StorageManager.class.getMethod("getVolumeList", null);  
          getVolumList.setAccessible(true);  
          Object[] results = (Object[])getVolumList.invoke(sm, null);  
          if (results != null) {  
              for (Object result : results) {  
                  Method mRemoveable = result.getClass().getMethod("isRemovable", null);  
                  Boolean isRemovable = (Boolean) mRemoveable.invoke(result, null);  
                  if (isRemovable) {  
                      Method getPath = result.getClass().getMethod("getPath", null);  
                      String path = (String) mRemoveable.invoke(result, null);  
                      Method getState = sm.getClass().getMethod("getVolumeState", String.class);  
                      String state = (String)getState.invoke(sm, path);  
                      if (state.equals(Environment.MEDIA_MOUNTED)) {  
                          isMounted = true;  
                          break;  
                      }  
                  }  
              }  
          }  
      } catch (NoSuchMethodException e){  
          e.printStackTrace();  
      } catch (IllegalAccessException e){  
          e.printStackTrace();  
      } catch (InvocationTargetException e) {  
          e.printStackTrace();  
      }  
  
      return isMounted;  
  }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
}