2013-03-28 137 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