如何在AsyncTask中执行网络操作 - Android

时间:2015-07-10 01:31:22

标签: android android-asynctask

我是Android新手,我使用单击按钮发送使用GCM的推送通知。我有执行GCM推送的功能。我需要将它从函数转换为AsyncTask类。我从互联网上看到了很多,但仍然面临着麻烦。任何人都可以帮我转换吗?

推送功能

public void sendPush(int position){
   pushProgressBar.setVisibility = (View.VISIBLE)

        try {
            // Prepare JSON containing the GCM message content. What to send and where to send.
            JSONObject jGcmData = new JSONObject();
            JSONObject jData = new JSONObject();
            jData.put("message", "Hello");
            // Where to send GCM message.
            TinyDB tinyDB = new TinyDB(mContext);
            ArrayList<String> userToken = tinyDB.getListString("tokenList");
            String tokenToSend = userToken.get(position);
            jGcmData.put("to", tokenToSend);
            // What to send in GCM message.
            jGcmData.put("data", jData);

            // Create connection to send GCM Message request.
            URL url = new URL("https://android.googleapis.com/gcm/send");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Authorization", "key=" + R.string.apikey);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);

            // Send GCM message content.
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(jGcmData.toString().getBytes());

            // Read GCM response.
            InputStream inputStream = conn.getInputStream();
            String resp = IOUtils.toString(inputStream);
            System.out.println(resp);
            System.out.println("Check your device/emulator for notification or logcat for " +
                    "confirmation of the receipt of the GCM message.");

            pushProgressBar.setVisibility = (View.GONE)
        } catch (IOException e) {
            System.out.println("Unable to send GCM message.");
            System.out.println("Please ensure that API_KEY has been replaced by the server " +
                    "API key, and that the device's registration token is correct (if specified).");
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

提前致谢。希望我从中吸取教训。

1 个答案:

答案 0 :(得分:1)

示例基本AsyncTask:

    class PushTask extends AsyncTask<Integer, Integer, Integer> {


        @Override
        protected void onPreExecute() {
                  pushProgressBar.setVisibility = (View.VISIBLE);
        }

       @Override
        protected Integer doInBackground(Integer... position) {
              int post = position[0];
              int respCode = 0;

              try {
              //your sending code here..
              //got gcm code
              respCode = 1;

              } catch (IOException e) {
              //json IOException 
              //cannot send gcm
              respCode = 2; 
              } catch (JSONException e) {
              //json Exception
              respCode = 3; 
              }


              return respCode;
        }

        @Override
        protected void onPostExecute(Integer response) {

                 switch(response)
                     case 1:
                       System.out.println("Check your device/emulator for notification or logcat for " +
                       "confirmation of the receipt of the GCM message.");
                     break;
                     case 2:
                        System.out.println("Please ensure that API_KEY has been replaced by the server " +
                        "API key, and that the device's registration token is correct (if specified).");
                     break;
                     case 3:
                        //print json Exception error
                     break;  
                     default:
                     break;                     
                 pushProgressBar.setVisibility = (View.GONE);
        }
    }

您可以通过执行

来执行该类
new PushTask().execute(1 or your position);
  

这只是示例,您可以根据需要修改代码。