Android:在运行需要一段时间才能完成的代码时,Activity会冻结

时间:2015-05-27 13:45:09

标签: android json runnable

我正在处理的应用程序从服务器获取JSON并且必须解释它们。我有大约6-7个JSON请求。

因此,这肯定需要一些时间。

只要用户向EditText输入信息并单击按钮,就会运行此代码。单击搜索按钮后,应用程序将冻结,并且在加载所有数据之前不会执行任何操作。

我尝试过这样的代码:

    Button button = (Button) findViewById(R.id.search_button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            InputMethodManager imm = (InputMethodManager) getSystemService(
                    Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(summonerNameET.getWindowToken(), 0);
            final CollectUserData c = new CollectUserData();
            c.setRegion(region);
            c.setSummonerName(summonerNameET.getText().toString());

            Runnable r = new Runnable() {
                @Override
                public void run() {
                    try {
                        c.setUpTheJSONs();
                        updateUI(c);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                }
            };
            r.run();


        }
    });

但它仍然冻结。这是setUpTheJSON();

的代码
public void setUpTheJSONs() throws IOException, JSONException, URISyntaxException {
    jsonSummonerInfo = getJsonSummonerInfo();
    if(canIContinue()) {
        jsonSummonerStats = getJsonSummaryStats();
        //jsonSummonerRankedStats = getJsonRankedStats();
        jsonSummonerMatchHistory = getJsonMatchHistory();
        jsonSummonerLeagueInfo = getJsonSummonerLeagueInfo();
        jsonSummonerRecentGames = getJsonSummonerRecentGames();
    }
}

这是unpdateUI(c)的代码;

public void updateUI(CollectUserData c) {
    if (c.canIContinue()) {
        String league = "";
        try {
            league = c.getMundaneCurrentLeague();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        setLeague(tierIV, league);
        try {
            summonerNameTV.setText(c.getSummonerName());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            tierTV.setText(c.getTier());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            leaguePointsTV.setText(c.getLeaguePoints() + "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            winsTV.setText("W: " + c.getWins());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        slashTV.setText("/");
        try {
            lossesTV.setText("L: " + c.getLosses());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            lastSeasonRankTV.setText("Season 4: " + c.getRankOfLastSeason());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            gameModeGameOneTV.setText(c.getGameType(1));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            gameOneChampion.setBackground(c.getChampionPicturePlayed(1));
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            gameOneKillsTV.setText(c.getKills(1) + "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        gameOneSlashOneTV.setText(" / ");
        try {
            gameOneDeathsTV.setText(c.getDeaths(1) + "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        gameOneSlashTwoTV.setText(" / ");
        try {
            gameOneAssistsTV.setText(c.getAssists(1) + "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            gameOneGoldTV.setText(c.getGold(1) + " K");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            gameOneCSTV.setText(" " + c.getMinionsKilled(1) + " CS");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        boolean gameOneWon = true;
        try {
            gameOneWon = c.isGameWon(1);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (gameOneWon) {
            gameOneTitleBar.setBackgroundColor(Color.parseColor("#d604c429"));
            gameOne.setBackgroundColor(Color.parseColor("#4600FF06"));
        }
        if (!gameOneWon) {
            gameOneTitleBar.setBackgroundColor(Color.parseColor("#d6ff0100"));
            gameOne.setBackgroundColor(Color.parseColor("#4fff0100"));
        }
        try {
            gameOneItemOneIV.setBackground(c.getItemFromMatchHistory(1, 0, getResources()));
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            gameOneItemTwoIV.setBackground(c.getItemFromMatchHistory(1, 1, getResources()));
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            gameOneItemThreeIV.setBackground(c.getItemFromMatchHistory(1, 2, getResources()));
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            gameOneItemFourIV.setBackground(c.getItemFromMatchHistory(1, 3, getResources()));
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            gameOneItemFiveIV.setBackground(c.getItemFromMatchHistory(1, 4, getResources()));
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            gameOneItemSixIV.setBackground(c.getItemFromMatchHistory(1, 5, getResources()));
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Drawable[] tempDrawable = null;
        try {
            tempDrawable = c.getTeamPlayerChampionIcon(1, 100);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (tempDrawable != null) {
            gameOneTeamOnePlayerOne.setBackground(tempDrawable[0]);
            gameOneTeamOnePlayerTwo.setBackground(tempDrawable[1]);
            gameOneTeamOnePlayerThree.setBackground(tempDrawable[2]);
            gameOneTeamOnePlayerFour.setBackground(tempDrawable[3]);
            gameOneTeamOnePlayerFive.setBackground(tempDrawable[4]);
        }
        Drawable[] tempDrawable2 = null;
        try {
            tempDrawable2 = c.getTeamPlayerChampionIcon(1, 200);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (tempDrawable != null) {
            gameOneTeamTwoPlayerOne.setBackground(tempDrawable2[0]);
            gameOneTeamTwoPlayerTwo.setBackground(tempDrawable2[1]);
            gameOneTeamTwoPlayerThree.setBackground(tempDrawable2[2]);
            gameOneTeamTwoPlayerFour.setBackground(tempDrawable2[3]);
            gameOneTeamTwoPlayerFive.setBackground(tempDrawable2[4]);
        }
        String[] tempString = null;
        try {
            tempString = c.getTeamPlayerName(1, 100);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (tempString != null) {
            gameOneTeamOnePlayerOneName.setText(tempString[0]);
            gameOneTeamOnePlayerTwoName.setText(tempString[1]);
            gameOneTeamOnePlayerThreeName.setText(tempString[2]);
            gameOneTeamOnePlayerFourName.setText(tempString[3]);
            gameOneTeamOnePlayerFiveName.setText(tempString[4]);
        }
        String[] tempString2 = null;
        try {
            tempString2 = c.getTeamPlayerName(1, 200);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (tempString2 != null) {
            gameOneTeamTwoPlayerOneName.setText(tempString2[0]);
            gameOneTeamTwoPlayerTwoName.setText(tempString2[1]);
            gameOneTeamTwoPlayerThreeName.setText(tempString2[2]);
            gameOneTeamTwoPlayerFourName.setText(tempString2[3]);
            gameOneTeamTwoPlayerFiveName.setText(tempString2[4]);
        }

    }

}

任何人都知道修复此问题吗?

谢谢☺

3 个答案:

答案 0 :(得分:1)

您需要引入多线程。 r.run()命令需要由另一个线程启动。

http://developer.android.com/training/multiple-threads/index.html

答案 1 :(得分:0)

您在UI线程中运行 Runnable ,这就是为什么您的 UI被阻止直到完成为止。
尝试这样的事情:

    Button button = (Button) findViewById(R.id.search_button);
    button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        InputMethodManager imm = (InputMethodManager) getSystemService(
                Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(summonerNameET.getWindowToken(), 0);
        final CollectUserData c = new CollectUserData();
        c.setRegion(region);
        c.setSummonerName(summonerNameET.getText().toString());

        new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        c.setUpTheJSONs();
                        updateUI(c);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                }
        }).start();
    }
});

答案 2 :(得分:0)

将下载文件放在单独的线程中。使用AsyncTask或Java Thread。只是简单。

class MyTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
      super.onPreExecute();
      //Show progress dialog, if u want
    }

    @Override
    protected Void doInBackground(Void... params) {

     //Do all your processing here! 

      return null;
    }

    @Override
    protected void onPostExecute(Void result) {
      super.onPostExecute(result);
      //Return some result to UI
    }
  }