2013-03-28 140 views
0

我有一个在系统启动时启动的Android应用程序。有时互联网连接处于搜索模式,我已经设置了一个计时器来检查连接,然后连接,如果找到。同样的事情,我已经做了SD卡,因为它也在准备模式。我在从系统启动时读取SD卡上的文本文件时遇到问题,并且应用程序启动时,它从不读取SD卡上的文本。当我手动启动应用程序后,它的作品。这是我的代码来读取SD卡文件。Android SD卡读取

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 
    } 
     } 

回答

0

complation后系统启动您的应用程序开始读取文件。

所以在这之前你可以检查此方式:

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; 
} 
+0

这个答案是错的。 Environment.getExternalStorageState()并不总是返回外部存储。 – 2013-09-08 18:30:31