2017-02-08 25 views
-1

我刚刚用Android Studio编写了我的第一个Android应用程序。这是一个词汇训练和它在一个文本文件在我的资产文件夹启动时,它包含的所有单词读(到现在为止,我只〜1000)是这样的:英语$ $日本类别。所以,我认为这应该不是太多工作,即使我有一个旧的三星S2。但开始需要10秒,有时会崩溃。Android应用程序太慢。如何加速?

这里的关键代码:

static String word; 
static String[] listOfWords; 

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    readWords(); 
    generateRandomWord(); 
} 

public void readWords() { 
    try { 
     InputStream is = getAssets().open("words.txt"); 
     String ww = ""; 
     int data = is.read(); 
     while(data != -1){ 
      ww += (char) data; 
      data = is.read(); 
     } 
     listOfWords = ww.split("\n"); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

public void generateRandomWord() { 
    TextView textView = new TextView(this); 
    textView.setTextSize(40); 
    textView = (TextView) findViewById(R.id.text_id); 

    Random random = new Random(); 
    int randomKey = random.nextInt(listOfWords.length-1); 
    String line = listOfWords[randomKey]; 
    String[] parts = line.split("/"); 
    Log.d("Tango-renshuu", "line: "+line+" "+parts.length+" "+parts[1]); 
    textView.setText(parts[1]); 
    word = parts[2]; 
} 

,当我尝试从另外一个回到那个活动发生同样的事情,即使我使用Intent.FLAG_ACTIVITY_CLEAR_TOP像这样:

public void back(View view) { 
    Intent intent = new Intent(this, MainActivity.class); 
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    startActivity(intent); 
} 

任何想法或你认为它只是我的设备?

感谢

回答

0

readWords方法是相当低效的:要创建在每次循环迭代一个新的字符串,而你通过字符读取文件的字符。考虑使用BufferedReader读通过直接线串线:

InputStream stream = getAssets().open("words.txt"); 
BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); 
ArrayList<String> lines = new ArrayList<String>(); 
String line; 
while ((line = reader.readLine()) != null) { 
    lines.add(line); 
} 
listOfWords = lines.toArray(new String[lines.size()]); 
reader.close(); 

如果你的代码仍然是这个优化后的速度太慢,那么你应该将这个代码移动到AsyncTask所以至少它不会冻结UI ,还可以显示在此期间加载微调。

+0

谢谢,它的工作就好了。 – user1734984

2

您正在阅读的主线程的资产,你需要开始一个任务加载它,而活动呈现资产加载发生在后台。