ConversationActivity.java

  1package de.gultsch.chat.ui;
  2
  3import java.util.ArrayList;
  4import java.util.Collections;
  5import java.util.Comparator;
  6import java.util.List;
  7
  8import de.gultsch.chat.R;
  9import de.gultsch.chat.R.id;
 10import de.gultsch.chat.entities.Contact;
 11import de.gultsch.chat.entities.Conversation;
 12import de.gultsch.chat.utils.UIHelper;
 13import android.net.Uri;
 14import android.os.Bundle;
 15import android.app.FragmentTransaction;
 16import android.app.NotificationManager;
 17import android.content.Context;
 18import android.content.Intent;
 19import android.support.v4.widget.SlidingPaneLayout;
 20import android.support.v4.widget.SlidingPaneLayout.PanelSlideListener;
 21import android.util.Log;
 22import android.view.KeyEvent;
 23import android.view.LayoutInflater;
 24import android.view.Menu;
 25import android.view.MenuItem;
 26import android.view.View;
 27import android.view.ViewGroup;
 28import android.view.inputmethod.InputMethodManager;
 29import android.widget.AdapterView;
 30import android.widget.AdapterView.OnItemClickListener;
 31import android.widget.ArrayAdapter;
 32import android.widget.ListView;
 33import android.widget.TextView;
 34import android.widget.ImageView;
 35
 36public class ConversationActivity extends XmppActivity {
 37
 38	public static final String VIEW_CONVERSATION = "viewConversation";
 39	public static final String CONVERSATION = "conversationUuid";
 40	
 41	public static final int INSERT_CONTACT = 0x9889;
 42
 43	protected SlidingPaneLayout spl;
 44
 45	private List<Conversation> conversationList = new ArrayList<Conversation>();
 46	private Conversation selectedConversation = null;
 47	private ListView listView;
 48	
 49	private boolean paneShouldBeOpen = true;
 50	private ArrayAdapter<Conversation> listAdapter;
 51	
 52	private OnConversationListChangedListener onConvChanged = new OnConversationListChangedListener() {
 53		
 54		@Override
 55		public void onConversationListChanged() {
 56			final Conversation currentConv = getSelectedConversation();
 57			conversationList.clear();
 58			conversationList.addAll(xmppConnectionService
 59					.getConversations());
 60			runOnUiThread(new Runnable() {
 61				
 62				@Override
 63				public void run() {	
 64					updateConversationList();
 65					/*for(int i = 0; i < conversationList.size(); ++i) {
 66						if (currentConv == conversationList.get(i)) {
 67							selectedConversation = conversationList.get(i);
 68							break;
 69						}
 70					}*/
 71					if(paneShouldBeOpen) {
 72						selectedConversation = conversationList.get(0);
 73						if (conversationList.size() >= 1) {
 74							swapConversationFragment();
 75						} else {
 76							startActivity(new Intent(getApplicationContext(), NewConversationActivity.class));
 77							finish();
 78						}
 79					}
 80					ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager().findFragmentByTag("conversation");
 81					if (selectedFragment!=null) {
 82						selectedFragment.updateMessages();
 83					}
 84				}
 85			});
 86		}
 87	};
 88	private boolean contactInserted = false;
 89	
 90	
 91	public List<Conversation> getConversationList() {
 92		return this.conversationList;
 93	}
 94
 95	public Conversation getSelectedConversation() {
 96		return this.selectedConversation;
 97	}
 98	
 99	public ListView getConversationListView() {
100		return this.listView;
101	}
102	
103	public SlidingPaneLayout getSlidingPaneLayout() {
104		return this.spl;
105	}
106	
107	public boolean shouldPaneBeOpen() {
108		return paneShouldBeOpen;
109	}
110	
111	public void updateConversationList() {
112		if (conversationList.size() >= 1) {
113			Collections.sort(this.conversationList, new Comparator<Conversation>() {
114				@Override
115				public int compare(Conversation lhs, Conversation rhs) {
116					return (int) (rhs.getLatestMessageDate() - lhs.getLatestMessageDate());
117				}
118			});
119		}
120		this.listView.invalidateViews();
121	}
122	
123	@Override
124	protected void onCreate(Bundle savedInstanceState) {
125
126		super.onCreate(savedInstanceState);
127
128		setContentView(R.layout.fragment_conversations_overview);
129
130		listView = (ListView) findViewById(R.id.list);
131
132		this.listAdapter = new ArrayAdapter<Conversation>(this,
133				R.layout.conversation_list_row, conversationList) {
134			@Override
135			public View getView(int position, View view, ViewGroup parent) {
136				if (view == null) {
137					LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
138					view = (View) inflater.inflate(
139							R.layout.conversation_list_row, null);
140				}
141				((TextView) view.findViewById(R.id.conversation_name))
142						.setText(getItem(position).getName());
143				((TextView) view.findViewById(R.id.conversation_lastmsg)).setText(getItem(position).getLatestMessage());
144				((TextView) view.findViewById(R.id.conversation_lastupdate))
145				.setText(UIHelper.readableTimeDifference(getItem(position).getLatestMessageDate()));
146				
147				Uri profilePhoto = getItem(position).getProfilePhotoUri();
148				ImageView imageView = (ImageView) view.findViewById(R.id.conversation_image);
149				if (profilePhoto!=null) {
150					imageView.setImageURI(profilePhoto);
151				} else {
152					imageView.setImageBitmap(UIHelper.getUnknownContactPicture(getItem(position).getName(),200));
153				}
154				
155				
156				((ImageView) view.findViewById(R.id.conversation_image))
157						.setImageURI(getItem(position).getProfilePhotoUri());
158				return view;
159			}
160
161		};
162		
163		listView.setAdapter(this.listAdapter);
164
165		listView.setOnItemClickListener(new OnItemClickListener() {
166
167			@Override
168			public void onItemClick(AdapterView<?> arg0, View clickedView,
169					int position, long arg3) {
170				paneShouldBeOpen = false;
171				if (selectedConversation != conversationList.get(position)) {
172					selectedConversation = conversationList.get(position);
173					swapConversationFragment(); //.onBackendConnected(conversationList.get(position));
174				} else {
175					spl.closePane();
176				}
177			}
178		});
179		spl = (SlidingPaneLayout) findViewById(id.slidingpanelayout);
180		spl.setParallaxDistance(150);
181		spl.setShadowResource(R.drawable.es_slidingpane_shadow);
182		spl.setSliderFadeColor(0);
183		spl.setPanelSlideListener(new PanelSlideListener() {
184
185			@Override
186			public void onPanelOpened(View arg0) {
187				paneShouldBeOpen = true;
188				getActionBar().setDisplayHomeAsUpEnabled(false);
189				getActionBar().setTitle(R.string.app_name);
190				invalidateOptionsMenu();
191
192				InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
193
194				View focus = getCurrentFocus();
195
196				if (focus != null) {
197
198					inputManager.hideSoftInputFromWindow(
199							focus.getWindowToken(),
200							InputMethodManager.HIDE_NOT_ALWAYS);
201				}
202			}
203
204			@Override
205			public void onPanelClosed(View arg0) {
206				paneShouldBeOpen = false;
207				if (conversationList.size() > 0) {
208					getActionBar().setDisplayHomeAsUpEnabled(true);
209					getActionBar().setTitle(getSelectedConversation().getName());
210					invalidateOptionsMenu();
211				}
212			}
213
214			@Override
215			public void onPanelSlide(View arg0, float arg1) {
216				// TODO Auto-generated method stub
217
218			}
219		});
220	}
221
222	@Override
223	public boolean onCreateOptionsMenu(Menu menu) {
224		getMenuInflater().inflate(R.menu.conversations, menu);
225
226		if (spl.isOpen()) {
227			((MenuItem) menu.findItem(R.id.action_archive)).setVisible(false);
228			((MenuItem) menu.findItem(R.id.action_details)).setVisible(false);
229			((MenuItem) menu.findItem(R.id.action_security)).setVisible(false);
230		} else {
231			((MenuItem) menu.findItem(R.id.action_add)).setVisible(false);
232			if (this.getSelectedConversation()!=null) {
233				if (this.getSelectedConversation().getMode() == Conversation.MODE_MULTI) {
234					((MenuItem) menu.findItem(R.id.action_security)).setVisible(false);
235					((MenuItem) menu.findItem(R.id.action_details)).setVisible(false);
236					((MenuItem) menu.findItem(R.id.action_archive)).setTitle("Leave conference");
237				}
238			}
239		}
240		return true;
241	}
242
243	@Override
244	public boolean onOptionsItemSelected(MenuItem item) {
245		switch (item.getItemId()) {
246		case android.R.id.home:
247			spl.openPane();
248			break;
249		case R.id.action_settings:
250			startActivity(new Intent(this, SettingsActivity.class));
251			break;
252		case R.id.action_accounts:
253			startActivity(new Intent(this, ManageAccountActivity.class));
254			break;
255		case R.id.action_add:
256			startActivity(new Intent(this, NewConversationActivity.class));
257			break;
258		case R.id.action_archive:
259			Conversation conv = getSelectedConversation();
260			conv.setStatus(Conversation.STATUS_ARCHIVED);
261			paneShouldBeOpen = true;
262			spl.openPane();
263			xmppConnectionService.archiveConversation(conv);
264			selectedConversation = conversationList.get(0);
265			break;
266		case R.id.action_details:
267			DialogContactDetails details = new DialogContactDetails();
268			Contact contact = xmppConnectionService.findOrCreateContact(this.getSelectedConversation().getAccount(),this.getSelectedConversation().getContactJid());
269			details.setContact(contact);
270			details.show(getFragmentManager(), "details");
271			break;
272		default:
273			break;
274		}
275		return super.onOptionsItemSelected(item);
276	}
277
278	protected ConversationFragment swapConversationFragment() {
279		ConversationFragment selectedFragment = new ConversationFragment();
280		
281		FragmentTransaction transaction = getFragmentManager()
282				.beginTransaction();
283		transaction.replace(R.id.selected_conversation, selectedFragment,"conversation");
284		transaction.commit();
285		return selectedFragment;
286	}
287
288	@Override
289	public boolean onKeyDown(int keyCode, KeyEvent event) {
290		if (keyCode == KeyEvent.KEYCODE_BACK) {
291			if (!spl.isOpen()) {
292				spl.openPane();
293				return false;
294			}
295		}
296		return super.onKeyDown(keyCode, event);
297	}
298	
299	public void onStart() {
300		super.onStart();
301		NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
302		nm.cancelAll();
303		if (conversationList.size()>=1) {
304			onConvChanged.onConversationListChanged();
305		}
306	}
307	
308	/*@Override
309	protected void onPause() {
310		super.onPause();
311		if (xmppConnectionServiceBound) {
312        	xmppConnectionService.removeOnConversationListChangedListener();
313            unbindService(mConnection);
314            xmppConnectionServiceBound = false;
315        }
316	}*/
317	
318	@Override
319	protected void onStop() {
320		Log.d("gultsch","called on stop in conversation activity");
321		if (xmppConnectionServiceBound) {
322        	xmppConnectionService.removeOnConversationListChangedListener();
323		}
324		super.onStop();
325	}
326
327	@Override
328	void onBackendConnected() {
329		
330		
331		if (contactInserted) {
332			Log.d("xmppService","merge phone contacts with roster");
333			contactInserted = false;
334			xmppConnectionService.mergePhoneContactsWithRoster();
335		}
336		
337		xmppConnectionService.setOnConversationListChangedListener(this.onConvChanged);
338		
339		if (conversationList.size()==0) {
340			conversationList.clear();
341			conversationList.addAll(xmppConnectionService
342					.getConversations());
343			
344			for(Conversation conversation : conversationList) {
345				conversation.setMessages(xmppConnectionService.getMessages(conversation));
346			}
347	
348			this.updateConversationList();
349		}
350
351		if ((getIntent().getAction().equals(Intent.ACTION_VIEW) && (!handledViewIntent))) {
352			if (getIntent().getType().equals(
353					ConversationActivity.VIEW_CONVERSATION)) {
354				handledViewIntent = true;
355
356				String convToView = (String) getIntent().getExtras().get(CONVERSATION);
357
358				for(int i = 0; i < conversationList.size(); ++i) {
359					if (conversationList.get(i).getUuid().equals(convToView)) {
360						selectedConversation = conversationList.get(i);
361					}
362				}
363				paneShouldBeOpen = false;
364				swapConversationFragment();
365			}
366		} else {
367			if (xmppConnectionService.getAccounts().size() == 0) {
368				startActivity(new Intent(this, ManageAccountActivity.class));
369				finish();
370			} else if (conversationList.size() <= 0) {
371				//add no history
372				startActivity(new Intent(this, NewConversationActivity.class));
373				finish();
374			} else {
375				spl.openPane();
376				//find currently loaded fragment
377				ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager().findFragmentByTag("conversation");
378				if (selectedFragment!=null) {
379					Log.d("gultsch","ConversationActivity. found old fragment.");
380					selectedFragment.onBackendConnected();
381				} else {
382					Log.d("gultsch","conversationactivity. no old fragment found. creating new one");
383					selectedConversation = conversationList.get(0);
384					Log.d("gultsch","selected conversation is #"+selectedConversation);
385					swapConversationFragment();
386				}
387			}
388		}
389	}
390	
391	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
392		if (requestCode==INSERT_CONTACT) {
393			Log.d("xmppService","contact inserted");
394			this.contactInserted  = true;
395		}
396	}
397}