w7chat
gradle file
//----------- xmpp---------compile 'org.igniterealtime.smack:smack-android:4.1.4'compile 'org.igniterealtime.smack:smack-tcp:4.1.4'compile 'org.igniterealtime.smack:smack-im:4.1.4'compile 'org.igniterealtime.smack:smack-extensions:4.1.4'
menifiest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<service android:name="cygnus.w7chat.xmpp.XmppService" android:enabled="true" />
ConstantDataOfXMPP.java
import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.location.Location; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.widget.Toast; import org.jivesoftware.smack.AbstractXMPPConnection; import org.jivesoftware.smack.SmackException; import org.jivesoftware.smack.chat.Chat; import org.jivesoftware.smack.chat.ChatManager; import org.jivesoftware.smack.chat.ChatMessageListener; import org.jivesoftware.smack.packet.Message; import org.json.JSONObject; import java.sql.Date; import java.text.SimpleDateFormat; /** * Created by w7shal on 06/04/16. */public class ConstantDataOfXMPP { public static final String DOMAIN = "202.131.106.78"; public static final String HOST = "202.131.106.78"; public static final int PORT = 5222; public static String userName = "suresh"; public static String passWord = "123456"; public static AbstractXMPPConnection connection; //------------error tag----------------- public static String TAG_ERROR = "Error-->>"; //--------------this is for JSON ENCODE and DECODE public static String KEY_MSG_OBJ = "msgObj"; public static String KEY_MY_MSG = "myMsg"; public static String KEY_MY_MSG_TIME = "myMsgTime"; public static String KEY_MY_MSG_TYPE = "chatType"; public static String DEFAULT_CHAT_FORMATE= "{\"myMsgTime\":\" \",\"chatType\":\"chat\",\"myMsg\":\"Something went wrong msg not send\"}"; public static MessageData exposeJSON(String json , boolean isSend) { MessageData messageData = new MessageData(); try { JSONObject obj = new JSONObject(json); messageData.setMyMsg(obj.getString(KEY_MY_MSG)); messageData.setMsgTime(obj.getString(KEY_MY_MSG_TIME)); messageData.setIsSend(isSend); } catch (Exception e) { Log.v(TAG_ERROR, e.toString()); } return messageData; } public static String makeJSON(String msg , boolean isChat) { JSONObject objOfChat = new JSONObject(); try { objOfChat.put(ConstantDataOfXMPP.KEY_MY_MSG, msg); objOfChat.put(ConstantDataOfXMPP.KEY_MY_MSG_TYPE, isChat?"chat":"media"); objOfChat.put(ConstantDataOfXMPP.KEY_MY_MSG_TIME, System.currentTimeMillis()); return objOfChat.toString(); } catch (Exception e) { Log.v(TAG_ERROR, e.toString()); } return DEFAULT_CHAT_FORMATE; } //----------------------send msg----------------- public static void sendMessage(String msg) { Chat mychat = ChatManager.getInstanceFor(ConstantDataOfXMPP.connection).createChat( "hitesh@skipsmktgplc", new ChatMessageListener() { @Override public void processMessage(Chat chat, Message message) { Log.v("you are", "lisner"); } }); Message message = new Message(); message.setBody(msg); message.setStanzaId("123"); message.setType(Message.Type.chat); Log.v("Messagesent", "message sent2"); // try { if (ConstantDataOfXMPP.connection.isAuthenticated()) { mychat.sendMessage(message); Log.v("Messagesent", message.toString()); } } catch (SmackException.NotConnectedException e) { Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!"); } catch (Exception e) { Log.e("error-->>", "" + e.toString()); } } //------------------- request to frnd--------------- //----------------normal function------------- public static void displayAlert(String title, String message, Context context) { AlertDialog.Builder builder1 = new AlertDialog.Builder(context); builder1.setTitle(title); builder1.setMessage(message); builder1.setCancelable(true); builder1.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert11 = builder1.create(); alert11.show(); } public static void toastMessage(final Context context , final String text) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { Toast.makeText(context, text, Toast.LENGTH_SHORT).show(); } }); } public static String convertTimeFromMillSec(long yourmilliseconds) { try { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm a"); Date resultdate = new Date(yourmilliseconds); return sdf.format(resultdate); } catch (Exception e) { return ""; } } }MessageData.java
public class MessageData { private String myUserName; private String myMsg; private String frndMsg; private String msgTime; private boolean isSend = false; public boolean isSend() { return isSend; } public void setIsSend(boolean isSend) { this.isSend = isSend; } public String getMyUserName() { return myUserName; } public void setMyUserName(String myUserName) { this.myUserName = myUserName; } public String getMyMsg() { return myMsg; } public void setMyMsg(String myMsg) { this.myMsg = myMsg; } public String getFrndMsg() { return frndMsg; } public void setFrndMsg(String frndMsg) { this.frndMsg = frndMsg; } public String getMsgTime() { return msgTime; } public void setMsgTime(String msgTime) { this.msgTime = msgTime; } }
XmppService.java
import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.location.Location; import android.os.AsyncTask; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.provider.ContactsContract; import android.util.Log; import android.widget.Toast; import org.jivesoftware.smack.AbstractXMPPConnection; import org.jivesoftware.smack.ConnectionConfiguration; import org.jivesoftware.smack.ConnectionListener; import org.jivesoftware.smack.MessageListener; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.SmackException; import org.jivesoftware.smack.StanzaListener; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.chat.Chat; import org.jivesoftware.smack.chat.ChatManager; import org.jivesoftware.smack.chat.ChatManagerListener; import org.jivesoftware.smack.chat.ChatMessageListener; import org.jivesoftware.smack.filter.MessageTypeFilter; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.filter.StanzaFilter; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.packet.Stanza; import org.jivesoftware.smack.roster.Roster; import org.jivesoftware.smack.roster.RosterListener; import org.jivesoftware.smack.tcp.XMPPTCPConnection; import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration; import java.io.IOException; import java.security.spec.ECField; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Timer; import java.util.TimerTask; import cygnus.w7chat.ChatActivity; import cygnus.w7chat.R; import cygnus.w7chat.xmpp.ConstantDataOfXMPP; public class XmppService extends Service{ // ConstantDataOfXMPP public long NOTIFY_INTERVAL = 5 * 1000; List<String> xmpplist = new ArrayList<String>(); // AbstractXMPPConnection connection ; XMPPConnectionListener connectionListener = new XMPPConnectionListener(); // run on another Thread to avoid crash private Handler mHandler = new Handler(); // timer handling private Timer mTimer = null; public XmppService() { } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { init(ConstantDataOfXMPP.userName , ConstantDataOfXMPP.passWord); connectConnection(); ChatManager.getInstanceFor(ConstantDataOfXMPP.connection).addChatListener(new ChatManagerListenerImpl()); // Roster roster = Roster.getInstanceFor(ConstantDataOfXMPP.connection);// roster.addRosterListener(new RosterListener() {// // Ignored events public void entriesAdded(Collection<String> addresses) {}// public void entriesDeleted(Collection<String> addresses) {////// Log.v("hi-->>" , addresses.size()+"");// }//// @Override// public void entriesAdded(Collection<String> addresses) {// Log.v("hi-->>" , addresses.size()+"");// }//// public void entriesUpdated(Collection<String> addresses) {// Log.v("hi-->>" , addresses.size()+"");// }//// public void presenceChanged(Presence presence) {// System.out.println("Presence changed: " + presence.getFrom() + " " + presence);// }// }); StanzaFilter filter = new StanzaFilter() { @Override public boolean accept(Stanza stanza) { Log.v("stanza-->>" , stanza.toString()); if (stanza.toString().indexOf("type='subscribe") >=0) { notification(stanza.getFrom().replace("@w7shal-pc" , "") + " is Added You as friend"); } else if(stanza.toString().indexOf("type='unsubscribe") >=0) { notification(stanza.getFrom().replace("@w7shal-pc" , "") + " is Remove You as friend"); } return true; } }; return Service.START_STICKY; } //Initialize public void init(String userId, String pwd) { Log.i("XMPP", "Initializing!"); ConstantDataOfXMPP.userName = userId; ConstantDataOfXMPP.passWord = pwd; XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder(); configBuilder.setUsernameAndPassword(ConstantDataOfXMPP.userName, ConstantDataOfXMPP.passWord); configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled); configBuilder.setResource("Android"); configBuilder.setServiceName(ConstantDataOfXMPP.DOMAIN); configBuilder.setHost(ConstantDataOfXMPP.HOST); configBuilder.setPort(ConstantDataOfXMPP.PORT); ConstantDataOfXMPP.connection = new XMPPTCPConnection(configBuilder.build()); ConstantDataOfXMPP.connection.addConnectionListener(connectionListener); } public void login() { // new DownloadFilesTask().execute(""); try { ConstantDataOfXMPP.connection.login(ConstantDataOfXMPP.userName, ConstantDataOfXMPP.passWord); // if (ConstantDataOfXMPP.connection.isAuthenticated())// startActivity(new Intent(XmppService.this, Profile.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } catch (XMPPException | SmackException | IOException e) { e.printStackTrace(); } catch (Exception e) { Log.v("Error-->>", e.toString()); } } public void resister() { new DownloadFilesTask().execute(""); } @Override public void onCreate() { // cancel if already existed if (mTimer != null) { mTimer.cancel(); } else { // recreate new mTimer = new Timer(); } mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL); } // Disconnect Function public void disconnectConnection() { new Thread(new Runnable() { @Override public void run() { ConstantDataOfXMPP.connection.disconnect(); } }).start(); } public void connectConnection() { AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... arg0) { // Create a connection try { ConstantDataOfXMPP.connection.connect(); login(); } catch (IOException e) { Log.e("error-->>", e.toString()); } catch (SmackException e) { Log.e("error-->>", e.toString()); } catch (XMPPException e) { Log.e("error-->>", e.toString()); } return null; } }; connectionThread.execute(); } class TimeDisplayTimerTask extends TimerTask { @Override public void run() { // run on another thread mHandler.post(new Runnable() { @Override public void run() { if (ConstantDataOfXMPP.connection.isConnected() && ConstantDataOfXMPP.connection.isAuthenticated()) { Log.i("service-->>", "User Connect!"); } else { Log.i("service-->>", "User DisConnect!"); if (!ConstantDataOfXMPP.connection.isAuthenticated()) login(); } // display toast// Toas t.makeText(getApplicationContext(), getDateTime(),// Toast.LENGTH_SHORT).show(); } }); } private String getDateTime() { // get date time in custom format SimpleDateFormat sdf = new SimpleDateFormat("[yyyy/MM/dd - HH:mm:ss]"); return sdf.format(new Date()); } } //Connection Listener to check connection state public class XMPPConnectionListener implements ConnectionListener { @Override public void connected(final XMPPConnection connection) { ToastMessage("Connected!"); if (!connection.isAuthenticated()) { login(); } } @Override public void connectionClosed() { ToastMessage("ConnectionCLosed"); } @Override public void connectionClosedOnError(Exception arg0) { ToastMessage("ConnectionClosedOn Error!"); } @Override public void reconnectingIn(int arg0) { ToastMessage("Reconnectingin!"); } @Override public void reconnectionFailed(Exception arg0) { ToastMessage("ReconnectionFailed!"); } @Override public void reconnectionSuccessful() { ToastMessage("ReconnectionSuccessful!"); } @Override public void authenticated(XMPPConnection arg0, boolean arg1) { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); ToastMessage(ConstantDataOfXMPP.userName+" Authenticated!"); } } private void ToastMessage(final String text) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show(); } }); } private class DownloadFilesTask extends AsyncTask<String, Void, String> { @Override protected void onPreExecute() { } @Override protected String doInBackground(String... urls) { try { XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder(); configBuilder.setUsernameAndPassword("cool", "123456"); configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled); configBuilder.setResource("Android"); configBuilder.setServiceName(ConstantDataOfXMPP.DOMAIN); configBuilder.setHost(ConstantDataOfXMPP.HOST); configBuilder.setPort(ConstantDataOfXMPP.PORT); AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build()); connection.connect(); org.jivesoftware.smackx.iqregister.AccountManager accountManager = org.jivesoftware.smackx.iqregister.AccountManager.getInstance(connection); accountManager.sensitiveOperationOverInsecureConnection(true); accountManager.createAccount("cool", "123456"); connection.login("cool", "123456"); } catch (Exception e) { Log.v("error-->>", e.toString()); } return ""; } @Override protected void onPostExecute(String result) { } } private class ChatManagerListenerImpl implements ChatManagerListener { /* {@inheritDoc} */ @Override public void chatCreated(final Chat chat, final boolean createdLocally) { chat.addMessageListener(new ChatMessageListener() { @Override public void processMessage(Chat chat, Message message) { try { message.getFrom(); Log.v("cool-->>", message.getBody()); Intent i = new Intent("android.intent.action.MAIN"); i.putExtra(ConstantDataOfXMPP.KEY_MSG_OBJ, message.getBody()); sendBroadcast(i); } catch (Exception ex) { Log.v("exception", ex.toString()); } } }); } } private void notification(String notificationMSG) { Intent intent = new Intent(XmppService.this , ChatActivity.class); PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0); Notification n = new Notification.Builder(this) .setContentTitle("W7chat") .setContentText(notificationMSG) .setSmallIcon(R.mipmap.ic_launcher) .setContentIntent(pIntent) .addAction(R.mipmap.ic_launcher, "", pIntent).build(); NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); notificationManager.notify(0, n); } }ChatActivity.java
import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import cygnus.w7chat.xmpp.ConstantDataOfXMPP; import cygnus.w7chat.xmpp.MessageData; public class ChatActivity extends Activity { ListView chatListView; TextView tv_typing; EditText et_msg; List<MessageData> chatMessageList = new ArrayList<MessageData>(); private BroadcastReceiver mReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.chat_activity); chatListView = (ListView)findViewById(R.id.listView); tv_typing = (TextView)findViewById(R.id.tv_typing); et_msg = (EditText)findViewById(R.id.et_msg); mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { MessageData messageData = ConstantDataOfXMPP.exposeJSON(intent.getStringExtra(ConstantDataOfXMPP.KEY_MSG_OBJ) , false); if (messageData.getMyMsg().equalsIgnoreCase("")) typing(); else { tv_typing.setVisibility(View.GONE); messageData.setIsSend(false); //-----it means this frnd msg not send msg try { chatMessageList.add(messageData); } catch (Exception e) { Log.v(ConstantDataOfXMPP.TAG_ERROR , e.toString()); } setAdpOfChat(); } } }; try { this.unregisterReceiver(this.mReceiver); } catch (Exception ex) { } this.registerReceiver(mReceiver, new IntentFilter("android.intent.action.MAIN")); } public void sendMsgClick(View v) { String msg = et_msg.getText().toString(); try { if (msg.equalsIgnoreCase("")) { ConstantDataOfXMPP.toastMessage(ChatActivity.this , "Please Enter Message"); } else { //-------- {"nyMsgTime":1460034351041,"chatType":"chat","myMsg":"hi..."} ConstantDataOfXMPP.sendMessage(ConstantDataOfXMPP.makeJSON(msg , true)); chatMessageList.add(ConstantDataOfXMPP.exposeJSON(ConstantDataOfXMPP.makeJSON(msg , true).toString(), true)); setAdpOfChat(); } } catch (Exception e) { Log.v(ConstantDataOfXMPP.TAG_ERROR , e.toString()); Toast.makeText(ChatActivity.this , "Message Not Send" , Toast.LENGTH_LONG).show(); } } public class ChatAdpter extends BaseAdapter { @Override public int getCount() { // TODO Auto-generated method stub return chatMessageList.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder; LayoutInflater inflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE); // If holder not exist then locate all view from UI file. if (convertView == null) { // inflate UI from XML file convertView = inflater.inflate(R.layout.chat_adp, parent, false); // get all UI view holder = new ViewHolder(convertView); // set tag for holder convertView.setTag(holder); } else { // if holder created, get tag from view holder = (ViewHolder) convertView.getTag(); } if (chatMessageList.get(position).isSend()) { holder.lay_left.setVisibility(View.GONE); holder.lay_right.setVisibility(View.VISIBLE); //--right // holder.right_chat_msg.setText(chatMessageList.get(position).getMessage());// holder.right_chat_msg.setText(chatMessageList.get(position).getMyMsg()); holder.right_msg_time.setText(ConstantDataOfXMPP.convertTimeFromMillSec(Long.parseLong(chatMessageList.get(position).getMsgTime()))); } else { holder.lay_left.setVisibility(View.VISIBLE); holder.lay_right.setVisibility(View.GONE); holder.left_chat_msg.setText(chatMessageList.get(position).getMyMsg()); holder.left_msg_time.setText(ConstantDataOfXMPP.convertTimeFromMillSec(Long.parseLong(chatMessageList.get(position).getMsgTime()))); } return convertView; } } private class ViewHolder { TextView right_chat_msg , left_chat_msg; TextView right_msg_time , left_msg_time; LinearLayout singleMessageContainer; LinearLayout lay_right; LinearLayout lay_left; public ViewHolder(View v) { lay_right = (LinearLayout) v.findViewById(R.id.lay_right); lay_left = (LinearLayout) v.findViewById(R.id.lay_left); right_chat_msg = (TextView) v.findViewById(R.id.right_msg); right_msg_time = (TextView) v.findViewById(R.id.right_msg_time); left_msg_time = (TextView) v.findViewById(R.id.left_msg_time); left_chat_msg = (TextView) v.findViewById(R.id.left_msg); } } //---------------when user typing that time its call and visible typing textview private void typing() { tv_typing.setVisibility(View.VISIBLE); android.os.Handler handler = new android.os.Handler(); handler.postDelayed(new Runnable() { @Override public void run() { tv_typing.setVisibility(View.GONE); } }, 3000); } private void setAdpOfChat() { chatListView.setAdapter(new ChatAdpter()); } }Splash Screen.java
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import cygnus.w7chat.xmpp.XmppService; public class SplashScreen extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splash_screen); Intent intent = new Intent(getBaseContext(), XmppService.class); startService(intent); android.os.Handler handler = new android.os.Handler(); handler.postDelayed(new Runnable() { @Override public void run() { startActivity(new Intent(SplashScreen.this , ChatActivity.class)); finish(); } }, 3000); } }https://drive.google.com/file/d/0B1dF4YSBqUooQkhQam41TW1adTg/view?usp=sharing
Comments
Post a Comment