Kalai Arasi
Kalai Arasi

Reputation: 249

How to perform network operation in AsyncTask - Android

I am new to Android and I am using the a button click to send a push notification using GCM. I have the function to perform the GCM push. I need it to be converted from the function to a AsyncTask class. I saw a lot from the internet and still facing trouble. Can anyone help me to convert it ?

The push function

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


    }

Thanks in advance. Hope I learn from this.

Upvotes: 0

Views: 228

Answers (1)

zzas11
zzas11

Reputation: 1115

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

You can execute the class by execute

new PushTask().execute(1 or your position);

This is example only, you can modified the code according your requirement.

Upvotes: 1

Related Questions