AsyncTask 从服务器获取全局游戏分数

AsyncTask to fetch global game scores from a server

我是 android 的新手,对 AsyncTasks 完全不解。我需要创建一个排行榜,它将从服务器中提取全球排行榜分数。

我在下面发布了在 LeaderboardsFragment 中创建的用于访问和显示分数的两个方法 - getGlobalScores 和 readStream。

我不确定如何在 AsyncTask 中使用这些 - 主要是如何以及将什么参数传递给 AsyncTask - 我一直在看的大多数教程都不处理二维数组。任何提示将不胜感激,我真的很难理解与此相关的文献。

package uk.ni.appidemic.whackamole;

import java.io.BufferedReader;

public class LeaderboardsFragment extends Fragment {

    AssetStore AS;
    private TextView TopScores;
    private String[][] global_scores = new String[10][3];

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_leaderboards, container, false);

        //Go and get the asset store from the activity
        AS = WhackAMoleActivity.getAssetManager();

        TopScores = (TextView) rootView.findViewById(R.id.leaderboards);

        // Extract and display the top score text view from the preferences
        displayLocalScores();

        // this method is used to send a highscore to the server (name and score)
        // this method may get pulled out to the gameloop as its the only place it should be used in the final game
        // but this can be used for testing purposes atm (Server needs to be on)
        // sendScoreGlobal("porter", 1001);



        //async Get global scores from the server and display them - new thread
        new AsyncOperation().execute();


        ...................

    public void getGlobalScores() {

        //gets global score in HTML format to be parsed

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        try {
            URL url = new URL("http://62........./high_scores");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            readStream(con.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /gets the data and stores the global scores in a 2d array
    //it then displays to screen
    public void readStream(InputStream in) {
        BufferedReader reader = null;
        try {
            StringBuilder htmlIn = new StringBuilder();

            StringBuilder globalScoreBuilder = new StringBuilder();

            htmlIn.append("");
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                htmlIn.append(line);
            }

            // String to be scanned to find the pattern.
            String html = htmlIn.toString();
            String regexPattern = "<td align=\"left\" style=\"padding-left:10px;\">(\d+?)</td>|<td align=\"right\" style=\"padding-right:10px;\">(\w+?)</td>";

            // Create a Pattern object
            Pattern patternObject = Pattern.compile(regexPattern);

            // Now create matcher object.
            Matcher matcherObject = patternObject.matcher(html);

            Log.d(getActivity().getResources().getString(R.string.LOG_TAG), "Trying to find regex matches");
            TopScores.append("\n");
            int nextFreePointer = 0;
            int rowCount = 0;

            while (matcherObject.find()) {
                if (matcherObject.group(1) != null) {
                    Log.d(getActivity().getResources().getString(R.string.LOG_TAG), "Regex match : " + matcherObject.group(1));
                    globalScoreBuilder.append(matcherObject.group(1) + " ");
                    global_scores[rowCount][nextFreePointer] = matcherObject.group(1);
                    nextFreePointer++;
                }
                if (matcherObject.group(2) != null) {
                    Log.d(getActivity().getResources().getString(R.string.LOG_TAG), "Regex match : " + matcherObject.group(2));
                    globalScoreBuilder.append(matcherObject.group(2) + " ");
                    global_scores[rowCount][nextFreePointer] = matcherObject.group(2);
                    nextFreePointer++;
                }

                if (nextFreePointer > 2) {
                    nextFreePointer = 0;
                    rowCount++;
                }

                globalScoreBuilder.append("\n");

            }

            StringBuilder sb = new StringBuilder();
            String lineSeparator = System.getProperty("line.separator");

            for (String[] row : global_scores) {
                sb.append(Arrays.toString(row)).append(lineSeparator);
            }

            String text = sb.toString();

            TopScores.append("Global Top 10 Scores\n");

            TopScores.append(text);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public class AsyncOperation extends AsyncTask<String, Void, Void>{

        protected void onPreExecute(){

        }//end of onPreExecute

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



        }//doinBackground       


        protected void onProgressUpdate(Void... values){

        }//onProgressUpdate


        protected void onPostExecute(Void... result){

        }//end of onPostExecute    


    }//end of AsyncOperation inner class

}//end of Leaderboards class

不在我的工作站,但我认为这样的事情应该可行。

public class AsyncOperation extends AsyncTask<String, Void, Void>{

    private String[][] global_scores = new String[10][3];

    protected void onPreExecute(){
        // optionally show loading indicator
        TopScores.append("\n");
    }//end of onPreExecute

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

        try {
            URL url = new URL("http://62........./high_scores");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            readStream(con.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }//doinBackground       


    protected void onProgressUpdate(Void... values){

    }//onProgressUpdate


    protected void onPostExecute(Void... result){
        // optionally hide loading indicator
        StringBuilder sb = new StringBuilder();
        String lineSeparator = System.getProperty("line.separator");

        for (String[] row : global_scores) {
            sb.append(Arrays.toString(row)).append(lineSeparator);
        }

        String text = sb.toString();

        TopScores.append("Global Top 10 Scores\n");

        TopScores.append(text);
    }//end of onPostExecute    


    private void readStream(InputStream in) {
        BufferedReader reader = null;
        try {
            StringBuilder htmlIn = new StringBuilder();

            StringBuilder globalScoreBuilder = new StringBuilder();

            htmlIn.append("");
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                htmlIn.append(line);
            }

            // String to be scanned to find the pattern.
            String html = htmlIn.toString();
            String regexPattern = "<td align=\"left\" style=\"padding-left:10px;\">(\d+?)</td>|<td align=\"right\" style=\"padding-right:10px;\">(\w+?)</td>";

            // Create a Pattern object
            Pattern patternObject = Pattern.compile(regexPattern);

            // Now create matcher object.
            Matcher matcherObject = patternObject.matcher(html);

            Log.d(getActivity().getResources().getString(R.string.LOG_TAG), "Trying to find regex matches");

            int nextFreePointer = 0;
            int rowCount = 0;

            while (matcherObject.find()) {
                if (matcherObject.group(1) != null) {
                    Log.d(getActivity().getResources().getString(R.string.LOG_TAG), "Regex match : " + matcherObject.group(1));
                    globalScoreBuilder.append(matcherObject.group(1) + " ");
                    global_scores[rowCount][nextFreePointer] =    matcherObject.group(1);
                    nextFreePointer++;
                }
                if (matcherObject.group(2) != null) {
                       Log.d(getActivity().getResources().getString(R.string.LOG_TAG), "Regex match : "     + matcherObject.group(2));
                    globalScoreBuilder.append(matcherObject.group(2) + " ");
                    global_scores[rowCount][nextFreePointer] = matcherObject.group(2);
                    nextFreePointer++;
                }

                if (nextFreePointer > 2) {
                    nextFreePointer = 0;
                    rowCount++;
                }

                globalScoreBuilder.append("\n");

            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}//end of AsyncOperation inner class

您应该通过扩展 AsynTask 的网络服务 class 获取您的游戏分数。下面是我用来安全获取远程数据的 class。

代码:

public class WebServiceRestTask extends AsyncTask<HttpUriRequest, Void, Object> {
    private static final String TAG = "WebServiceRestTask";
    private AbstractHttpClient mClient;
    private WeakReference<WebServiceRestCallback> mCallback;
    private int ws_task;

    public WebServiceRestTask(int ws_task) {
        this(new DefaultHttpClient(), ws_task);

    }

    public WebServiceRestTask(AbstractHttpClient client, int task_number) {
        mClient = client;
        this.ws_task = task_number;
    }

    public interface WebServiceRestCallback {
        public void onRequestSuccess(String response);

        public void onRequestError(Exception error);
    }

    public void setResponseCallback(WebServiceRestCallback callback) {
        mCallback = new WeakReference<WebServiceRestCallback>(callback);
    }

    @Override
    protected Object doInBackground(HttpUriRequest... params) {
        try {
            HttpUriRequest request = params[0];
            HttpResponse serverResponse = mClient.execute(request);

            BasicResponseHandler handler = new BasicResponseHandler();
            String response = handler.handleResponse(serverResponse);
            return response + ws_task;
        } catch (Exception e) {
            Log.w(TAG, e);
            return e;
        }
    }

    @Override
    protected void onPostExecute(Object result) {
        if (mCallback != null && mCallback.get() != null) {
            if (result instanceof String) {
                mCallback.get().onRequestSuccess((String) result);
            } else if (result instanceof Exception) {
                mCallback.get().onRequestError((Exception) result);
            } else {
                mCallback.get().onRequestError(
                        new IOException("Unknown Error Contacting Host"));
            }
        }
    }

}