Tutorials‎ > ‎

Simple Android Chat Application Part 1


Android real time application is an interesting area of study. It's has been much easier developing such application these days. Using Google Cloud Messaging (GCM) we can create a real time application, which a server can send a request to mobile device as a client without a device send the request first. In this tutorial, I'll going to show how to create a chat application that based on GCM. 

Tools that will be used in this tutorial:
  • Android Studio, IDE to code android application
  • Android SDK with minimum android version 2.2
  • Intellij, IDE to code java as the web server
  • Wildfly, as the java web server container
To create this android chat application we need to do the following steps:
  1. Enable GCM in Google Developer Console
  2. Setup GCM Android library in android studio
  3. Register GCM token id from android device to web server
  4. Create a web server to store android token id
  5. Code the user interface for chat application
  6. Broadcast all incoming message to all connected android device
Enable GCM in Google Developer Console
  1. First create a new project in https://console.developers.google.com/ and named it SimpleAndroidChat
  2. In the left navigation bar, click on APIs & Auth > APIs, then it will show all API that google provides
  3. In Mobiles APIs, click on Cloud Messaging for Android, then click Enable API
  4. In the left navigation bar, click on APIs & Auth > Credentials, then click Add credential Button and chose API Key
  5. Then it will popup a dialog. After that click server key button, and name it AndroidChatServerKey
  6. Later we will use this API key to send a message from a web server to GCM server.
Setup GCM Android library in android studio
  1. Get google-service.json configuration file that is specific for our application. 
    1.1.  Open this link: https://developers.google.com/mobile/add?platform=android&cntapi=gcm&cnturl=https:%2F%2Fdevelopers.google.com%2Fcloud-messaging%2Fandroid%2Fclient&cntlbl=Continue%20Adding%20GCM%20Support&%3Fconfigured%3Dtrue
    1.2.  Choose SimpleAndroidChat as an app name.
    1.3.  Then write bluejack.tutorial.android.chat as out package name.
    1.4.  Choose your country, for example Indonesia
    1.5.  Click continue and configure service button
    1.6.  Click enable cloud messaging service button
    1.7.  Click generate configuration files button
    1.8.  Click download google-service.json button
  2. Create a new android project
    2.1.  Create a new project and specify 
    bluejack.tutorial.android.chat as it's package name
    2.2. Copy google-service.json file into your {project-name}/app directory
    2.3. In your build.gradle project level add the following line in the buildscript dependency section
           classpath 'com.google.gms:google-services:1.4.0-beta3'
    2.4. In your build.gradle app level add the following line at the top level
           apply plugin: 'com.google.gms.google-services'
    2.5. In your build.gradle app level add the following line in dependency section
           compile "com.google.android.gms:play-services:8.1.0" // library for gcm
           compile "com.mcxiaoke.volley:library:1.0.19" // library to send http request
    2.6. Add the following <uses-persmission> and <permission> in AndroidManifest.xml inside <manifest> tag:
    <uses-permission android:name="android.permission.INTERNET" /> <!-- to allow internet akses -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> <!-- to register and receive message from gcm service -->
    <permission android:name="com.example.gcm.permission.C2D_MESSAGE" android:protectionLevel="signature" />
    <uses-permission android:name="bluejack.tutorial.android.chat.permission.C2D_MESSAGE" /><!-- prevent other application to register and receive message -->
Register GCM token id from android device to web server
  1. Create an Intent Service that will get a gcm token string.
    Right click on the package bluejack.tutorial.android.chat, then choose New > Service > Service (IntentService)
    Named it RegisterTokenIntentService
  2. Write the following code to receive gcm token id:
    public class RegisterTokenIntentService extends IntentService {

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

    @Override
    protected void onHandleIntent(Intent intent) {
    InstanceID instanceID = InstanceID.getInstance(this);

    try {
    String token = instanceID.getToken(
    getString(R.string.gcm_defaultSenderId),
    GoogleCloudMessaging.INSTANCE_ID_SCOPE,
    null);

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(new StringRequest(
    Request.Method.GET,
    "http://192.168.1.126:8080/AndroidChatServer/register?token=" + token,
    null,
    null
    ));
    requestQueue.start();

    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    -. In my case, I already setup a web server that listen to 192.168.1.126:8080, but you can use any ip address where you start the web server. For now we haven't setup the web server yet, in the next step we will discuss about it.
    -. We use Volley to send a http request, containing the token id specified as a query params.
    -. String request is a http request that has a string as its response type.
  3. From MainActivity (Or if there is no activity yet, create a new activity and make it as Main Activity with intent filter in AndroidManifest.xml)
    start the previous intent service using the following code:
    public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent i = new Intent(this, RegisterTokenIntentService.class);
    startService(i);
    }
    }

Create a web server to store android token id
  1. Create a new web application project.
    1.1.  File > New > Project
    1.2.  Choose Java Enteprise, then check web application
    1.3.  Named the project AndroidChatServer
  2. Create a new servlet to handle token request. For the sake of simplicity, this token will be stored in application context
    2.1.  Under AndroidChatServer's src folder, right click New > Java Class
    2.2.  Named it RegisterTokenServlet
    2.3. Write the following code within the RegisterTokenServlet.java
    @WebServlet(urlPatterns = "/register")
    public class RegisterTokenServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String token = req.getParameter("token");

    List<String> tokens = (List<String>) req.getServletContext().getAttribute("tokens");
    if(tokens == null) tokens = new ArrayList<>();
    tokens.add(token);
    req.getServletContext().setAttribute("tokens", tokens);

    resp.getWriter().println("Success receive token: " + token);
    }
    }

  3. Deploying the project
    3.1.  Open Project Structure (Ctrl + Shift + Alt + S)
    3.2.  Choose artifact, create a new artifact chose Web Application: Archive based on the current project
    3.3.  Open Run/Debug Configuration
    3.4.  If there is no web server chosen yet, click + icon on the upper left corner side, then choose jboss server, and locate the wildfly server
    3.5.  In the deployment tab, choose the previous artifact that we make
    3.6.  In Startup / Connection tab, add argument "-b 0.0.0.0" to the script, so that our web server listen to any interface in the current machine.
           for example: standalone.sh -b 0.0.0.0
    3.7.  If you run the web server outside the ide, make sure that the server listen to 0.0.0.0 address.
  4. Then clik run icon.
The next following steps will be explain in the next tutorial. I hope you guys can setup the basic configuration for GCM application.