Buzz
Buzz

Reputation: 25

Error in Google Cloud Messaging GCM for Android and Push Notifications

i am using GCM for sending and receiving push notifications to and from an Android application. I was creating this app form an example given here (Google Cloud Messaging GCM for Android and Push Notifications)

these are java file i am using

MainActivity.java

 import android.app.Activity;
 import android.content.Context;
 import android.os.AsyncTask;
 import android.os.Bundle;
 import android.util.Log;
 import android.widget.Toast;

    public class MainActivity extends Activity {

    ShareExternalServer appUtil;
    String regId;
    AsyncTask shareRegidTask;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    appUtil = new ShareExternalServer();

    regId = getIntent().getStringExtra("regId");
    Log.d("MainActivity", "regId: " + regId);

    final Context context = this;
    shareRegidTask = new AsyncTask() {

        protected String doInBackground(Void... params) {
            String result = appUtil.shareRegIdWithAppServer(context, regId);
            return result;
        }

        protected void onPostExecute(String result) {
            shareRegidTask = null;
            Toast.makeText(getApplicationContext(), result,
                    Toast.LENGTH_LONG).show();
        }

    };
    shareRegidTask.execute(null, null, null);
}

}

final Context context = this;

shareRegidTask = new AsyncTask()

there is an error on AsyncTask()

GCMNotificationService.java

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.android.gms.gcm.GoogleCloudMessaging; 

public class GCMNotificationIntentService extends IntentService {

public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;

public GCMNotificationIntentService() {
    super("GcmIntentService");
}

public static final String TAG = "GCMNotificationIntentService";

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) {
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
                .equals(messageType)) {
            sendNotification("Send error: " + extras.toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
                .equals(messageType)) {
            sendNotification("Deleted messages on server: "
                    + extras.toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
                .equals(messageType)) {

            for (int i = 0; i < 3; i++) {
                Log.i(TAG,
                        "Working... " + (i + 1) + "/5 @ "
                                + SystemClock.elapsedRealtime());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                }

            }
            Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());

            sendNotification("Message Received from Google GCM Server: "
                    + extras.get(Config.MESSAGE_KEY));
            Log.i(TAG, "Received: " + extras.toString());
        }
    }
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

private void sendNotification(String msg) {
    Log.d(TAG, "Preparing to send notification...: " + msg);
    mNotificationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class), 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            this).setSmallIcon(R.drawable.gcm_cloud)
            .setContentTitle("GCM Notification")
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
            .setContentText(msg);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    Log.d(TAG, "Notification sent successfully.");
}
}

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(

this).setSmallIcon(R.drawable.gcm_cloud)

.setContentTitle("GCM Notification")

.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))

.setContentText(msg);

There is error at .gcm_cloud

ShareExternalServer.java

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import android.content.Context;
import android.util.Log;

public class ShareExternalServer {

public String shareRegIdWithAppServer(final Context context,
                                      final String regId) {

    String result = "";
    Map paramsMap = new HashMap();
    paramsMap.put("regId", regId);
    try {
        URL serverUrl = null;
        try {
            serverUrl = new URL(Config.APP_SERVER_URL);
        } catch (MalformedURLException e) {
            Log.e("AppUtil", "URL Connection Error: "
                    + Config.APP_SERVER_URL, e);
            result = "Invalid URL: " + Config.APP_SERVER_URL;
        }

        StringBuilder postBody = new StringBuilder();
        Iterator> iterator = paramsMap.entrySet()
                .iterator();

        while (iterator.hasNext()) {
            Entry param = iterator.next();
            postBody.append(param.getKey()).append('=')
                    .append(param.getValue());
            if (iterator.hasNext()) {
                postBody.append('&');
            }
        }
        String body = postBody.toString();
        byte[] bytes = body.getBytes();
        HttpURLConnection httpCon = null;
        try {
            httpCon = (HttpURLConnection) serverUrl.openConnection();
            httpCon.setDoOutput(true);
            httpCon.setUseCaches(false);
            httpCon.setFixedLengthStreamingMode(bytes.length);
            httpCon.setRequestMethod("POST");
            httpCon.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");
            OutputStream out = httpCon.getOutputStream();
            out.write(bytes);
            out.close();

            int status = httpCon.getResponseCode();
            if (status == 200) {
                result = "RegId shared with Application Server. RegId: "
                        + regId;
            } else {
                result = "Post Failure." + " Status: " + status;
            }
        } finally {
            if (httpCon != null) {
                httpCon.disconnect();
            }
        }

    } catch (IOException e) {
        result = "Post Failure. Error in sharing with App Server.";
        Log.e("AppUtil", "Error in sharing with App Server: " + e);
    }
    return result;
}
}

StringBuilder postBody = new StringBuilder();

Iterator> iterator = paramsMap.entrySet()

.iterator();

while (iterator.hasNext()) {

Entry param = iterator.next();

postBody.append(param.getKey()).append('=')

.append(param.getValue());

if (iterator.hasNext()) {

postBody.append('&');

} }

Error on iterator

I don't understand why these errors are rising as i'm following the example properly, please some one help me out.

Upvotes: 0

Views: 413

Answers (1)

Koh
Koh

Reputation: 1570

Your iterator was declared improperly (perhaps a typo). It should be Iterator iterator without the > sign.

Upvotes: 0

Related Questions