Android Open Source - RavenChat Dispatch Message Intent Service






From Project

Back to project page RavenChat.

License

The source code is released under:

Copyright (c) 2014 Sumit Gouthaman. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Softwar...

If you think the Android project RavenChat listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.sumitgouthaman.raven.services;
/*from w w  w  .  j a v  a 2  s .c  o m*/
import android.app.IntentService;
import android.content.Intent;

import com.sumitgouthaman.raven.R;
import com.sumitgouthaman.raven.models.Message;
import com.sumitgouthaman.raven.models.MessageTypes;
import com.sumitgouthaman.raven.persistence.Persistence;
import com.sumitgouthaman.raven.utils.crypto.EncryptionUtils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Service that is invoked to send a regular chat message.
 * It picks up unsent messages form the dispatch queue and sends it.
 * Tries 3 times in case of network problems.
 */
public class DispatchMessageIntentService extends IntentService {

    public DispatchMessageIntentService() {
        super("DispatchMessageIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            String regId = intent.getStringExtra("registrationID");
            String secretUsername = intent.getStringExtra("targetSecretUsername");
            String encKey = intent.getStringExtra("encKey");

            /**
             * Pick up next message from the queue of unsent messages.
             */
            Message toBeSent = Persistence.getMessageFromQueue(this, secretUsername);

            /**
             * Construct the object representing the message to be sent
             */
            JSONObject messageJSON = new JSONObject();
            String messageText = "";
            try {
                messageJSON.put("secretUsername", Persistence.getSecretUsername(this));
                String finalMessageText = null;
                /**
                 * If the encKey is not null, encrypt the message text
                 */
                if (encKey != null) {
                    finalMessageText = EncryptionUtils.encrypt(toBeSent.messageText, encKey);
                } else {
                    finalMessageText = toBeSent.messageText;
                }

                messageJSON.put("messageText", finalMessageText);
                messageText = messageJSON.toString();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            String result = null;
            int retries = 3; //Number of times to try in case of network error

            while (result == null && retries > 0) {
                try {
                    if (retries == 2) {
                        Thread.sleep(3000);
                    } else if (retries == 1) {
                        Thread.sleep(5000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    HttpClient client = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost("https://android.googleapis.com/gcm/send");
                    httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
                    httpPost.addHeader("Authorization", "key=" + getString(R.string.api_key));
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                    JSONObject data = new JSONObject();
                    data.put("messageType", MessageTypes.MORNAL_MESSAGE);
                    data.put("messageText", messageText);
                    nameValuePairs.add(new BasicNameValuePair("data", data.toString()));
                    nameValuePairs.add(new BasicNameValuePair("registration_id", regId));
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
                    HttpResponse response = client.execute(httpPost);
                    HttpEntity entity = response.getEntity();
                    result = EntityUtils.toString(entity, "UTF-8");
                } catch (Exception ie) {
                    ie.printStackTrace();
                    result = null;
                }
                retries--;
            }

            if (result == null) {
                //Message failed to send. 0 in timestamp indicates this to ChatThreadAdaptor
                toBeSent.timestamp = 0l;
            } else {
                //Sent successfully
                toBeSent.timestamp = System.currentTimeMillis();
            }

            //Add message to actual list of messages for this contact
            //Add message to actual list of messages for this contact
            Persistence.addMessage(this, secretUsername, toBeSent);
            //Remove message from the unsent queue
            Persistence.removeMessageFromQueue(this, secretUsername);
        }
    }
}




Java Source Code List

com.sumitgouthaman.raven.AddContactActivity.java
com.sumitgouthaman.raven.ChatThreadActivity.java
com.sumitgouthaman.raven.DebugActivity.java
com.sumitgouthaman.raven.DispatchGCMMessage.java
com.sumitgouthaman.raven.GCMBroadcastReceiver.java
com.sumitgouthaman.raven.MessageListActivity.java
com.sumitgouthaman.raven.NFCPairing.java
com.sumitgouthaman.raven.SelfDestructingMessageCompose.java
com.sumitgouthaman.raven.SelfDestructingMessageDisplay.java
com.sumitgouthaman.raven.SettingsActivity.java
com.sumitgouthaman.raven.ShareViaRaven.java
com.sumitgouthaman.raven.IntentHelpers.IntentCreator.java
com.sumitgouthaman.raven.listadapters.ChatThreadAdapter.java
com.sumitgouthaman.raven.listadapters.MessageListAdapter.java
com.sumitgouthaman.raven.models.Contact.java
com.sumitgouthaman.raven.models.MessageListItem.java
com.sumitgouthaman.raven.models.MessageTypes.java
com.sumitgouthaman.raven.models.Message.java
com.sumitgouthaman.raven.persistence.Persistence.java
com.sumitgouthaman.raven.services.DispatchMessageIntentService.java
com.sumitgouthaman.raven.services.DispatchNameUpdateMessageIntentService.java
com.sumitgouthaman.raven.services.DispatchRegUpdateMessageIntentService.java
com.sumitgouthaman.raven.services.DispatchRejectionMessageIntentService.java
com.sumitgouthaman.raven.services.TTSService.java
com.sumitgouthaman.raven.utils.CheckPlayServices.java
com.sumitgouthaman.raven.utils.MessageDispatcher.java
com.sumitgouthaman.raven.utils.RandomStrings.java
com.sumitgouthaman.raven.utils.SimpleNotificationMaker.java
com.sumitgouthaman.raven.utils.SimpleSoundNotificationMaker.java
com.sumitgouthaman.raven.utils.StringToQRBitmap.java
com.sumitgouthaman.raven.utils.TimestampFormatter.java
com.sumitgouthaman.raven.utils.crypto.Base64Utils.java
com.sumitgouthaman.raven.utils.crypto.EncryptionUtils.java
com.sumitgouthaman.raven.utils.crypto.KeyGeneratorUtils.java