Android Studio code Notes - USB interface, reading and writing files, string segmentation, input device information, etc

Keywords: Android Android Studio android-studio

USB interface

Universal Serial Bus (USB) is not only a serial bus standard, but also a technical specification of input and output interfaces. It is widely used in information communication products such as personal computers and mobile devices, and extended to photography equipment, digital television (set-top box), game consoles and other related fields.
USB is an external bus standard, which regulates the connection and communication between computer and external devices. USB interface has hot plug function. USB interface can connect a variety of peripherals, such as mouse and keyboard.

Broadcast listening event of USB external storage device

Broadcast when the state of an external storage device changesSD card, U SB flash disk and other external storage devices
ACTION_MEDIA_BAD_REMOVALThe external storage media has been removed from the SD card slot, but its mounting node has not been unloaded. The path of the mount node is still contained in the Intent.mData field.
ACTION_MEDIA_BUTTONThe Media button is pressed. Includes an additional field, EXTRA_KEY_EVENT, which causes the broadcast to contain the key event
ACTION_MEDIA_CHECKINGExternal storage media exists and will be checked. The path of the mount node is contained in the Intent.mData field.
ACTION_MEDIA_EJECTThe user expressed the wish to delete the external storage media. When the application receives this intention, it should close all files open on this mount node.
ACTION_MEDIA_MOUNTEDThe external storage media exists and has been mounted successfully. The path of the mount node is contained in the Intent.mData field. In addition, Intent also contains a "read-only" Boolean additional information to indicate whether the storage medium is read-only, ant green
AcTION_MEDIA_NOFSExternal storage media exists, but the system is not compatible with it. The path of the mount node is contained in the Intent.mData field.
ACTION_MEDIA_REMOVEDExternal storage media has been removed. The path of the attached node is contained in the Intent.mData field.
AeTION_MEDIA_SCANNER_FINISHEDThe storage media scanner completes a path scan. The scanned path is contained in the Intent.mData field.
ACTION_MEDIA_SCANNER_SCAN_PILERequests the media scanner to scan a file and add it to the media database. The scanned file path is contained in the Intent.mData field.
ACTION_MEDIA_SCANNER_STARTEDThe storage media scanner starts scanning a directory. Include the path to be scanned in the Intent.mData field.

There are four situations

  1. When inserting an external SD card:
    android.intent.action.MEDIA_CHECKING
    android.intent.action.MEDIA_MOUNTED
    android.intent.action.MEDIA_SCANNER_STARTED
    android.intent.action.MEDIA_SCANNER_FINISHED
  2. When removing an external SD card:
    android.intent.action.MEDIA_EJECT
    android.intent.action.MEDIA_UNMOUNTED
    android.intent.action.MEDIA_SCAnER_STARTED
    android.intent.action.MEDIA_BAD_REMOVAL
    android.intent.action.MEDIA_SCANMNER_FINISHED
  3. When connecting PC and entering USB mass storage mode:
    android.intent.action.MEDIA_EJECT
    android.intent.action.MEDIA_UNMOUNTED
    android.intent.action.MEDIA_UNMOUNTED
    android.intent.action.MEDIA_SHARED
  4. When connecting PC and exiting USB mass storage mode:
    android.intent.action.MEDIA_UNMAOUNTED
    android.intent.action.MEDIA_CHECKING
    android.intent.action.MEDIA_MOUNTED
    android.intent.action.MEDIA_SCANNER_STARTED
    android.intent.action.MEDIA_SCANNER_FINISHED

Dynamically register the broadcast, use the plug-in broadcast to monitor the access pop-up of the USB storage device, and remember to log off the broadcast

    @Override
    protected void onResume(){
        super.onResume();
        IntentFilter intentFilter_USB = new IntentFilter();
        intentFilter_USB.addAction("com.android.example.USB_PERMISSION");
        intentFilter_USB.addAction(ACTION_USB_DEVICE_ATTACHED);//Action USB device connected
        intentFilter_USB.addAction(ACTION_USB_DEVICE_DETACHED);//Action USB device detached
        intentFilter_USB.addAction(ACTION_MEDIA_MOUNTED);//Action media installation
        intentFilter_USB.addAction(ACTION_MEDIA_REMOVED);//Mobile media deleted
        registerReceiver(receiver_USB, intentFilter_USB);
    }
    private BroadcastReceiver receiver_USB = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            switch (action) {
                case ACTION_USB_DEVICE_ATTACHED:
                    Log.i("LXH", "USB Device connection");
                    break;
                case ACTION_USB_DEVICE_DETACHED:
                    Log.i("LXH", "USB Device disconnected");
                    break;
                case ACTION_MEDIA_MOUNTED:
                    Log.i("LXH", "USB Loading complete");
                    break;
                case ACTION_MEDIA_UNMOUNTED:
                    Log.i("LXH", "USB Unmount");
                    break;
            }
        }
    };
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver_USB);
    }

After running, connect the USB flash disk to the USB interface, and then pop up the USB flash disk. The log is

onResume() is executed when the activity can interact with the user. The user can get the focus of the activity and interact with the user. onResume() is onPause() (usually the current acitivity is suspended, such as being overwritten by another transparent or dialog style activity). After that, the dialog is cancelled, the activity returns to the interactive state, and onResume() is called. See an article Difference between onstart and resumed.

USB external storage device acquisition

Obtain the external storage device on the USB interface and insert two USB disks into the interface. If the connection is not a storage device but an input device, such as mouse, keyboard and light, it will not be displayed

UsbManager usbManager;//USB initialization
PendingIntent pendingIntent;//USB permissions
UsbDevice usbDevice_link;//USB device
usbManager = (UsbManager)getSystemService(Context.USB_SERVICE);
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent("com.android.example.USB_PERMISSION"), 0);
HashMap<String, UsbDevice> deviceHashMap = usbManager.getDeviceList();
Iterator<UsbDevice> iterator = deviceHashMap.values().iterator();
while (iterator.hasNext()) {
    UsbDevice device = iterator.next();
    Log.i("LXH","Obtained USB Equipment has DeviceName:"+device.getDeviceName()+",VendorId:"+device.getVendorId()+",ProductId:"+device.getProductId());
    usbDevice_link=device;
}

Run log:
Get USB interface external storage device address

   /**
     * @LXH Get the path of USB A interface
     * @return A Path of interface
     */
    public String get_USBpath_A() {
        String USBpath_A = "";
        File file_a = new File("/mnt/sda/");//Hisilicon U SB flash disk mounting path
        if (file_a.exists()) {
            for (File subFile : file_a.listFiles()) {
                File findFile = new File(subFile.getPath());
                if (findFile.exists()) {
                    Tag_USB_a = true;
                    USBpath_A = findFile.getPath();
                    text_USB_a = USBpath_A;
                    Log.i("LXH", "Get current USB Interface path has A:" + text_USB_a);
                    break;
                }
            }
        }
        return USBpath_A;
    }

Run log

file

Gets the specified file path

 /**
     * @LXH Gets the specified file path
     * @return specify the path to a file
     */
    public String  get_Filepath_LXH(){
        String filepath_LXH="";
        File file=new File("/mnt/sda/");
        if(file.exists())
        {
            for (File subFile :file.listFiles())
            {
                File findFile=new File(subFile.getPath()+"/LXH.txt");
                if(findFile.exists())
                {
                    file_usb=subFile;
                    Tag_USB_pz=true;
                    filepath_LXH=findFile.getPath();
                    text_USB_pz=filepath_LXH;
                    Log.i("LXH","U Specified file path under disk:"+text_USB_pz);
                    break;
                }
            }
        }
        return filepath_LXH;
    }

Get all files under file

    File ffile = new File(text_USB_a);
    get_Fileall(ffile);
/**
     * @LXH Get all files under file
     * @param path This document
     */
    public void get_Fileall(File path){
        File files[] = path.listFiles();
        if(files != null){
            for (File f : files){
                if(f.isDirectory()){
                    get_Fileall(f);
                }else{
                    Log.i("LXH","Under this document:" + f);
                }
            }
        }
    }

Read data under file path

       try {
            get_File(text_path);
        } catch (IOException e) {
            e.printStackTrace();
        }
/**
     * @LXH Read data under file path
     * @param filePathName
     * @return  Data type read: String
     * @throws IOException
     */
    public String get_File(String filePathName) throws IOException {
        String get_file="";
        StringBuffer stringBuffer = new StringBuffer();
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            FileInputStream fileInputStream = new FileInputStream(filePathName);
            byte[] buffer = new byte[1024];
            int len = fileInputStream.read(buffer);
            while (len > 0) {
                stringBuffer.append(new String(buffer, 0, len));
                len = fileInputStream.read(buffer);
            }
            fileInputStream.close();
        }
        get_file=stringBuffer.toString();
        text_USB_pznr=get_file;Tag_USB_pznr=true;
        Log.i("LXH","The contents of the read file are:"+get_file);
        return get_file;
    }

Write data to file path

        try {
            write_File(text_path,"configure=1,\nversion=2,\nLXH=5,");
        } catch (IOException e) {
            e.printStackTrace();
        }
/**
     * @LXH Write file data in
     * @param filePathName file
     * @param content Data string
     * @throws IOException
     */
    public void write_File(String filePathName, String content) throws IOException {
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            FileOutputStream fileOutputStream = new FileOutputStream(filePathName);
            fileOutputStream.write(content.getBytes());
            fileOutputStream.close();
        }
    }

String delimitation

configure=1,
version=2,

/**
     * @LXH Split string
     * @param filedata character string
     */
    public void split_String(String filedata){
        String str = null;
        str = filedata;
        if (str != null) {
            String[] arrayOfString1 = str.split(",");
            for (int i = 0; i < arrayOfString1.length; i++) {
                String string = arrayOfString1[i];
                if (string.contains("configure")){
                    Log.i("LXH",string.split("=")[0]+" The value of is:"+string.split("=")[1]);
                } else if (string.contains("version")) {
                    Log.i("LXH",string.split("=")[0]+" The value of is:"+string.split("=")[1]);
                }
            }
        }
    }

The contents of the read file are: configure=1,
version=2,
LXH=5,
The value of configure is: 1
The value of version is: 2

Posted by jpaloyo on Thu, 04 Nov 2021 17:04:47 -0700