Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import android.app.Notification;
- import android.app.NotificationManager;
- import android.app.PendingIntent;
- import android.content.Context;
- import android.content.Intent;
- import android.content.SharedPreferences;
- import android.media.AudioManager;
- import android.media.RingtoneManager;
- import android.media.SoundPool;
- import android.net.Uri;
- import android.os.Bundle;
- import android.preference.PreferenceManager;
- import android.support.v7.app.AppCompatActivity;
- import android.text.TextUtils;
- import android.util.Log;
- import android.view.Menu;
- import android.view.MenuInflater;
- import android.view.MenuItem;
- import android.view.View;
- import android.widget.EditText;
- import android.widget.ImageButton;
- import android.widget.ListView;
- import android.widget.RelativeLayout;
- import android.widget.TextView;
- import com.google.gson.Gson;
- import com.google.gson.GsonBuilder;
- import org.json.JSONException;
- import org.json.JSONObject;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.text.DateFormat;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Date;
- public class ChatActivity extends AppCompatActivity {
- private EditText messageET;
- private static ListView messagesContainer;
- private ImageButton sendBtn;
- private ChatAdapter adapter;
- private ArrayList<ChatMessage> chatHistory;
- private ObjectInputStream objectInputStream;
- private ObjectOutputStream objectOutputStream;
- private final String AUTHKEYPREF = "BOOLEANAUTHKEY";
- private final String USERNAME = "USERNAME";
- private final String PASSWORD = "PASSWORD";
- private final String CHATTAG = "CHAT_ACTIVITY_TAG";
- public String login;
- private String token;
- private String hash;
- private Socket socket;
- ServerSocket _socketServer;
- private String server_address;
- private int server_port;
- public static String newMessage;
- public void listenNewMessages()
- {
- /*
- try {
- while (true) {
- Thread.sleep(500);
- SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
- RClient rClient = new RClient(server_address, server_port);
- MessioObject.GetMessageResponse response = rClient.getMessageFromHash(token,hash);
- if(response.isResult()&&response.getHash()!=hash)
- {
- ArrayList<RChecksum.Pair<String,String>> messagesList =
- response.getMessagesList();
- for(final RChecksum.Pair<String,String> pair : messagesList)
- {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- ChatMessage chatMessage = new ChatMessage();
- chatMessage.setMessage(pair.getRight());
- chatMessage.setMe(false);
- displayMessage(chatMessage);
- }
- });
- }
- }
- SharedPreferences s = getSharedPreferences("rset",MODE_PRIVATE);
- SharedPreferences.Editor sh = s.edit();
- sh.putString("HASH",response.getHash());
- sh.commit();
- }
- }
- catch (InterruptedException ex)
- {
- ex.printStackTrace();
- }
- */
- while (true)
- {
- try {
- Thread.sleep(10);
- Socket socket = _socketServer.accept();
- newMessage = new DataInputStream(socket.getInputStream()).readUTF();
- Log.d("MESSAGE", newMessage);
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- try {
- JSONObject jsonObject = new JSONObject(newMessage);
- ChatMessage chatMessage = new ChatMessage();
- Log.d("MESSAGETEXT", "message received" + jsonObject.toString());
- String author = jsonObject.getString("author");
- String text = jsonObject.getString("message");
- chatMessage.setMessage(jsonObject.getString("message"));
- chatMessage.setMe(false);
- chatMessage.setDate(DateFormat.getDateTimeInstance().format(new Date()) + "\n" + jsonObject.getString("author"));
- chatMessage.setId(1);
- chatMessage.setUserId(53);
- showNotification(text, author);
- displayMessage(chatMessage);
- }
- catch (JSONException ex)
- {
- }
- }
- });
- /*
- Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
- Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
- r.play();
- */
- socket.close();
- }
- catch (Exception ex)
- {
- // ex.printStackTrace();
- }
- }
- }
- public final static int NOTIFY_ID = 101;
- public void showNotification(String text, String author){
- Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
- Intent intent = new Intent(ChatActivity.this, ChatActivity.class);
- PendingIntent pIntent = PendingIntent.getActivity(ChatActivity.this, 0, intent, 0);
- Notification mNotification = new Notification.Builder(this)
- .setContentTitle(author + " send you a new message!" )
- .setContentText(text)
- .setSmallIcon(R.drawable.sendicon)
- .setContentIntent(pIntent)
- .setSound(soundUri)
- .addAction(R.drawable.sendicon, "View", pIntent)
- .addAction(0, "Remind", pIntent)
- .build();
- NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
- notificationManager.notify(0, mNotification);
- }
- public void cancelNotification(int notificationId){
- if (Context.NOTIFICATION_SERVICE!=null) {
- String ns = Context.NOTIFICATION_SERVICE;
- NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
- nMgr.cancel(notificationId);
- }
- }
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- SharedPreferences s = getSharedPreferences("rset", MODE_PRIVATE);
- token = s.getString("TOKEN","");
- hash = s.getString("HASH","");
- login = s.getString(USERNAME, "");
- SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
- server_address = sp.getString("server", "");
- server_port = Integer.parseInt(sp.getString("port", ""));
- if (!server_address.equals("") && server_port != 0) {
- try {
- Thread thread = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- _socketServer = new ServerSocket(1347);
- socket = new Socket(server_address, server_port);
- objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
- objectOutputStream.flush();
- objectInputStream = new ObjectInputStream(socket.getInputStream());
- }
- catch (IOException ex)
- {
- ex.printStackTrace();
- }
- RClient rClient = new RClient(server_address, server_port);
- }
- });
- thread.start();
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- setContentView(R.layout.activity_chat);
- initControls();
- }
- private void initControls() {
- adapter = new ChatAdapter(ChatActivity.this, new ArrayList<ChatMessage>());
- messagesContainer = (ListView) findViewById(R.id.messagesContainer);
- messageET = (EditText) findViewById(R.id.messageEdit);
- sendBtn = (ImageButton) findViewById(R.id.chatSendButton);
- TextView meLabel = (TextView) findViewById(R.id.meLbl);
- meLabel.setText(getSharedPreferences("rset", MODE_PRIVATE).getString(USERNAME, ""));
- TextView companionLabel = (TextView) findViewById(R.id.friendLabel);
- RelativeLayout container = (RelativeLayout) findViewById(R.id.container);
- companionLabel.setText("Chat");
- Thread _thread = new Thread(new Runnable() {
- @Override
- public void run() {
- listenNewMessages();
- }
- });
- /*
- Thread updateChatThread = new Thread(new Runnable() {
- @Override
- public void run() {
- while(true) {
- try {
- Thread.sleep(2000);
- doHistoryRequest();
- }
- catch (InterruptedException ex)
- {
- }
- }
- }
- });
- updateChatThread.start();
- */
- _thread.setDaemon(true);
- _thread.start();
- sendBtn.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- try {
- final String messageText = messageET.getText().toString();
- if (TextUtils.isEmpty(messageText)) {
- return;
- }
- messageET.setText("");
- Log.d(CHATTAG, messageText);
- SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
- final String server_address = sp.getString("server", "");
- final int server_port = Integer.parseInt(sp.getString("port", ""));
- Thread thread = new Thread(new Runnable() {
- @Override
- public void run() {
- if (!server_address.equals("") && server_port != 0)
- {
- String hash = null;
- RClient rClient = new RClient(server_address, server_port);
- try {
- hash = RChecksum.sha1hash(getCurrentTimeStamp() + login + messageText);
- }
- catch (Exception ex)
- {
- ex.printStackTrace();
- }
- MessioObject.SendMessageResponse response =
- rClient.sendMessageRequest(token,hash,messageText);
- final ChatMessage chatMessage = new ChatMessage();
- chatMessage.setMessage(messageText);
- chatMessage.setMe(true);
- chatMessage.setDate(DateFormat.getDateTimeInstance().format(new Date()));
- chatMessage.setId(1);
- SoundPool soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 100);
- soundPool.load(getApplicationContext(), R.raw.sound_in, 1);
- soundPool.play(1, 1, 1, 1, 0 ,1);
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- displayMessage(chatMessage);
- }
- });
- }
- }
- });
- thread.start();
- }
- catch (Exception ex)
- {
- ex.printStackTrace();
- }
- }
- });
- }
- public void displayMessage(ChatMessage message) {
- adapter.add(message);
- adapter.notifyDataSetChanged();
- scroll();
- }
- public String getDateFromUnixTimeStamp(long time)
- {
- Date date = new Date(time); // *1000 is to convert seconds to milliseconds
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // the format of your date
- return sdf.format(date);
- }
- private void scroll() {
- messagesContainer.setSelection(messagesContainer.getCount() - 1);
- }
- private void loadHistory(ArrayList<MessioObject.MessageDBItem> list) {
- chatHistory = new ArrayList<ChatMessage>();
- messagesContainer.setAdapter(null);
- ArrayList<ChatMessage> arrayList = new ArrayList<>();
- for(MessioObject.MessageDBItem item : list)
- {
- ChatMessage message = new ChatMessage();
- Log.d("History: ", "current login: " + login + "checking: " + item.getLOGIN());
- if(item.getLOGIN().equals(login)) {
- message.setMe(true);
- message.setDate(getDateFromUnixTimeStamp(item.getDATEOFMESSAGE()));
- }
- else {
- message.setMe(false);
- message.setDate(getDateFromUnixTimeStamp(item.getDATEOFMESSAGE()) + "\n" + item.getLOGIN());
- }
- message.setId(1);
- message.setUserId(53);
- message.setMessage(item.getMESSAGE());
- arrayList.add(message);
- }
- adapter = new ChatAdapter(ChatActivity.this, arrayList);
- messagesContainer.setAdapter(adapter);
- for (int i = 0; i < chatHistory.size(); i++) {
- ChatMessage message = chatHistory.get(i);
- displayMessage(message);
- scroll();
- }
- scroll();
- }
- public String getCurrentTimeStamp() {
- return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- MenuInflater menuInflater = getMenuInflater();
- menuInflater.inflate(R.menu.chatmenu, menu);
- return super.onCreateOptionsMenu(menu);
- }
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case R.id.exit_button: {
- SharedPreferences sharedPreferences = getSharedPreferences("rset", MODE_PRIVATE);
- SharedPreferences.Editor editor = sharedPreferences.edit();
- editor.putString("TOKEN", token);
- editor.putString(USERNAME, "");
- editor.putString(PASSWORD, "");
- editor.putBoolean("BOOLEANAUTHKEY", false);
- editor.commit();
- this.finish();
- }
- case R.id.update: {
- doHistoryRequest();
- }
- return true;
- default:
- // If we got here, the user's action was not recognized.
- // Invoke the superclass to handle it.
- return super.onOptionsItemSelected(item);
- }
- }
- public void doHistoryRequest()
- {
- Thread thread = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- Socket socket = new Socket(server_address, server_port);
- DataOutputStream os = new DataOutputStream(socket.getOutputStream());
- os.flush();
- DataInputStream is = new DataInputStream(socket.getInputStream());
- MessioObject.GetHistoryMessagesRequest request = new
- MessioObject.GetHistoryMessagesRequest();
- request.setToken(token);
- request.setType(MessioObject.GETALLCHATHISTORY_REQUEST);
- Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create();
- os.writeUTF(gson.toJson(request));
- os.flush();
- String re = is.readUTF();
- final MessioObject.GetHistoryMessagesResponse response =
- gson.fromJson(re, MessioObject.GetHistoryMessagesResponse.class);
- Log.d("tag", re);
- socket.close();
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- loadHistory(response.getMessagesList());
- }
- });
- } catch (Exception ex) {
- }
- }
- });
- thread.start();
- }
- @Override
- public void onBackPressed() {
- super.onBackPressed();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement