http://androidknowledgeblog.blogspot.com/2016/04/simple-chat-app-in-android.html
Today we are build chat app using gcm (Google Cloud messaging).
Today we are build chat app using gcm (Google Cloud messaging).
Prerequisite :
1) API KEY
2) SENDER ID = PROJECT NUMBER
3) GCM ID
4) API ( WEBSERVICE )
First two value (API KEY , SENDER ID) get using this VEDIO
How to get GCM ID next question in your mind right??
GCM ID get using coding i will show you in coding part.
And last need is Download API from HERE
I assuming that you are smart enough to Run this api in your local or server. So run this api and get this URL for later use. You can also use my api i uploaded in server just copy this url
chat_api.php
-
<?php
-
-
$method = $_SERVER['REQUEST_METHOD'];
-
-
switch ($method){
-
case 'GET':
-
get();
-
break;
-
case 'POST':
-
post();
-
break;
-
case 'PUT':
-
put();
-
break;
-
case 'DELETE':
-
delete();
-
break;
-
default :
-
break;
-
}
-
-
function get(){
-
$category;
-
for($i=0 ; $i<5 ; $i++){
-
$category[$i] = array(
-
'cat_id' => $i,
-
'cat_name' => 'first',
-
'cat_desc' => 'second'
-
);
-
}
-
-
-
$response = array(
-
'status' => '200',
-
'categories' => $category
-
);
-
-
header('Content-type: application/json');
-
echo json_encode($response);
-
}
-
-
function p(){
-
$text = $_POST['text'];
-
$response = array(
-
'result' => $text,
-
);
-
echo json_encode($response);
-
}
-
function post(){
-
-
$text = $_POST['text'];
-
//echo $text;
-
-
// API access key from Google API's Console
-
define( 'API_ACCESS_KEY', 'AIzaSyCGYYyl3FNVFORs3Cz1QAsvkvaqIrLjfuU' );
-
-
// pass here your GCM ID and other Mobile GCM ID
-
//if you use server then fetch GCM registration id coloumn array from database an pass it so everyone get notify
-
$registrationIds = array('dgiQy412lH8:APA91bEC6d8yngpmUDU0VUIkDCaO_f1jvYa-Mjk3mkRjlVLmJXZ1HDSLosH1cljFmt9AGZEhOd1taz7Zcf012spRUGGoxQi73CZFFCmspcskqTYsn4d_lBS1-DCbT5R5L79mOYojuluf');
-
// prep the bundle
-
$msg = array
-
(
-
'Message' => $text,
-
'title' => 'This is a title. title',
-
'subtitle' => 'This is a subtitle. subtitle',
-
'tickerText' => 'Ticker text here...Ticker text here...Ticker text here',
-
'vibrate' => 1,
-
'sound' => 1,
-
'largeIcon' => 'large_icon',
-
'smallIcon' => 'small_icon'
-
);
-
$fields = array
-
(
-
'registration_ids' => $registrationIds,
-
'data' => $msg
-
);
-
-
$headers = array
-
(
-
'Authorization: key=' . API_ACCESS_KEY,
-
'Content-Type: application/json'
-
);
-
-
$ch = curl_init();
-
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
-
curl_setopt( $ch,CURLOPT_POST, true );
-
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
-
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
-
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
-
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
-
$result = curl_exec($ch );
-
curl_close( $ch );
-
echo $result;
-
}
-
function put(){
-
echo 'PUT request';
-
}
-
function delete(){
-
echo 'DELETE request';
-
}
-
?>
<?php
$method = $_SERVER['REQUEST_METHOD'];
switch ($method){
case 'GET':
get();
break;
case 'POST':
post();
break;
case 'PUT':
put();
break;
case 'DELETE':
delete();
break;
default :
break;
}
function get(){
$category;
for($i=0 ; $i<5 ; $i++){
$category[$i] = array(
'cat_id' => $i,
'cat_name' => 'first',
'cat_desc' => 'second'
);
}
$response = array(
'status' => '200',
'categories' => $category
);
header('Content-type: application/json');
echo json_encode($response);
}
function p(){
$text = $_POST['text'];
$response = array(
'result' => $text,
);
echo json_encode($response);
}
function post(){
$text = $_POST['text'];
//echo $text;
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'AIzaSyCGYYyl3FNVFORs3Cz1QAsvkvaqIrLjfuU' );
// pass here your GCM ID and other Mobile GCM ID
//if you use server then fetch GCM registration id coloumn array from database an pass it so everyone get notify
$registrationIds = array('dgiQy412lH8:APA91bEC6d8yngpmUDU0VUIkDCaO_f1jvYa-Mjk3mkRjlVLmJXZ1HDSLosH1cljFmt9AGZEhOd1taz7Zcf012spRUGGoxQi73CZFFCmspcskqTYsn4d_lBS1-DCbT5R5L79mOYojuluf');
// prep the bundle
$msg = array
(
'Message' => $text,
'title' => 'This is a title. title',
'subtitle' => 'This is a subtitle. subtitle',
'tickerText' => 'Ticker text here...Ticker text here...Ticker text here',
'vibrate' => 1,
'sound' => 1,
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;
}
function put(){
echo 'PUT request';
}
function delete(){
echo 'DELETE request';
}
?>
here is my api(webservice) coding you have to change your API KEY and GCM ID in this file.
GCM ID is get using coding as i said before.So will tell you later.
STEP 1 :
Create project with empty activity in android studio. Then add this three library in your
gradle file. and compare my gradle to your gradle.
1) Play service for GCM
compile "com.google.android.gms:play-services-gcm:8.4.0"
2 & 3) Json parsing and post data using this two library (Volly , okhttp)
compile 'com.android.volley:volley:1.0.0' compile 'com.squareup.okhttp3:okhttp:3.2.0'
build.gradle (Module:app)
- apply plugin: 'com.android.application'
- android {
- compileSdkVersion 23
- buildToolsVersion "23.0.3"
- defaultConfig {
- applicationId "com.example.androiddeveloper.simplechat"
- minSdkVersion 14
- targetSdkVersion 23
- versionCode 1
- versionName "1.0"
- }
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
- }
- dependencies {
- compile fileTree(dir: 'libs', include: ['*.jar'])
- testCompile 'junit:junit:4.12'
- compile 'com.android.support:appcompat-v7:23.3.0'
- compile "com.google.android.gms:play-services-gcm:8.4.0"
- compile 'com.android.volley:volley:1.0.0'
- compile 'com.squareup.okhttp3:okhttp:3.2.0'
- }
Now we are moving to coding part. first create the design. rename it actvity_main.xml to activity_gcm.xml
activity_gcm.xml
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context=".MainActivity">
- <ListView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/listView"
- android:layout_alignParentTop="true"
- android:layout_alignParentLeft="true"
- android:layout_alignParentStart="true"
- android:layout_marginBottom="50dp" />
- <LinearLayout
- android:orientation="horizontal"
- android:layout_width="match_parent"
- android:layout_height="50dp"
- android:layout_alignParentBottom="true"
- android:layout_alignParentLeft="true"
- android:layout_alignParentStart="true">
- <EditText
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/etText"
- android:layout_weight="9" />
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Send"
- android:id="@+id/btnSend"
- android:layout_weight="1" />
- </LinearLayout>
- </RelativeLayout>
Now Copy this code into your MainActivity.java you can get the GCM ID from here.
Using this AsyncTask you get the GCM ID in Logcat (Android Monitor)
And paste this id into your api file.
- /*Post data using volley*/
- new AsyncTask<Void, Void, Void>(){
- @Override
- protected Void doInBackground(Void... params) {
- try {
- InstanceID instanceID = InstanceID.getInstance(getApplicationContext());
- final String token = instanceID.getToken("820466753885",
- GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
- Log.d(TAG, "GCM_ID : "+token);
- StringRequest stringRequest = new StringRequest(Request.Method.POST
- ,"http://104.237.134.200/android_test/push_notf.php?"
- ,new Response.Listener<String>() {
- @Override
- public void onResponse(String response) {
- Log.d(TAG, "onResponse: Success");
- }
- },
- new Response.ErrorListener() { @Override
- public void onErrorResponse(VolleyError error) {
- Log.d(TAG, "onErrorResponse: Error");
- }
- }
- ){
- @Override
- protected Map<String,String> getParams(){
- Map<String,String> params = new HashMap<String, String>();
- params.put("id",token);
- return params;
- }
- };
- requestQueue.add(stringRequest);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
- }.execute();
Here is the full code of MainActivity.java
MainActivity.java
- import android.content.Intent;
- import android.os.AsyncTask;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.ListView;
- import com.android.volley.Request;
- import com.android.volley.RequestQueue;
- import com.android.volley.Response;
- import com.android.volley.VolleyError;
- import com.android.volley.toolbox.StringRequest;
- import com.google.android.gms.gcm.GoogleCloudMessaging;
- import com.google.android.gms.iid.InstanceID;
- import java.io.IOException;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.concurrent.TimeUnit;
- import okhttp3.FormBody;
- import okhttp3.OkHttpClient;
- import okhttp3.RequestBody;
- public class MainActivity extends AppCompatActivity {
- public static final String TAG = "From GCM";
- RequestQueue requestQueue;
- static ListView listView;
- EditText etText;
- Button btnSend;
- public static ListViewAdapter listViewAdapter;
- String text;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_gcm);
- requestQueue = VolleySingleton.getInstance(getApplicationContext()).getRequestQueue();
- listView = (ListView) findViewById(R.id.listView);
- etText = (EditText) findViewById(R.id.etText);
- btnSend = (Button) findViewById(R.id.btnSend);
- listViewAdapter = new ListViewAdapter(this);
- listView.setAdapter(listViewAdapter);
- Intent intent = new Intent();
- intent.setAction("com.example.chat");
- sendBroadcast(intent);
- btnSend.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- text = etText.getText().toString();
- new AsyncTask<Void, Void, Void>(){
- @Override
- protected Void doInBackground(Void... params) {
- OkHttpClient client = new OkHttpClient.Builder()
- .connectTimeout(0, TimeUnit.SECONDS)
- .writeTimeout(0, TimeUnit.SECONDS)
- .readTimeout(0, TimeUnit.SECONDS)
- .build();
- RequestBody formBody = new FormBody.Builder()
- .add("text", text)
- .build();
- okhttp3.Request request = new okhttp3.Request.Builder()
- .url("http://openspace.tranetech.com/mis/chat.php")
- .post(formBody)
- .build();
- try {
- okhttp3.Response response = client.newCall(request).execute();
- String responseString = response.body().string();
- response.body().close();
- Log.d(TAG, "doInBackground: RESPONSE : "+responseString);
- } catch (Exception e){
- }
- return null;
- }
- }.execute();
- etText.setText("");
- }
- });
- /*Post data using volley*/
- new AsyncTask<Void, Void, Void>(){
- @Override
- protected Void doInBackground(Void... params) {
- try {
- InstanceID instanceID = InstanceID.getInstance(getApplicationContext());
- final String token = instanceID.getToken("820466753885",
- GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
- Log.d(TAG, "GCM_ID : "+token);
- StringRequest stringRequest = new StringRequest(Request.Method.POST
- ,"http://104.237.134.200/android_test/push_notf.php?"
- ,new Response.Listener<String>() {
- @Override
- public void onResponse(String response) {
- Log.d(TAG, "onResponse: Success");
- }
- },
- new Response.ErrorListener() { @Override
- public void onErrorResponse(VolleyError error) {
- Log.d(TAG, "onErrorResponse: Error");
- }
- }
- ){
- @Override
- protected Map<String,String> getParams(){
- Map<String,String> params = new HashMap<String, String>();
- params.put("id",token);
- return params;
- }
- };
- requestQueue.add(stringRequest);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
- }.execute();
- }
- }
Now add MyGcmListenerService.java in your project. This class is used for getting gcm response send by GCM server.
MyGcmListenerService.java
- import android.app.Notification;
- import android.app.NotificationManager;
- import android.app.PendingIntent;
- import android.content.Context;
- import android.content.Intent;
- import android.os.Bundle;
- import android.support.v4.app.NotificationCompat;
- import android.util.Log;
- import com.google.android.gms.gcm.GcmListenerService;
- import java.util.ArrayList;
- public class MyGcmListenerService extends GcmListenerService {
- public static final String TAG = "From Service";
- static String message;
- ArrayList<String> data1 = new ArrayList<>();
- @Override
- public void onMessageReceived(String from, Bundle data) {
- message = data.getString("Message");
- Log.d(TAG, "onMessageReceived: From "+from);
- Log.d(TAG, "onMessageReceived: Message "+ message);
- Intent intent = new Intent();
- intent.setAction("com.example.chat");
- intent.putExtra("message",message);
- sendBroadcast(intent);
- notifyUser(message);
- }
- public void notifyUser(String message){
- Intent intent = new Intent(getApplicationContext(), MainActivity.class);
- PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
- NotificationCompat.Builder notification = new NotificationCompat.Builder(getApplicationContext());
- notification.setAutoCancel(true)
- .setDefaults(Notification.DEFAULT_ALL)
- .setWhen(System.currentTimeMillis())
- .setSmallIcon(R.mipmap.ic_launcher)
- .setTicker("Demo")
- .setContentTitle("Demo Notification")
- .setContentText(message)
- .setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_SOUND)
- .setContentIntent(contentIntent)
- .setContentInfo("Info");
- NotificationManager notificationManager = (NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
- notificationManager.notify(10, notification.build());
- }
- }
Then create single listitem for the listview so user can see.
listview_item.xml
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <TextView
- android:id="@+id/rank"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_margin="5dp"
- android:padding="5dp" />
- </RelativeLayout>
Now add this java class adapter in you project.
ListViewAdapter.java
- import android.content.Context;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.BaseAdapter;
- import android.widget.TextView;
- import java.util.ArrayList;
- public class ListViewAdapter extends BaseAdapter {
- // Declare Variables
- Context context;
- LayoutInflater inflater;
- ArrayList<String> data;
- public ListViewAdapter(Context context
- ) {
- this.context = context;
- data = new ArrayList<>();
- }
- @Override
- public int getCount() {
- return data.size();
- }
- @Override
- public Object getItem(int position) {
- return data.get(position);
- }
- @Override
- public long getItemId(int position) {
- return position;
- }
- public View getView(final int position, View convertView, ViewGroup parent) {
- // Declare Variables
- TextView rank;
- inflater = (LayoutInflater) context
- .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- View itemView = inflater.inflate(R.layout.listview_item, parent, false);
- // Locate the TextViews in listview_item.xml
- rank = (TextView) itemView.findViewById(R.id.rank);
- // Capture position and set results to the TextViews
- rank.setText(data.get(position));
- return itemView;
- }
- public void updateList(String message){
- data.add(message);
- notifyDataSetChanged();
- }
- }
Just few steps remain for chat application. Now you create the ChatReceiver.java BroadcastReceiver class because we can not update the ui (Design) using MyGcmListenerService because it's extending GcmListenerService.
ChatRecevier.java
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.util.Log;
- import java.util.ArrayList;
- /**
- * Created by Arpit on 28-Apr-16.
- */
- public class ChatReceiver extends BroadcastReceiver{
- public static final String TAG = "ChatReceiver";
- ArrayList<String> data1 = new ArrayList<>();
- @Override
- public void onReceive(Context context, Intent intent) {
- Log.d(TAG, "onReceive: Chat Received");
- String message = intent.getStringExtra("message");
- Log.d(TAG, "onReceive: Chat : "+message);
- data1.add(message);
- MainActivity.listViewAdapter.updateList(message);
- MainActivity.listView.setSelection(MainActivity.listView.getAdapter().getCount()-1);
- }
- }
We are just getting chat message using this class and set it into the listview adapter.
Now add this VollySingleton.java class in your project for Json parsing and post data to server
VollySingleton.java
- import android.content.Context;
- import com.android.volley.RequestQueue;
- import com.android.volley.toolbox.Volley;
- /**
- * Created by Arpit on 16-Mar-16.
- */
- public class VolleySingleton {
- private static VolleySingleton volleySingleton;
- private RequestQueue requestQueue;
- private VolleySingleton(Context context){
- requestQueue = Volley.newRequestQueue(context);
- }
- public static VolleySingleton getInstance(Context context){
- if(volleySingleton == null){
- return new VolleySingleton(context);
- }
- return volleySingleton;
- }
- public RequestQueue getRequestQueue(){
- return requestQueue;
- }
- }
One last step for coding add Reciver in you manifest file one receiver for GCM and other for our ChatReciver.java
Compare your manifest file with my manifest.
Note : Don't forget to change your package name and add permission also.
Android Manifest.xml
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.androiddeveloper.simplechat">
- <uses-permission android:name="android.permission.INTERNET" />
- <permission
- android:name="com.example.androiddeveloper.simplechat.permission.C2D_MESSAGE"
- android:protectionLevel="signature" />
- <uses-permission android:name="com.example.androiddeveloper.simplechat.permission.C2D_MESSAGE" />
- <application
- android:allowBackup="true"
- android:icon="@mipmap/ic_launcher"
- android:label="@string/app_name"
- android:supportsRtl="true"
- android:theme="@style/AppTheme">
- <activity android:name=".MainActivity">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- <!-- This is default reciever, If you need your reciever then impliment it using below code -->
- <receiver
- android:name="com.google.android.gms.gcm.GcmReceiver"
- android:exported="true"
- android:permission="com.google.android.c2dm.permission.SEND">
- <intent-filter>
- <action android:name="com.google.android.c2dm.intent.RECEIVE" />
- <category android:name="com.example.gcm" />
- </intent-filter>
- </receiver>
- <!-- Make service by extending GcmListenerService -->
- <service
- android:name=".MyGcmListenerService"
- android:exported="false">
- <intent-filter>
- <action android:name="com.google.android.c2dm.intent.RECEIVE" />
- </intent-filter>
- </service>
- <receiver android:name=".ChatReceiver">
- <intent-filter>
- <action android:name="com.example.chat"/>
- </intent-filter>
- </receiver>
- </application>
- </manifest>
There you go complete the coding part one last step for chat app
Final Step
Goto this LINK For register your app add your app name and package name they provide google-json file after complete all step the.
this file put into your app folder and define google_app_id in string file.
Comments
Post a Comment