Hi!
In android developer experience it may chance to develop chatting application. in this tutorial i have define you "How to making a chat application".
In android we are using GCM, like in IOS APNS service. But we have to fallow some steps to work on GCM. i have define in two parts.
1) Google Account Integration
2) Android GCM Integration.
1) Google Account Integration
GCM (Google Messaging Services) is provided by Google. for integration with Google acount, please do the fallowing.
BigQuery API
Debuglet Controller API
Google Cloud Logging API
Google Cloud Messaging
Google Cloud SQL
Google Cloud Storage
Google Cloud Storage JSON API
2) Android GCM Integration
Class to Have your static Information
(have to download and add GCM.JAR with your android project)
MainActivity (Help to receive your Application ID from GCM Server)
Class to wakeup your application when receive the Alert
Class to Handle Alert
Detailed Chat Page
Business Classes
ADPTR Class
Database Class
Preference
Parser Class
URL Caller
Thats All!
Enjoy with your GCM application..,
Thank You!
Have A Great Day..,
In android developer experience it may chance to develop chatting application. in this tutorial i have define you "How to making a chat application".
In android we are using GCM, like in IOS APNS service. But we have to fallow some steps to work on GCM. i have define in two parts.
1) Google Account Integration
2) Android GCM Integration.
1) Google Account Integration
GCM (Google Messaging Services) is provided by Google. for integration with Google acount, please do the fallowing.
- Login to your Google Developer Account.
- Create a new project with your project name, SHA1 and package name.
- It will show your project ID (this id will used on android code to identify your project)
- Go to Overview and enable the fallowing API (I have added some extra API based on my project)
BigQuery API
Debuglet Controller API
Google Cloud Logging API
Google Cloud Messaging
Google Cloud SQL
Google Cloud Storage
Google Cloud Storage JSON API
as Shown on below image
- Go to credentials --> create credentials --> API KEY --> Server Key --> enter name --> create
- Note down the your API key
2) Android GCM Integration
Class to Have your static Information
(have to download and add GCM.JAR with your android project)
public interface ApplicationConstants {
// my server url to store the Application ID for future use
// (application id will generated automatically when your project connected with GCM server for 1st Time) static final String APP_SERVER_URL = "http://27.251.xxx.xxx/xxxx/xxx/xxxx";
// Project ID which is created by you from Google account static final String GOOGLE_PROJ_ID = "xxxxx"; }
MainActivity (Help to receive your Application ID from GCM Server)
package xxxx.raj.tot.pushand; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.gcm.GoogleCloudMessaging; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import java.io.IOException; import java.util.ArrayList; import java.util.List; import Others.JSONParser; import Others.My_Lines; import Others.My_Preference; public class MainActivity extends Activity { GoogleCloudMessaging gcmObj; Context applicationContext; String regId = ""; private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; EditText _u_name; My_Preference m_prf; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); applicationContext = getApplicationContext(); m_prf = new My_Preference(getApplicationContext()); _u_name = (EditText) findViewById(R.id.et_u_name); boolean is_reg = m_prf.isLoggedIn(); if (is_reg) { Intent i = new Intent(MainActivity.this, HomeActivity.class); startActivity(i); finish(); } } public void RegisterUser(View view) { String reg_u_name = _u_name.getText().toString(); if (!TextUtils.isEmpty(reg_u_name)) { if (checkPlayServices()) { registerInBackground(reg_u_name); } } else { Toast.makeText(applicationContext, "Please enter valid Name", Toast.LENGTH_LONG).show(); } } private void registerInBackground(final String u_name) { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { if (gcmObj == null) { gcmObj = GoogleCloudMessaging .getInstance(applicationContext); } regId = gcmObj .register(ApplicationConstants.GOOGLE_PROJ_ID); msg = "Registration ID :" + regId; Log.d("Registration ID :", regId); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); } return msg; } @Override protected void onPostExecute(String msg) { if (!TextUtils.isEmpty(regId)) { new store_Reg_Id(u_name, regId).execute(); Toast.makeText( applicationContext, "Registered with GCM Server successfully.\n\n" + msg, Toast.LENGTH_SHORT).show(); } else { Toast.makeText( applicationContext, "Reg ID Creation Failed.\n\nEither you haven't enabled Internet or GCM server is busy right now. Make sure you enabled Internet and try registering again after some time." + msg, Toast.LENGTH_LONG).show(); } } }.execute(null, null, null); } public class store_Reg_Id extends AsyncTask<String, String, String> { ProgressDialog p_dialog; String u_name_, _result, _regId; store_Reg_Id(String u_name, String reg_Id) { this.u_name_ = u_name; this._regId = reg_Id; } @Override protected void onPreExecute() { super.onPreExecute(); p_dialog = new ProgressDialog(MainActivity.this); p_dialog.setTitle("Please Wait..,"); p_dialog.setCancelable(false); p_dialog.setIndeterminate(false); p_dialog.show(); } @Override protected String doInBackground(String... params) { JSONParser j_parser = new JSONParser(); List<NameValuePair> n_pair = new ArrayList<>(); n_pair.add(new BasicNameValuePair("User", u_name_ + "`" + _regId + "`A")); _result = j_parser.GenrtHttpRequest(My_Lines.URL_Reg_User, "GET", n_pair); Log.d("r_sult", _result); return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); p_dialog.dismiss(); m_prf.create_User(_result, u_name_, _regId); Intent i = new Intent(MainActivity.this, HomeActivity.class); startActivity(i); finish(); } } private boolean checkPlayServices() { int resultCode = GooglePlayServicesUtil .isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show(); } else { Toast.makeText( applicationContext, "This device doesn't support Play services, App will not work normally", Toast.LENGTH_LONG).show(); finish(); } return false; } else { /*Toast.makeText( applicationContext, "This device supports Play services, App will work normally", Toast.LENGTH_LONG).show();*/ } return true; } @Override protected void onResume() { super.onResume(); checkPlayServices(); } }
Class to wakeup your application when receive the Alert
package vagus.raj.tot.pushand; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.content.WakefulBroadcastReceiver; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import Others.Chat_DB; import Others.User_B; public class GcmBroadcastReceiver extends WakefulBroadcastReceiver { Bundle bndl; Chat_DB C_DB; @Override public void onReceive(Context context, Intent intent) { Bundle extras_bndl = intent.getExtras(); bndl = extras_bndl; C_DB = new Chat_DB(context); SimpleDateFormat sdf_dt = new SimpleDateFormat("yyyy/MM/dd"); SimpleDateFormat sdf_tim = new SimpleDateFormat("HH:mm:ss"); String ct_parnt_id = String.valueOf(bndl.get("tickerText")) + sdf_dt.format(new Date()); ArrayList<String> users = C_DB.get_All_Device(); try { C_DB.addChat(new Chat_B(ct_parnt_id, String.valueOf(bndl.get("tickerText")), String.valueOf(bndl.get("contentTitle")), String.valueOf(bndl.get("message")), "Y", "N", "N", sdf_dt.format(new Date()), sdf_tim.format(new Date()))); if (users.isEmpty() || !users.contains(String.valueOf(bndl.get("tickerText")))) { C_DB.addUser(new User_B(String.valueOf(bndl.get("tickerText")), String.valueOf(bndl.get("contentTitle")))); } } catch (Exception e) { e.getMessage(); } Intent i = new Intent("DETAILEDCHAT"); context.sendBroadcast(i); Intent j = new Intent("ALLCHAT"); context.sendBroadcast(j); ComponentName comp = new ComponentName(context.getPackageName(), GCMNotificationIntentService.class.getName()); startWakefulService(context, (intent.setComponent(comp))); setResultCode(Activity.RESULT_OK); } }
Class to Handle Alert
Class to display the alertpackage xxxx.raj.tot.pushand; import android.app.IntentService; 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 com.google.android.gms.gcm.GoogleCloudMessaging; import static xxxx.raj.tot.pushand.R.drawable.altt; public class GCMNotificationIntentService extends IntentService { // Don't Change the ID public static final int notifyID = 9001; Bundle bndl; public GCMNotificationIntentService() { super("GcmIntentService"); } @Override protected void onHandleIntent(Intent intent) { Bundle extras_bndl = intent.getExtras(); bndl = extras_bndl; GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); String messageType = gcm.getMessageType(intent); if (!extras_bndl.isEmpty()) { if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR .equals(messageType)) { sendNotification(); //sendNotification("Send error: " + extras_bndl.toString()); } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED .equals(messageType)) { sendNotification(); //sendNotification("Deleted messages on server: " + extras_bndl.toString()); } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE .equals(messageType)) { sendNotification(); //sendNotification("Message Received from Google GCM Server:\n\n" + extras_bndl.get("message")); } } GcmBroadcastReceiver.completeWakefulIntent(intent); } private void sendNotification() { Intent resultIntent = new Intent(this, HomeActivity.class); PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_ONE_SHOT); NotificationCompat.Builder mNotifyBuilder; NotificationManager mNotificationManager; mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotifyBuilder = new NotificationCompat.Builder(this) .setContentTitle(getString(R.string.app_name)) .setContentText(String.valueOf(bndl.get("message"))) .setSmallIcon(altt); mNotifyBuilder.setContentIntent(resultPendingIntent); int defaults = 0; defaults = defaults | Notification.DEFAULT_LIGHTS; defaults = defaults | Notification.DEFAULT_VIBRATE; defaults = defaults | Notification.DEFAULT_SOUND; mNotifyBuilder.setDefaults(defaults); mNotifyBuilder.setContentText(String.valueOf(bndl.get("contentTitle") + " : " + bndl.get("message"))); mNotifyBuilder.setAutoCancel(true); mNotificationManager.notify(notifyID, mNotifyBuilder.build()); } }
Manifest file to bring the permission for your applicationpackage xxxx.raj.tot.pushand; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import Others.Chat_DB; import Others.JSONParser; import Others.My_Lines; import Others.My_Preference; import Others.User_B; public class HomeActivity extends ListActivity { ArrayList<User_B> User_list_; Chat_DB C_DB; TextView usertitle; My_Preference m_prf; private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { C_DB = new Chat_DB(getApplicationContext()); User_list_ = C_DB.get_All_USer(); if (!User_list_.isEmpty()) { Chat_A ca = new Chat_A(getApplicationContext(), R.layout.chat_a, User_list_, C_DB); setListAdapter(ca); } else { new Get_All_User().execute(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); m_prf = new My_Preference(getApplicationContext()); usertitle = (TextView) findViewById(R.id.usertitle); usertitle.setText("Contacts"); C_DB = new Chat_DB(getApplicationContext()); User_list_ = C_DB.get_All_USer(); if (!checkPlayServices()) { Toast.makeText( getApplicationContext(), "This device doesn't support Play services, App will not work normally", Toast.LENGTH_LONG).show(); } if (!User_list_.isEmpty()) { Chat_A ca = new Chat_A(getApplicationContext(), R.layout.chat_a, User_list_, C_DB); setListAdapter(ca); } else { new Get_All_User().execute(); } } private boolean checkPlayServices() { int resultCode = GooglePlayServicesUtil .isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show(); } else { Toast.makeText( getApplicationContext(), "This device doesn't support Play services, App will not work normally", Toast.LENGTH_LONG).show(); finish(); } return false; } else { /*Toast.makeText( getApplicationContext(), "This device supports Play services, App will work normally", Toast.LENGTH_LONG).show();*/ } return true; } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); Intent int_det_chat = new Intent(HomeActivity.this, Detaild_Chat.class); int_det_chat.putExtra("usr_frm_id", User_list_.get(position).getUser_ID()); int_det_chat.putExtra("usr_frm_name", User_list_.get(position).getUser_Name()); startActivityForResult(int_det_chat, 1); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (null != data) { if (requestCode == 1) { } } }public class Get_All_User extends AsyncTask<String, String, String> { ProgressDialog p_dialog; @Override protected void onPreExecute() { super.onPreExecute(); p_dialog = new ProgressDialog(HomeActivity.this); p_dialog.setTitle("Please Wait..,"); p_dialog.setCancelable(false); p_dialog.setIndeterminate(false); p_dialog.show(); } @Override protected String doInBackground(String... params) { User_list_ = new ArrayList<>(); HashMap<String, String> c_user = m_prf.get_User(); JSONParser j_parser = new JSONParser(); List<NameValuePair> n_pair = new ArrayList<>(); n_pair.add(new BasicNameValuePair("", "")); String _result = j_parser.GenrtHttpRequest(My_Lines.URL_All_User, "GET", n_pair); try { if (_result != null) { JSONArray j_aray = new JSONArray(_result); for (int i = 0; i < j_aray.length(); i++) { JSONObject j_obj = j_aray.getJSONObject(i); String UserId = j_obj.getString("UserId"); String RegistrationName = j_obj.getString("RegistrationName"); String frm_user_id = c_user.get(m_prf.U_ID); frm_user_id = frm_user_id.trim(); Log.d("UserId",UserId); Log.d("frm_user_id",frm_user_id); Log.d("UserId",UserId); if (!UserId.equals(frm_user_id)) { User_list_.add(new User_B(UserId, RegistrationName)); } } } } catch (Exception e) { e.getMessage(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); p_dialog.dismiss(); Chat_A ca = new Chat_A(getApplicationContext(), R.layout.chat_a, User_list_, C_DB); setListAdapter(ca); } } @Override protected void onPause() { unregisterReceiver(broadcastReceiver); super.onPause(); } @Override public void onResume() { super.onResume(); checkPlayServices(); IntentFilter filter = new IntentFilter("com.google.android.c2dm.intent.RECEIVE"); filter.setPriority(1); registerReceiver(broadcastReceiver, new IntentFilter("ALLCHAT")); super.onResume(); } }
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="xxxx.raj.tot.pushand"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> <permission android:name="xxxx.raj.tot.pushand.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <uses-permission android:name="xxxx.raj.tot.pushand.permission.C2D_MESSAGE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".HomeActivity" android:label="@string/title_activity_home" /> <receiver android:name=".GcmBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND"> <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> <category android:name="xxxx.raj.tot.pushand" /> </intent-filter> </receiver> <service android:name=".GCMNotificationIntentService" /> <activity android:name=".Detaild_Chat" android:label="@string/title_activity_detailed__chat" android:theme="@style/AppTheme.NoActionBar"></activity> </application> </manifest>
Detailed Chat Page
package xxxx.raj.tot.pushand; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import Others.Chat_DB; import Others.Chat_List_A; import Others.JSONParser; import Others.My_Lines; import Others.My_Preference; /** * Created by system57 on 06-04-2016. */ public class Detaild_Chat extends ListActivity { TextView tv_det_chat_u_nm; EditText et_det_chat_u_snd_msg; ImageButton imb_det_chat_u_snd_msg; String usr_frm_id, usr_frm_name; Chat_DB C_DB; ArrayList<Chat_B> chat_list; My_Preference m_prf; HashMap<String, String> user_date; // Add this inside your class BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { C_DB = new Chat_DB(getApplicationContext()); SimpleDateFormat sdf_dt = new SimpleDateFormat("yyyy/MM/dd"); SimpleDateFormat sdf_tim = new SimpleDateFormat("HH:mm:ss"); String ct_parnt_id = usr_frm_id + sdf_dt.format(new Date()); chat_list = C_DB.get_Single_User_Chat_List(ct_parnt_id); Chat_List_A CA_ = new Chat_List_A(getApplicationContext(), chat_list); setListAdapter(CA_); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detaild_chat); m_prf = new My_Preference(getApplicationContext()); user_date = m_prf.get_User(); usr_frm_id = getIntent().getStringExtra("usr_frm_id"); usr_frm_name = getIntent().getStringExtra("usr_frm_name"); C_DB = new Chat_DB(getApplicationContext()); SimpleDateFormat sdf_dt = new SimpleDateFormat("yyyy/MM/dd"); String ct_parnt_id = usr_frm_id + sdf_dt.format(new Date()); chat_list = C_DB.get_Single_User_Chat_List(ct_parnt_id); tv_det_chat_u_nm = (TextView) findViewById(R.id.tv_det_chat_u_nm); et_det_chat_u_snd_msg = (EditText) findViewById(R.id.et_det_chat_u_snd_msg); imb_det_chat_u_snd_msg = (ImageButton) findViewById(R.id.imb_det_chat_u_snd_msg); imb_det_chat_u_snd_msg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String _message = et_det_chat_u_snd_msg.getText().toString(); String frm_user_id = user_date.get(m_prf.U_ID); if (!_message.isEmpty()) { new Send_GCM(_message, frm_user_id, usr_frm_id).execute(); } } }); Chat_List_A CA_ = new Chat_List_A(getApplicationContext(), chat_list); setListAdapter(CA_); tv_det_chat_u_nm.setText(usr_frm_name); } public class Send_GCM extends AsyncTask<String, String, String> { ProgressDialog p_dialog; String _message, from_, userids_; Send_GCM(String message, String from, String userids) { this._message = message; this.from_ = from; this.userids_ = userids; } @Override protected void onPreExecute() { super.onPreExecute(); //InputMethodManager inputManager = (InputMethodManager) getSystemService(Detaild_Chat.INPUT_METHOD_SERVICE); //inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } @Override protected String doInBackground(String... params) { JSONParser j_parser = new JSONParser(); List<NameValuePair> n_pair = new ArrayList<>(); n_pair.add(new BasicNameValuePair("message", _message)); n_pair.add(new BasicNameValuePair("from", from_)); n_pair.add(new BasicNameValuePair("userids", userids_)); String r_sult = j_parser.GenrtHttpRequest(My_Lines.URL_Chat, "GET", n_pair); return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); C_DB = new Chat_DB(getApplicationContext()); SimpleDateFormat sdf_dt = new SimpleDateFormat("yyyy/MM/dd"); SimpleDateFormat sdf_tim = new SimpleDateFormat("HH:mm:ss"); String ct_parnt_id = usr_frm_id + sdf_dt.format(new Date()); C_DB.addChat(new Chat_B(ct_parnt_id, usr_frm_id, usr_frm_name, _message, "Y", "N", "Y", sdf_dt.format(new Date()), sdf_tim.format(new Date()))); et_det_chat_u_snd_msg.setText(""); chat_list = C_DB.get_Single_User_Chat_List(ct_parnt_id); Chat_List_A CA_ = new Chat_List_A(getApplicationContext(), chat_list); setListAdapter(CA_); } } @Override protected void onPause() { unregisterReceiver(broadcastReceiver); super.onPause(); } @Override public void onResume() { IntentFilter filter = new IntentFilter("com.google.android.c2dm.intent.RECEIVE"); filter.setPriority(1); registerReceiver(broadcastReceiver, new IntentFilter("DETAILEDCHAT")); super.onResume(); } @Override public void onBackPressed() { //super.onBackPressed(); Intent i = new Intent(); setResult(1, i); finish(); } }
Business Classes
package xxxx.raj.tot.pushand; /** * Created by Selvaraj on 08-Mar-16. */public class Chat_B { String Chat_Parent_ID, Chat_Frm, Chat_Name, message_, R_status, S_Status, Is_self, date_, time_; public Chat_B() { } public Chat_B(String chat_Parent_ID, String chat_Frm, String chat_Name, String message_, String r_status, String s_Status, String is_self, String date_, String time_) { Chat_Parent_ID = chat_Parent_ID; Chat_Frm = chat_Frm; Chat_Name = chat_Name; this.message_ = message_; R_status = r_status; S_Status = s_Status; Is_self = is_self; this.date_ = date_; this.time_ = time_; } public String getChat_Parent_ID() { return Chat_Parent_ID; } public void setChat_Parent_ID(String chat_Parent_ID) { Chat_Parent_ID = chat_Parent_ID; } public String getChat_Frm() { return Chat_Frm; } public void setChat_Frm(String chat_Frm) { Chat_Frm = chat_Frm; } public String getChat_Name() { return Chat_Name; } public void setChat_Name(String chat_Name) { Chat_Name = chat_Name; } public String getMessage_() { return message_; } public void setMessage_(String message_) { this.message_ = message_; } public String getR_status() { return R_status; } public void setR_status(String r_status) { R_status = r_status; } public String getS_Status() { return S_Status; } public void setS_Status(String s_Status) { S_Status = s_Status; } public String getIs_self() { return Is_self; } public void setIs_self(String is_self) { Is_self = is_self; } public String getDate_() { return date_; } public void setDate_(String date_) { this.date_ = date_; } public String getTime_() { return time_; } public void setTime_(String time_) { this.time_ = time_; } }
package Others; /** * Created by system57 on 05-04-2016. */public class User_B { String User_ID, User_Name; public User_B() { } public User_B(String user_ID, String user_Name) { User_ID = user_ID; User_Name = user_Name; } public String getUser_ID() { return User_ID; } public void setUser_ID(String user_ID) { User_ID = user_ID; } public String getUser_Name() { return User_Name; } public void setUser_Name(String user_Name) { User_Name = user_Name; } }
package Others; /** * Created by system57 on 04-04-2016. */public class Chat_List_B { String from_id, to_id, message; boolean is_self; public Chat_List_B() { } public Chat_List_B(String from_id, String to_id, String message, boolean is_self) { this.from_id = from_id; this.to_id = to_id; this.message = message; this.is_self = is_self; } public String getFrom_id() { return from_id; } public void setFrom_id(String from_id) { this.from_id = from_id; } public String getTo_id() { return to_id; } public void setTo_id(String to_id) { this.to_id = to_id; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public boolean is_self() { return is_self; } public void setIs_self(boolean is_self) { this.is_self = is_self; } }
ADPTR Class
package xxxx.raj.tot.pushand; 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.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import Others.Chat_DB; import Others.User_B; /** * Created by Selvaraj on 08-Mar-16. */public class Chat_A extends BaseAdapter { ArrayList<User_B> chat_list; Context context; Chat_DB C_DB; public Chat_A(Context applicationContext, int chat_a, ArrayList<User_B> chat_list_, Chat_DB C_DB_) { this.context = applicationContext; this.chat_list = chat_list_; this.C_DB = C_DB_; } @Override public int getCount() { return chat_list.size(); } @Override public Object getItem(int position) { return chat_list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater lf = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = lf.inflate(R.layout.chat_a, null); } TextView tv_user = (TextView) convertView.findViewById(R.id.tv_user); TextView tv_message = (TextView) convertView.findViewById(R.id.tv_msg); TextView tv_count = (TextView) convertView.findViewById(R.id.tv_count); tv_user.setText(chat_list.get(position).getUser_Name()); //tv_time.setText(chat_list.get(position).getUser_Name()); SimpleDateFormat sdf_dt = new SimpleDateFormat("yyyy/MM/dd"); String ct_parnt_id = chat_list.get(position).getUser_ID() + sdf_dt.format(new Date()); Chat_B chat_lst = C_DB.get_Latest_User_Chat_(ct_parnt_id); ArrayList<Chat_B> msg_count = C_DB.get_Single_User_Chat_List(ct_parnt_id); tv_count.setText(String.valueOf(msg_count.size())); String last_msg = "New"; if (chat_lst != null) { last_msg = chat_lst.getMessage_(); } tv_message.setText(last_msg); return convertView; } }
package Others; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import xxxx.raj.tot.pushand.Chat_B; import xxxx.raj.tot.pushand.R; /** * Created by system57 on 04-04-2016. */public class Chat_List_A extends BaseAdapter { private Context context; private List<Chat_B> messagesItems; public Chat_List_A(Context applicationContext, ArrayList<Chat_B> m_list) { // TODO Auto-generated constructor stub this.context = applicationContext; this.messagesItems = m_list; } @Override public int getCount() { return messagesItems.size(); } @Override public Object getItem(int position) { return messagesItems.get(position); } @Override public long getItemId(int position) { return position; } @SuppressLint("InflateParams") @Override public View getView(final int position, View convertView, ViewGroup parent) { LayoutInflater mInflater = (LayoutInflater) context .getSystemService(Activity.LAYOUT_INFLATER_SERVICE); convertView = mInflater.inflate(R.layout.list_item_message_right, null); // Identifying the message owner if (messagesItems.get(position).getIs_self().equals("Y")) { convertView = mInflater.inflate(R.layout.list_item_message_right, null); } else { convertView = mInflater.inflate(R.layout.list_item_message_left, null); } TextView txtMsg = (TextView) convertView.findViewById(R.id.txtMsg); TextView lblMsgFrom2 = (TextView) convertView.findViewById(R.id.lblMsgFrom2); ///// if (messagesItems.get(position).getIs_self().equals("Y")) { // message belongs to you, so load the right aligned layout txtMsg.setTextColor(Color.parseColor("#ff614c")); } ///// txtMsg.setText(messagesItems.get(position).getMessage_()); lblMsgFrom2.setText(messagesItems.get(position).getTime_()); txtMsg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub //Toast.makeText(context, messagesItems.get(position).getPersonfrom(), Toast.LENGTH_SHORT).show(); } }); return convertView; } }
Database Class
package Others; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import java.util.ArrayList; import xxxx.raj.tot.pushand.Chat_B; /** * Created by Selvaraj on 08-Mar-16. */public class Chat_DB extends SQLiteOpenHelper { private static final int Db_Version = 1; private static final String Db_Name = "chat_14"; private static final String Tb_chat = "Tb_chat"; private static final String Tb_User = "Tb_User"; // Field for Room Booking final String Chat_ID = "Chat_ID"; final String Chat_Parent_ID = "Chat_Parent_ID"; final String Chat_Frm = "Chat_Frm"; final String Chat_Name = "Chat_Name"; final String Chat_Msg = "Chat_Msg"; final String Chat_R_status = "Chat_R_status"; final String Chat_S_Status = "Chat_S_Status"; final String Chat_Is_self = "Chat_Is_self"; final String Chat_Dat = "Chat_Dat"; final String Chat_Time = "Chat_Time"; // User final String Chat_U_ID = "Chat_U_ID"; final String User_ID = "User_ID"; final String User_Name = "User_Name"; public Chat_DB(Context context) { super(context, Db_Name, null, Db_Version); } @Override public void onCreate(SQLiteDatabase db) { String CREATE_Chat_TABLE = "CREATE TABLE " + Tb_chat + "(" + Chat_ID + " INTEGER PRIMARY KEY," + Chat_Parent_ID + " TEXT," + Chat_Frm + " TEXT," + Chat_Name + " TEXT," + Chat_Msg + " TEXT," + Chat_R_status + " TEXT," + Chat_S_Status + " TEXT," + Chat_Is_self + " TEXT," + Chat_Dat + " TEXT," + Chat_Time + " TEXT " + ")"; String CREATE_User_TABLE = "CREATE TABLE " + Tb_User + "(" + Chat_U_ID + " INTEGER PRIMARY KEY," + User_ID + " TEXT," + User_Name + " TEXT " + ")"; db.execSQL(CREATE_Chat_TABLE); db.execSQL(CREATE_User_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS" + Tb_chat); db.execSQL("DROP TABLE IF EXISTS" + Tb_User); onCreate(db); } // Add Objects on the table public void addChat(Chat_B Rpl_lst) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(Chat_Parent_ID, Rpl_lst.getChat_Parent_ID()); values.put(Chat_Frm, Rpl_lst.getChat_Frm()); values.put(Chat_Name, Rpl_lst.getChat_Name()); values.put(Chat_Msg, Rpl_lst.getMessage_()); values.put(Chat_R_status, Rpl_lst.getR_status()); values.put(Chat_S_Status, Rpl_lst.getS_Status()); values.put(Chat_Is_self, Rpl_lst.getIs_self()); values.put(Chat_Dat, Rpl_lst.getDate_()); values.put(Chat_Time, Rpl_lst.getTime_()); db.insert(Tb_chat, null, values); db.close(); Log.d("BD Log", "EXECUTIVE SUCESS"); } // Select list of all available records public ArrayList<Chat_B> get_All_Chat() { ArrayList<Chat_B> repay_list = new ArrayList<Chat_B>(); String sltqry = "SELECT * FROM " + Tb_chat + " ORDER BY " + Chat_Msg + " DESC"; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(sltqry, null); if (cursor.moveToFirst()) { do { Chat_B repy = new Chat_B(); //exe.setId(String.valueOf(Integer.parseInt(cursor.getString(0)))); repy.setChat_Parent_ID(cursor.getString(1)); repy.setChat_Frm(cursor.getString(2)); repy.setChat_Name(cursor.getString(3)); repy.setMessage_(cursor.getString(4)); repy.setR_status(cursor.getString(5)); repy.setS_Status(cursor.getString(6)); repy.setIs_self(cursor.getString(7)); repy.setDate_(cursor.getString(8)); repy.setTime_(cursor.getString(9)); repay_list.add(repy); } while (cursor.moveToNext()); } cursor.close(); db.close(); return repay_list; } public ArrayList<Chat_B> get_Single_User_Chat_List(String Parnt_Id) { ArrayList<Chat_B> Single_user = new ArrayList<Chat_B>(); SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery("SELECT * FROM " + Tb_chat + " WHERE " + Chat_Parent_ID + " = ?" + " ORDER BY " + Chat_Time + " ASC", new String[]{Parnt_Id}); if (cursor.moveToFirst()) { do { Chat_B user_chat = new Chat_B(); user_chat.setChat_Parent_ID(cursor.getString(1)); user_chat.setChat_Frm(cursor.getString(2)); user_chat.setChat_Name(cursor.getString(3)); user_chat.setMessage_(cursor.getString(4)); user_chat.setR_status(cursor.getString(5)); user_chat.setS_Status(cursor.getString(6)); user_chat.setIs_self(cursor.getString(7)); user_chat.setDate_(cursor.getString(8)); user_chat.setTime_(cursor.getString(9)); Single_user.add(user_chat); } while (cursor.moveToNext()); } return Single_user; } public void addUser(User_B Rpl_lst) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(User_ID, Rpl_lst.getUser_ID()); values.put(User_Name, Rpl_lst.getUser_Name()); db.insert(Tb_User, null, values); db.close(); Log.d("BD Log", "EXECUTIVE SUCESS"); } public ArrayList<User_B> get_All_USer() { ArrayList<User_B> repay_list = new ArrayList<User_B>(); String sltqry = "SELECT * FROM " + Tb_User + " ORDER BY " + User_ID + " DESC"; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(sltqry, null); if (cursor.moveToFirst()) { do { User_B repy = new User_B(); //exe.setId(String.valueOf(Integer.parseInt(cursor.getString(0)))); repy.setUser_ID(cursor.getString(1)); repy.setUser_Name(cursor.getString(2)); repay_list.add(repy); } while (cursor.moveToNext()); } cursor.close(); db.close(); return repay_list; } public ArrayList<String> get_All_Device() { ArrayList<String> repay_list = new ArrayList<String>(); String sltqry = "SELECT * FROM " + Tb_User + " ORDER BY " + User_ID + " DESC"; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(sltqry, null); if (cursor.moveToFirst()) { do { String D_Id = cursor.getString(1); repay_list.add(D_Id); } while (cursor.moveToNext()); } cursor.close(); db.close(); return repay_list; } public Chat_B get_Latest_User_Chat_(String Parnt_Id) { Chat_B user_chat = null; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery("SELECT * FROM " + Tb_chat + " WHERE " + Chat_Parent_ID + " = ?", new String[]{Parnt_Id}); if (cursor.moveToLast()) { user_chat = new Chat_B(); user_chat.setChat_Parent_ID(cursor.getString(1)); user_chat.setChat_Frm(cursor.getString(2)); user_chat.setChat_Name(cursor.getString(3)); user_chat.setMessage_(cursor.getString(4)); user_chat.setR_status(cursor.getString(5)); user_chat.setS_Status(cursor.getString(6)); user_chat.setIs_self(cursor.getString(7)); user_chat.setDate_(cursor.getString(8)); user_chat.setTime_(cursor.getString(9)); } return user_chat; } }
Preference
package Others; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import java.util.HashMap; import xxxx.raj.tot.pushand.MainActivity; /** * Created by Selvaraj on 12/5/2015. */public class My_Preference { public static final String MyPREFERENCES = "Chat_me2"; public static final String U_ID = "userid"; public static final String U_Name = "username"; public static final String U_Device_ID = "userdeviceide"; private static final String IS_LOGIN = "IsLoggedIn"; Context context; SharedPreferences sharedpreferences; SharedPreferences.Editor editor; int PRIVATE_MODE = 0; public My_Preference() { } public My_Preference(Context _context) { this.context = _context; sharedpreferences = context.getSharedPreferences(MyPREFERENCES, PRIVATE_MODE); editor = sharedpreferences.edit(); } public void create_User(String U_id, String U_nm, String u_dev_id) { editor.putBoolean(IS_LOGIN, true); editor.putString(U_ID, U_id); editor.putString(U_Name, U_nm); editor.putString(U_Device_ID, u_dev_id); editor.commit(); } /* public void Update_User(String U_id, String U_nm, String u_dev_id) { editor.clear(); editor.commit(); editor.putBoolean(IS_LOGIN, true); editor.putString(U_ID, U_id); editor.putString(U_Name, U_nm); editor.putString(U_Device_ID, u_dev_id); editor.commit(); }*/ public void create_User_Reg(boolean chng_ps) { editor.putBoolean(IS_LOGIN, true); editor.commit(); } public HashMap<String, String> get_User() { HashMap<String, String> user = new HashMap<>(); user.put(U_ID, sharedpreferences.getString(U_ID, null)); user.put(U_Name, sharedpreferences.getString(U_Name, null)); user.put(U_Device_ID, sharedpreferences.getString(U_Device_ID, null)); return user; } public void checkLogin() { if (!this.isLoggedIn()) { Intent i = new Intent(context, MainActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); } } public void logoutUser() { editor.clear(); editor.commit(); Intent i = new Intent(context, MainActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); } public boolean isLoggedIn() { return sharedpreferences.getBoolean(IS_LOGIN, false); } }
Parser Class
package Others; /** * Created by Selvaraj on 07-Mar-16. */import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.List; public class JSONParser { // Declare InputStream for handle input & String for return the result static InputStream ips = null; static String jsn_rtn = ""; // empty constructor is necessary public JSONParser() { } // create a method for input arguments "url & type & values" public String GenrtHttpRequest(String url, String method, List<NameValuePair> params) { try { // if the method is post if (method == "POST") { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); ips = httpEntity.getContent(); } // if the method is get else if (method == "GET") { DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); ips = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(ips, "iso-8859-1"), 8); //use StringBuilder to concordinate the String values StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } ips.close(); jsn_rtn = sb.toString(); } catch (Exception e) { e.getMessage(); } // return the final result values return jsn_rtn; } }
URL Caller
package Others; /** * Created by Selvaraj on 06-Apr-16. */public class My_Lines { public static final String URL_Reg_User = "http://yourschat.xxxx.com/Notification/CreateUser"; public static final String URL_All_User = "http://yourschat.xxxx.com/Notification/UserList"; public static final String URL_Chat = "http://yourschat.xxxx.com/Notification/SendMessage"; }
Gradle File
apply plugin: 'com.android.application' buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:1.1.0' } } allprojects { repositories { jcenter() } } android { compileSdkVersion 22 buildToolsVersion '22.0.1' defaultConfig { applicationId "xxxx.raj.tot.pushand" minSdkVersion 15 targetSdkVersion 22 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') compile 'com.android.support:appcompat-v7:22.2.0' compile 'com.google.android.gms:play-services:7.5.0' compile files('libs/android-async-http-1.4.4.jar') compile files('libs/gcm.jar') compile 'com.android.support:support-v4:23.1.1' }
Thats All!
Enjoy with your GCM application..,
Thank You!
Please Leave Your Comment..,
Have A Great Day..,