简体   繁体   中英

Android SD card read

I have an application on Android which is started when the system boots. Sometimes the internet connection is in searching mode and i have put a timer to check the connection and then connect if found. Same thing i have done for sd card as it is also in preparing mode. I am facing a problem in reading text file from sd card when the system boots and app starts it never read the text from sd card. When i manually start the app later it works. Here is my code to read the sd card file.

 if (isSDCardAvailable())
            {
                setTickerText();
            }

    else if(!isSDCardAvailable())
            {
                //pop up message
                Toast toast=Toast.makeText(this, "Preparing SD card..", Toast.LENGTH_LONG);
                toast.show();

                //Run the sd card read process after 30 seconds
                Handler handler = new Handler(); 
                handler.postDelayed(new Runnable() { 
                     public void run() 
                     { 
                         setTickerText();
                     } 
                }, 30000);
            }

 public void setTickerText()
{
    File sdcard = Environment.getExternalStorageDirectory();

    //Get the text file
    File file = new File(sdcard,"TickerText.txt");

    //Read text from file
    StringBuilder text = new StringBuilder();

    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;

        while ((line = br.readLine()) != null) {
            text.append(line);
            //text.append('\n');
        }
    }
    catch (IOException e) {
        //You'll need to add proper error handling here
    }
       }

After complation System boot your app is start reading file.

so before that you can check this way:

static public boolean hasStorage(boolean requireWriteAccess) {
    //TODO: After fix the bug,  add "if (VERBOSE)" before logging errors.
    String state = Environment.getExternalStorageState();
    Log.v(TAG, "storage state is " + state);

    if (Environment.MEDIA_MOUNTED.equals(state)) {
        if (requireWriteAccess) {
            boolean writable = checkFsWritable();
            Log.v(TAG, "storage writable is " + writable);
            return writable;
        } else {
            return true;
        }
    } else if (!requireWriteAccess && Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        return true;
    }
    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM