All pastes #2132717 Raw Edit

nikki

public text v1 · immutable
#2132717 ·published 2012-03-27 13:21 UTC
rendered paste body
package com.live2support;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;




import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;

import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class VisitorChat extends Activity   {



	private static final String TAG = "Chat";
	private static final boolean D = true;
	private final int NOTIFICATION_ID = 1012;
	private int sendmsg,receivemsg;
	private ArrayList<String> chatMessages;
	BackgroundThread backgroundThread;


	private NotificationManager mNotificationManager;

	private String response;
	private String chatMsg,previousChatMsg,sender,textchat,lastnum;
	String[] timeduration;
	public static String sendmessage,receivedmsg;
	// Layout Views
	private ListView 	mConversationView;
	private EditText 	mOutEditText;
	private Button 		mSendButton,header,showall;
	private String delimiter,delimiter1,delimiter2,delimiter3,url;

	private TextView message;
	private String[] valueArray,valueArray1,messagelist,temp1;
	private String strchattext,strResponseFirst,strMsgNewNum,strMsgOldNum;
	private CustomAdapter mAdapter;

	// Member object for the chat services
	private static final String DEB_TAG = "Error Message";

	final static int PACKET_CAME = 1;
	final static int TOAST1  = 2;
	protected static final int TOAST = 0;
	//user name
	private String mUserName= Main.loginId.getText().toString();
	ServerThread 	myThread;
	private Timer timer = new Timer();
	int odd_resID,even_resID;
	
	public class BackgroundThread extends Thread {

		 boolean running = false;

		 void setRunning(boolean b){
		  running = b;
		 }

		 @Override
		 public void run() {
		  // TODO Auto-generated method stub
		  //super.run();
		  while(running){
		   try {
		    sleep(1000);
		   } catch (InterruptedException e) {
		    // TODO Auto-generated catch block
		    e.printStackTrace();
		   }
		   getResponseMessage(BaseActivity.session);
		   
		  }
		 }

		}



	public void setUserName(String userName){

		mUserName = userName;
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat);

		Log.i(DEB_TAG, "error in chat window");

		header = (Button) findViewById(R.id.btnheadertext);

		showall = (Button) findViewById(R.id.btnshowall);
		
		Controls.preferences = getPreferences(MODE_PRIVATE);
		Controls.chatOnlyPref = Controls.preferences.getBoolean("chatOnlyPref", true);  //default is true
		Controls.soundOnlyPref = Controls.preferences.getBoolean("soundOnlyPref", true);

		

		// Initialize the compose field with a listener for the return key
		mOutEditText = (EditText) findViewById(R.id.edit_text_out);

		mSendButton = (Button) findViewById(R.id.button_send);
		//mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message3);
		mConversationView = (ListView) findViewById(R.id.in);

		chatMessages = new ArrayList<String>();

		mConversationView.setDivider(null);
		mConversationView.setDividerHeight(0);

		if(D) Log.e(TAG, "+++ ON CREATE +++");

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			try{

				extras.getString(BaseActivity.ip);
				extras.getString(BaseActivity.session);
				extras.getString(BaseActivity.status);
				extras.getString("from");

				extras.getInt("Position");
				extras.getString(VisitorDetail.name);


				setTitle("Messaging with " + BaseActivity.ip);
			}
			catch(Exception e){
				e.printStackTrace();
			}



		}
		try{

			header.setText(BaseActivity.ip);
		}catch(Exception e){
			e.printStackTrace();
		}



		mAdapter = new CustomAdapter();
		mConversationView.setAdapter(mAdapter);
		mConversationView.setCacheColorHint(0);

		
	

		message = (TextView) findViewById(R.id.edit_text_out);
		sendmessage = message.getText().toString();
		mSendButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(D) Log.e(TAG, "[sendButton clicked]");
				// Send a message using content of the edit text widget
				message = (TextView) findViewById(R.id.edit_text_out);
				sendmessage = message.getText().toString();

				try{
					setupChat(BaseActivity.session);
					postMessage();
				}
				catch(Exception e){
					e.printStackTrace();
				}
				
				/*TimerTask timerTask = new TimerTask()
				{
					@Override
					public void run()
					{


						try{

							getResponseMessage(BaseActivity.session);
						}
						catch(Exception e){
							e.printStackTrace();
						}
						

					}


				};
				timer.schedule(timerTask, 6000);*/

				
			}



		});

		showall.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent intent = new Intent(VisitorChat.this,MultiChat.class);
				startActivity(intent);

			}


		});


	}

	public void onStart() {
		super.onStart();
		if(D) Log.e(TAG, "++ ON START ++");

		/*TimerTask timerTask = new TimerTask()
		{
			@Override
			public void run()
			{


				try{

					getResponseMessage(BaseActivity.session);
				}
				catch(Exception e){
					e.printStackTrace();
				}
				

			}


		};
		timer.schedule(timerTask, 6000);*/
		myMethod();
		backgroundThread = new BackgroundThread();
		 backgroundThread.setRunning(true);
		       backgroundThread.start();
		       Toast.makeText(this, "onStart()", Toast.LENGTH_LONG).show();


				
		

	}


	//------------------------Showing all chat message to user----------------------------

	private void myMethod(){

		url = "http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_GETCHAT_TEXT;
		final HashMap<String, String> postParameters = new HashMap<String, String>();

		try{
			postParameters.put("uname", VisitorDetail.name);
			postParameters.put("adminid", Main.loginId.getText().toString());
			postParameters.put("csesid",BaseActivity.session);
			postParameters.put("ipadd",BaseActivity.ip);	
			postParameters.put("sid", Main.siteId.getText().toString());
			postParameters.put("lastnum", "0");

		}
		catch(Exception e){
			e.printStackTrace();
		}

		Runnable searchThread = new Runnable(){

			public void run() {
				// TODO Auto-generated method stub

				try {
					response = CustomHttpClient.executeHttpPost1(url,postParameters);

					Log.i(DEB_TAG, "Requesting to server"+response);


					System.out.println("the chat msg are================:"+response);



				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(response!=null){

					runOnUiThread(new Runnable() {

						public void run() {
							// TODO Auto-generated method stub
							delimiter = "<l2s_type_split>";
							delimiter1= "<l2s_blk>";
							delimiter2 = "<l2s_ln>";
							delimiter3 = "<nsp>";

							valueArray = response.split(delimiter);
							//lastnum = valueArray[1];
							//System.out.println("lastnum is"+lastnum);
							if(valueArray.length==3){

								strResponseFirst = valueArray[0];
								System.out.println("first response================"+strResponseFirst);

								if(!strResponseFirst.equalsIgnoreCase("")){

									valueArray1 = strResponseFirst.split(delimiter1);

									if(valueArray1.length==4){

										strchattext = valueArray1[0];
										strMsgNewNum = valueArray1[1];
										strMsgOldNum = valueArray1[2];

										temp1 = strchattext.split(delimiter2);


										for(int i=0;i<temp1.length;i++){

											System.out.println("temp value are============="+temp1[i]);
										}
										if(strMsgNewNum!=strMsgOldNum){

											for(int i=0;i<temp1.length;i++){

												String strToAppend = temp1[i];

												messagelist = strToAppend.split(delimiter3);

												if(messagelist.length==3){

													chatMsg = messagelist[2];

													previousChatMsg = temp1[0];
													timeduration = temp1[1].split(delimiter3);

													sender = messagelist[0];
													chatMessages.add(sender+":"+chatMsg);
													receivemsg =1;

													System.out.println("previouschatmsg=========="+previousChatMsg);
													System.out.println("chatmsg=========="+chatMsg);
													System.out.println("name of sender=========="+sender);
													
													
												}


												System.out.println("chattext============="+messagelist[0]);
											}


											if(chatMsg.equals("chat close by user")){
												System.out.println("chattext============="+messagelist[0]);

											}
										}
									}

								}
							}


							mConversationView.getDrawingCache(false);
							mConversationView.invalidateViews();
							mConversationView.setCacheColorHint(Color.TRANSPARENT);
							mConversationView.requestFocus(0);


						}

					});
				}


			}


		};

		Thread thread =  new Thread(null, searchThread, "MagentoBackground");
		thread.start();

	}

	//--------------Called this method when send any message--------------

	private void postMessage() {
		// TODO Auto-generated method stub

		String theNewMessage = message.getText().toString();
		try{
			chatMessages.add(mUserName+":"+theNewMessage);
			message.setText("");
		}catch(Exception e){
			Log.e(DEB_TAG, "Can not send message"+e.getMessage());
		}
		sendmsg =1;



	}

	//---------------------the Custom adapter class-------------------------

	class CustomAdapter extends BaseAdapter {
		LayoutInflater mInflater;

		public CustomAdapter() {

			mInflater = getLayoutInflater();
			this.notifyDataSetChanged();
			chatMessages.clear();

		}



		public int getCount() {
			return chatMessages.size();
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(final int position, View convertView, ViewGroup parent) {


			View row = null;
			Log.i("sentmsg", Integer.toString(sendmsg));
			Log.i("revmsg", Integer.toString(receivemsg));
			if(position%2==0){
				row = mInflater.inflate(R.layout.list_row_layout_even, parent, false);
				Button img = (Button) row.findViewById(R.id.even_bubble);			
				img.setText(chatMessages.get(position));


			}else{
				row = mInflater.inflate(R.layout.list_row_layout_odd, parent, false);
				Button textLabel = (Button) row.findViewById(R.id.odd_bubble);				
				textLabel.setText(chatMessages.get(position));
			}

			return (row);
		}
	}



	//---------------------Getting the response message of visitor-----------------------------

	private void getResponseMessage(String session){

		url = "http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_GETCHAT_TEXT;
		final HashMap<String, String> postParameters = new HashMap<String, String>();

		try{
			postParameters.put("uname", VisitorDetail.name);
			postParameters.put("adminid", Main.loginId.getText().toString());
			postParameters.put("sid", Main.siteId.getText().toString());
			if(BaseActivity.session!=null){
				postParameters.put("csesid",BaseActivity.session);	
			}
			postParameters.put("lastnum", lastnum);

		}
		catch(Exception e){
			e.printStackTrace();
		}



		Runnable searchThread = new Runnable(){

			public void run() {
				// TODO Auto-generated method stub

				try {
					response = CustomHttpClient.executeHttpPost1(url,postParameters);

					Log.i(DEB_TAG, "Requesting to server"+response);
					//CustomHttpClient.getResponseInString(response );

					delimiter = "<l2s_type_split>";
					delimiter1= "<l2s_blk>";
					delimiter2 = "<l2s_ln>";
					delimiter3 = "<nsp>";

					valueArray = response.split(delimiter);

					if(valueArray.length==3){

						strResponseFirst = valueArray[0];
						System.out.println("first response================"+strResponseFirst);

						if(!strResponseFirst.equalsIgnoreCase("")){

							valueArray1 = strResponseFirst.split(delimiter1);

							if(valueArray1.length==4){

								strchattext = valueArray1[0];
								strMsgNewNum = valueArray1[1];
								strMsgOldNum = valueArray1[2];

								System.out.println("strchattext=================="+valueArray1[0]+"\n"+"strMsgNewNum======================"+strMsgNewNum+"\n"+"strOldNum============"+strMsgOldNum);

								temp1 = strchattext.split(delimiter2);

								System.out.println("value of temp variable"+temp1[1]);
								System.out.println("value of strchatmsg============="+valueArray1[0]+"\n"+"value of new num"+valueArray1[1]+"\n"+"value of old num=="+strMsgOldNum);

								for(int i=0;i<temp1.length;i++){

									System.out.println("temp value are============="+temp1[i]);
								}
								if(strMsgNewNum!=strMsgOldNum){


									for(int i=0;i<temp1.length;i++){

										String strToAppend = temp1[i];

										messagelist = strToAppend.split(delimiter3);

										if(messagelist.length==3){

											chatMsg = messagelist[2];

											previousChatMsg = temp1[0];
											timeduration = temp1[1].split(delimiter3);

											sender = messagelist[0];

											System.out.println("previouschatmsg=========="+previousChatMsg);
											System.out.println("chatmsg=========="+chatMsg);
											System.out.println("name of sender=========="+sender);
											System.out.println("time duration=========="+timeduration);
										}


										else if(sender.equals(Main.loginId.getText().toString())){

											textchat = messagelist[0];

											System.out.println("textchat message are the followings"+textchat);
										}

										else {
											if(sender.equals("notice")){
												String textchat = messagelist[0];
											}
										}

										System.out.println("chattext============="+messagelist[0]);
									}
								}


								if(chatMsg.equals("chat close by user")){
									System.out.println("chattext============="+messagelist[0]);

								}
							}
							lastnum = strMsgNewNum;

						}
					}



				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(response!=null){

					runOnUiThread(new Runnable() {

						public void run() {
							// TODO Auto-generated method stub
							if(CustomHttpClient.Response.getStatusLine().getStatusCode()==200){

								try{

									if(chatMsg!=null)
										handleMessage(chatMsg);
								}catch(Exception e){
									e.printStackTrace();
								}
								TimerTask timerTask = new TimerTask()
								{
									@Override
									public void run()
									{
										//playsound();
										try{
											triggerNotification(chatMsg,strMsgNewNum);
										}catch(Exception e){
											e.printStackTrace();
										}

									}


								};
								timer.schedule(timerTask, 10000);
							}

						}





					});
				}

			}



		};

		Thread thread =  new Thread(null, searchThread, "MagentoBackground");
		thread.start();

	}

	//----------Show notification when any response message occurs--------------------

	private void triggerNotification(String chatMsg, String strMsgNewNum) {
		// TODO Auto-generated method stub
		CharSequence title = "A new Message arrived";

		NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		Notification notification = new Notification(R.drawable.chat, chatMsg, System.currentTimeMillis());
		notification.flags |= Notification.FLAG_AUTO_CANCEL;

		Intent notificationIntent = new Intent(this, VisitorChat.class);
		notificationIntent.putExtra("strMsgNewNum", strMsgNewNum);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

		notification.setLatestEventInfo(VisitorChat.this, title, chatMsg, pendingIntent);
		notificationManager.notify(NOTIFICATION_ID, notification);
	}

	public void completed()    {
		//remove the notification from the status bar
		mNotificationManager.cancel(NOTIFICATION_ID);
	}

	public static void CancelNotification(Context ctx, int notifyId) {
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager nMgr = (NotificationManager) ctx.getSystemService(ns);
		nMgr.cancel(notifyId);
	}



	private void playsound() {
		// TODO Auto-generated method stub
		MediaPlayer mp = MediaPlayer.create(this, R.raw.chatmessage);
            if(Controls.soundonly.isChecked()){
			mp.start();
            }


	}



	//--------------------Start Chatting from here-----------------------------------

	private void setupChat(String session) {
		// TODO Auto-generated method stub


		url = "http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_SEND_CSRMSG;
		final HashMap<String, String> postParameters = new HashMap<String, String>();
		try{
			postParameters.put("say",sendmessage);	
			if(BaseActivity.session!=null){
				postParameters.put("csesid",BaseActivity.session);	
			}
			if(Main.loginId.getText().toString()!=null){
				postParameters.put("adminid", Main.loginId.getText().toString());
			}
			postParameters.put("sid", Main.siteId.getText().toString());
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}

		Runnable searchThread = new Runnable(){

			public void run() {
				// TODO Auto-generated method stub

				try {
					response = CustomHttpClient.executeHttpPost1(url,postParameters);

					Log.i(DEB_TAG, "Requesting to server"+response);
					//CustomHttpClient.getResponseInString(response );

					System.out.println("Output of httpResponse:"+response);


				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(response!=null){

					runOnUiThread(new Runnable() {

						public void run() {

							if(CustomHttpClient.Response.getStatusLine().getStatusCode()==200){
								// TODO Auto-generated method stub

								System.out.println(response);
								//playsound();


							}

						}




					});
				}


			}


		};

		Thread thread =  new Thread(null, searchThread, "MagentoBackground");
		thread.start();


	}

	

	//--------------------For seeing message if any exists--------------------

	private void handleMessage(String receivedmsg) {
		// TODO Auto-generated method stub
		String receivemsg = receivedmsg;
		try{
			if(BaseActivity.ip!=null)
				chatMessages.add(BaseActivity.ip+":"+receivemsg);

			message.setText("");


		}

		catch(Exception e){
			e.printStackTrace();
		}


	}
	
	@Override
	protected void onStop() {
	 // TODO Auto-generated method stub
	 super.onStop();

	
	 backgroundThread.setRunning(false);

	

	 Toast.makeText(this, "onStop()", Toast.LENGTH_LONG).show();

	}
	
	@Override
	protected void onDestroy() {
	 // TODO Auto-generated method stub
	 super.onDestroy();

	
	 backgroundThread.setRunning(false);

	 

	 Toast.makeText(this, "onStop()", Toast.LENGTH_LONG).show();

	}




	//---------------------when user click any of these button---------------



	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {			
			finish();
			return true;	
		}
		return super.onKeyDown(keyCode, event);
	}



}