Android应用太慢了。加速的方法?

时间:2017-02-08 17:53:52

标签: android performance app-startup

我刚用Android Studio编写了我的第一个Android应用程序。它是一个词汇训练师,它在启动时读入我的资产文件夹中的文本文件,其中包含所有单词(到现在为止,我只有~1000),如下所示:english $ japanese $ category。所以,我认为这不应该是很多工作,即使我有一个旧的三星S2。但它需要10秒才能启动,有时它会崩溃。

这是关键代码:

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

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

感谢

2 个答案:

答案 0 :(得分:2)

您正在主线程上读取资产,您需要启动一个任务来加载它,而活动将被渲染,资产加载发生在后台。

答案 1 :(得分: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,并且您可以同时显示加载微调器。 / p>