Recently i was doing a project for my client where in it was required to access a USB bar code scanner manufactured by MARSON Tech, Taiwan. The USB scanner when connected to the Android handset, was detected as a HID keyboard and a external mass storage device.

The only way to trigger the scanner is to Create a file with name "HTA02100.000" in the mass storage device. Since the USB scanner detected as a mass storage device is a external memory there is no straight forward way to access it in Android Lollipop OS. Because, starting from Android Kit Kat release, Google has prevented third party applications from accessing the external storage devices, But this had become a big problem for developers, and due to the huge demand they have released something called as a Storage Access Framework, which is  a set of API which can be used to access external storage devices be it a external SD card or a USB mass storage device.

"These API are available for only Android Lollipop and above. This didn't work for me on Android Kit Kat. "

The main requirement of this API is that the application can ask the user to provide permission to access a particular path on a external storage device, and once the user provides the permission the application can therefore access that particular path and do whatever it wants like creating a file/folder or deleting modifying etc. 

So the first step is to use the API to open up the Android system file browser dialog and prompt the user to select the folder/path. 

It should show something like this, but it will also show a external storage device if you have inserted any,

The user should browse to the desired external storage mount path and once he selects the path , a URI is returned by the dialog which the application can use to access that particular path whenever it wants in future even after reboot. 

 

Here is the code i used to get access to the storage, 

MainActivity.java

View source
 
package com.valetron.myapplication;
 
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.provider.DocumentFile;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
 
import java.io.File;
import java.io.OutputStream;
 
public class MainActivity extends Activity {
 
    Context context = this;
    EditText input;
 
    public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
        if (resultCode == RESULT_OK) {
            Uri treeUri = resultData.getData();
            DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);
 
            String SDPATH = Environment.getExternalStorageDirectory().getPath();
            File pathFile = new File(SDPATH+"/Valetron/", "ScanPath");
            if(!pathFile.exists())
            {
                      // Save the returned file path /URI
                      lib.WriteFile("ScanPath", treeUri.toString(), context);
 
            } 
 
        }
    }
  
    public void triggerButtonClick(View v)
    {
 
        Uri treeUri = Uri.parse(lib.ReadFile("ScanPath",getApplicationContext()));
 
        DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);
        // List all existing files inside picked directory
        for (DocumentFile file : pickedDir.listFiles()) {
            input.setText("Found file " + file.getName() + " with size " + file.length());
            file.delete();
        }
        // Create a new file and if you want you can write into it
        DocumentFile newFile = pickedDir.createFile("application/octet-stream", "HTA02100.000");
 
    }
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        input = (EditText) findViewById(R.id.editText2);
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        startActivityForResult(intent, 42);
    }
  
}
 

 

Contents of my lib.java library class

 

 

lib.java

View source
 
package com.valetron.myapplication;
 
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.provider.DocumentFile;
import android.widget.Toast;
 
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
//import android.content.Context;
 
public class lib
{
    
    public static String ReadFile(String FileName,Context context)
    {
        String temp="";
        try {
            String SDPATH = Environment.getExternalStorageDirectory().getPath();
            File secondInputFile = new File(SDPATH+"/Valetron/", FileName);
            InputStream secondInputStream = new BufferedInputStream(new FileInputStream(secondInputFile));
            BufferedReader r = new BufferedReader(new InputStreamReader(secondInputStream));
            StringBuilder total = new StringBuilder();
            String line;
            while ((line = r.readLine()) != null) {
                total.append(line);
            }
            r.close();
            secondInputStream.close();
            temp = total.toString();
 
 
 
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(context, e.toString(),Toast.LENGTH_LONG).show();
        }
        return temp;
    }
 
    public static void WriteFile(String FileName, String Data,Context context)
    {
 
        try {
            String SDPATH = Environment.getExternalStorageDirectory().getPath();
            File secondFile = new File(SDPATH+"/Valetron/", "ScanPath");
            if (secondFile.getParentFile().mkdirs())
            {
                secondFile.createNewFile();
                FileOutputStream fos = new FileOutputStream(secondFile);
 
                fos.write(Data.getBytes());
                fos.flush();
                fos.close();
            }
            else
            {
 
                FileOutputStream fos = new FileOutputStream(secondFile);
 
                fos.write(Data.getBytes());
                fos.flush();
                fos.close();
 
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            Toast.makeText(context, e.toString(),Toast.LENGTH_LONG).show();
        }
 
    }
    }
 
 

 

Also make sure you put all the right permissions in your AndroidManifest.xml file 

I used <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> in my case.

 

My activity_main.xml file contents

 

activity_main.xml

View source
 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
 
    <TextView android:text="Press button to trigger scan" android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView">
    </TextView>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
 
 
        android:id="@+id/editText1"
        android:ems="10"
        android:hint="Scanned data" >
        <requestFocus />
    </EditText>
 
 
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Scan"
        android:id="@+id/button"
        android:onClick="triggerButtonClick"
 
        android:layout_below="@+id/editText1"
 
         />
 
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
 
        android:layout_below="@+id/button"
        android:id="@+id/editText2"
        android:ems="10"
        android:hint="Log data" >
 
 
    </EditText>
</RelativeLayout>
 
 

Hope it helps someone !




About the Author

is the author of this blog and is an Embedded systems design engineer by profession & Founder @ Valetron Systems Pvt Ltd


Email:This email address is being protected from spambots. You need JavaScript enabled to view it.

Find us on Google+

HIRE ME FOR YOUR PROJECT AS A FREELANCER

 

EasyEDA: Free Circuit Design Software

  • Easy Schematic Capture
  • Powerful Circuit Simulation
  • Online PCB design

Design Your Circuit and PCB here:

https://easyeda.com/editor

PCB Prototype Manufacturer - JLCPCB

Electronic Components Online Store