1package eu.siacs.conversations.ui;
2
3import java.io.FileNotFoundException;
4import java.lang.ref.WeakReference;
5import java.util.ArrayList;
6import java.util.Hashtable;
7import java.util.List;
8
9import eu.siacs.conversations.R;
10import eu.siacs.conversations.entities.Account;
11import eu.siacs.conversations.entities.Contact;
12import eu.siacs.conversations.entities.Conversation;
13import eu.siacs.conversations.entities.Message;
14import eu.siacs.conversations.utils.ExceptionHelper;
15import eu.siacs.conversations.utils.UIHelper;
16import android.os.AsyncTask;
17import android.os.Bundle;
18import android.preference.PreferenceManager;
19import android.app.AlertDialog;
20import android.app.FragmentTransaction;
21import android.content.Context;
22import android.content.DialogInterface;
23import android.content.DialogInterface.OnClickListener;
24import android.content.Intent;
25import android.content.SharedPreferences;
26import android.content.res.Resources;
27import android.graphics.Bitmap;
28import android.graphics.Color;
29import android.graphics.Typeface;
30import android.graphics.drawable.BitmapDrawable;
31import android.graphics.drawable.Drawable;
32import android.support.v4.widget.SlidingPaneLayout;
33import android.support.v4.widget.SlidingPaneLayout.PanelSlideListener;
34import android.util.DisplayMetrics;
35import android.util.Log;
36import android.view.KeyEvent;
37import android.view.LayoutInflater;
38import android.view.Menu;
39import android.view.MenuItem;
40import android.view.View;
41import android.view.ViewGroup;
42import android.widget.AdapterView;
43import android.widget.AdapterView.OnItemClickListener;
44import android.widget.ArrayAdapter;
45import android.widget.CheckBox;
46import android.widget.ListView;
47import android.widget.PopupMenu;
48import android.widget.PopupMenu.OnMenuItemClickListener;
49import android.widget.TextView;
50import android.widget.ImageView;
51
52public class ConversationActivity extends XmppActivity {
53
54 public static final String VIEW_CONVERSATION = "viewConversation";
55 public static final String CONVERSATION = "conversationUuid";
56 public static final String TEXT = "text";
57 public static final String PRESENCE = "eu.siacs.conversations.presence";
58
59 public static final int REQUEST_SEND_MESSAGE = 0x75441;
60 public static final int REQUEST_DECRYPT_PGP = 0x76783;
61 private static final int ATTACH_FILE = 0x48502;
62
63 protected SlidingPaneLayout spl;
64
65 private List<Conversation> conversationList = new ArrayList<Conversation>();
66 private Conversation selectedConversation = null;
67 private ListView listView;
68
69 private boolean paneShouldBeOpen = true;
70 private boolean useSubject = true;
71 private ArrayAdapter<Conversation> listAdapter;
72
73 private OnConversationListChangedListener onConvChanged = new OnConversationListChangedListener() {
74
75 @Override
76 public void onConversationListChanged() {
77 runOnUiThread(new Runnable() {
78
79 @Override
80 public void run() {
81 updateConversationList();
82 if (paneShouldBeOpen) {
83 if (conversationList.size() >= 1) {
84 swapConversationFragment();
85 } else {
86 startActivity(new Intent(getApplicationContext(),
87 ContactsActivity.class));
88 finish();
89 }
90 }
91 ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
92 .findFragmentByTag("conversation");
93 if (selectedFragment != null) {
94 selectedFragment.updateMessages();
95 }
96 }
97 });
98 }
99 };
100
101 protected ConversationActivity activity = this;
102 private DisplayMetrics metrics;
103
104 public List<Conversation> getConversationList() {
105 return this.conversationList;
106 }
107
108 public Conversation getSelectedConversation() {
109 return this.selectedConversation;
110 }
111
112 public ListView getConversationListView() {
113 return this.listView;
114 }
115
116 public SlidingPaneLayout getSlidingPaneLayout() {
117 return this.spl;
118 }
119
120 public boolean shouldPaneBeOpen() {
121 return paneShouldBeOpen;
122 }
123
124 @Override
125 protected void onCreate(Bundle savedInstanceState) {
126
127 metrics = getResources().getDisplayMetrics();
128
129 super.onCreate(savedInstanceState);
130
131 setContentView(R.layout.fragment_conversations_overview);
132
133 listView = (ListView) findViewById(R.id.list);
134
135 this.listAdapter = new ArrayAdapter<Conversation>(this,
136 R.layout.conversation_list_row, conversationList) {
137 @Override
138 public View getView(int position, View view, ViewGroup parent) {
139 if (view == null) {
140 LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
141 view = (View) inflater.inflate(
142 R.layout.conversation_list_row, null);
143 }
144 Conversation conv;
145 if (conversationList.size() > position) {
146 conv = getItem(position);
147 } else {
148 return view;
149 }
150 if (!spl.isSlideable()) {
151 if (conv == getSelectedConversation()) {
152 view.setBackgroundColor(0xffdddddd);
153 } else {
154 view.setBackgroundColor(Color.TRANSPARENT);
155 }
156 } else {
157 view.setBackgroundColor(Color.TRANSPARENT);
158 }
159 TextView convName = (TextView) view
160 .findViewById(R.id.conversation_name);
161 convName.setText(conv.getName(useSubject));
162 TextView convLastMsg = (TextView) view
163 .findViewById(R.id.conversation_lastmsg);
164 ImageView imagePreview = (ImageView) view.findViewById(R.id.conversation_lastimage);
165
166 Message latestMessage = conv.getLatestMessage();
167
168 if (latestMessage.getType() == Message.TYPE_TEXT) {
169 convLastMsg.setText(conv.getLatestMessage().getBody());
170 convLastMsg.setVisibility(View.VISIBLE);
171 imagePreview.setVisibility(View.GONE);
172 } else if (latestMessage.getType() == Message.TYPE_IMAGE) {
173 if ((latestMessage.getStatus() >= Message.STATUS_RECIEVED)&&(latestMessage.getStatus() != Message.STATUS_PREPARING)) {
174 convLastMsg.setVisibility(View.GONE);
175 imagePreview.setVisibility(View.VISIBLE);
176 loadBitmap(latestMessage, imagePreview);
177 } else {
178 convLastMsg.setVisibility(View.VISIBLE);
179 imagePreview.setVisibility(View.GONE);
180 if (latestMessage.getStatus() == Message.STATUS_PREPARING) {
181 convLastMsg.setText(getText(R.string.preparing_image));
182 } else if (latestMessage.getStatus() == Message.STATUS_RECEIVED_OFFER) {
183 convLastMsg.setText(getText(R.string.image_offered_for_download));
184 } else if (latestMessage.getStatus() == Message.STATUS_RECIEVING) {
185 convLastMsg.setText(getText(R.string.receiving_image));
186 } else {
187 convLastMsg.setText("");
188 }
189 }
190 }
191
192
193
194 if (!conv.isRead()) {
195 convName.setTypeface(null, Typeface.BOLD);
196 convLastMsg.setTypeface(null, Typeface.BOLD);
197 } else {
198 convName.setTypeface(null, Typeface.NORMAL);
199 convLastMsg.setTypeface(null, Typeface.NORMAL);
200 }
201
202 ((TextView) view.findViewById(R.id.conversation_lastupdate))
203 .setText(UIHelper.readableTimeDifference(conv
204 .getLatestMessage().getTimeSent()));
205
206 ImageView profilePicture = (ImageView) view
207 .findViewById(R.id.conversation_image);
208 profilePicture.setImageBitmap(UIHelper.getContactPicture(
209 conv, 56, activity.getApplicationContext(), false));
210
211 return view;
212 }
213
214 };
215
216 listView.setAdapter(this.listAdapter);
217
218 listView.setOnItemClickListener(new OnItemClickListener() {
219
220 @Override
221 public void onItemClick(AdapterView<?> arg0, View clickedView,
222 int position, long arg3) {
223 paneShouldBeOpen = false;
224 if (selectedConversation != conversationList.get(position)) {
225 selectedConversation = conversationList.get(position);
226 swapConversationFragment(); // .onBackendConnected(conversationList.get(position));
227 } else {
228 spl.closePane();
229 }
230 }
231 });
232 spl = (SlidingPaneLayout) findViewById(R.id.slidingpanelayout);
233 spl.setParallaxDistance(150);
234 spl.setShadowResource(R.drawable.es_slidingpane_shadow);
235 spl.setSliderFadeColor(0);
236 spl.setPanelSlideListener(new PanelSlideListener() {
237
238 @Override
239 public void onPanelOpened(View arg0) {
240 paneShouldBeOpen = true;
241 getActionBar().setDisplayHomeAsUpEnabled(false);
242 getActionBar().setTitle(R.string.app_name);
243 invalidateOptionsMenu();
244 hideKeyboard();
245 }
246
247 @Override
248 public void onPanelClosed(View arg0) {
249 paneShouldBeOpen = false;
250 if ((conversationList.size() > 0)
251 && (getSelectedConversation() != null)) {
252 getActionBar().setDisplayHomeAsUpEnabled(true);
253 getActionBar().setTitle(
254 getSelectedConversation().getName(useSubject));
255 invalidateOptionsMenu();
256 if (!getSelectedConversation().isRead()) {
257 getSelectedConversation().markRead();
258 UIHelper.updateNotification(getApplicationContext(),
259 getConversationList(), null, false);
260 listView.invalidateViews();
261 }
262 }
263 }
264
265 @Override
266 public void onPanelSlide(View arg0, float arg1) {
267 // TODO Auto-generated method stub
268
269 }
270 });
271 }
272
273 @Override
274 public boolean onCreateOptionsMenu(Menu menu) {
275 getMenuInflater().inflate(R.menu.conversations, menu);
276 MenuItem menuSecure = (MenuItem) menu.findItem(R.id.action_security);
277 MenuItem menuArchive = (MenuItem) menu.findItem(R.id.action_archive);
278 MenuItem menuMucDetails = (MenuItem) menu
279 .findItem(R.id.action_muc_details);
280 MenuItem menuContactDetails = (MenuItem) menu
281 .findItem(R.id.action_contact_details);
282 MenuItem menuInviteContacts = (MenuItem) menu
283 .findItem(R.id.action_invite);
284 MenuItem menuAttach = (MenuItem) menu.findItem(R.id.action_attach_file);
285 MenuItem menuClearHistory = (MenuItem) menu.findItem(R.id.action_clear_history);
286
287 if ((spl.isOpen() && (spl.isSlideable()))) {
288 menuArchive.setVisible(false);
289 menuMucDetails.setVisible(false);
290 menuContactDetails.setVisible(false);
291 menuSecure.setVisible(false);
292 menuInviteContacts.setVisible(false);
293 menuAttach.setVisible(false);
294 menuClearHistory.setVisible(false);
295 } else {
296 ((MenuItem) menu.findItem(R.id.action_add)).setVisible(!spl
297 .isSlideable());
298 if (this.getSelectedConversation() != null) {
299 if (this.getSelectedConversation().getMode() == Conversation.MODE_MULTI) {
300 menuContactDetails.setVisible(false);
301 menuSecure.setVisible(false);
302 menuAttach.setVisible(false);
303 } else {
304 menuMucDetails.setVisible(false);
305 menuInviteContacts.setVisible(false);
306 if (this.getSelectedConversation().getLatestMessage()
307 .getEncryption() != Message.ENCRYPTION_NONE) {
308 menuSecure.setIcon(R.drawable.ic_action_secure);
309 }
310 }
311 }
312 }
313 return true;
314 }
315
316 @Override
317 public boolean onOptionsItemSelected(MenuItem item) {
318 switch (item.getItemId()) {
319 case android.R.id.home:
320 spl.openPane();
321 break;
322 case R.id.action_attach_file:
323 selectPresence(getSelectedConversation(), new OnPresenceSelected() {
324
325 @Override
326 public void onPresenceSelected(boolean success, String presence) {
327 if (success) {
328 Intent attachFileIntent = new Intent();
329 attachFileIntent.setType("image/*");
330 attachFileIntent.setAction(Intent.ACTION_GET_CONTENT);
331 Intent chooser = Intent.createChooser(attachFileIntent, getString(R.string.attach_file));
332 startActivityForResult(chooser, ATTACH_FILE);
333 }
334 }
335 });
336 break;
337 case R.id.action_add:
338 startActivity(new Intent(this, ContactsActivity.class));
339 break;
340 case R.id.action_archive:
341 this.endConversation(getSelectedConversation());
342 break;
343 case R.id.action_contact_details:
344 Contact contact = this.getSelectedConversation().getContact();
345 if (contact != null) {
346 Intent intent = new Intent(this, ContactDetailsActivity.class);
347 intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
348 intent.putExtra("uuid", contact.getUuid());
349 startActivity(intent);
350 } else {
351 showAddToRosterDialog(getSelectedConversation());
352 }
353 break;
354 case R.id.action_muc_details:
355 Intent intent = new Intent(this, MucDetailsActivity.class);
356 intent.setAction(MucDetailsActivity.ACTION_VIEW_MUC);
357 intent.putExtra("uuid", getSelectedConversation().getUuid());
358 startActivity(intent);
359 break;
360 case R.id.action_invite:
361 Intent inviteIntent = new Intent(getApplicationContext(),
362 ContactsActivity.class);
363 inviteIntent.setAction("invite");
364 inviteIntent.putExtra("uuid", selectedConversation.getUuid());
365 startActivity(inviteIntent);
366 break;
367 case R.id.action_security:
368 final Conversation selConv = getSelectedConversation();
369 View menuItemView = findViewById(R.id.action_security);
370 PopupMenu popup = new PopupMenu(this, menuItemView);
371 final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
372 .findFragmentByTag("conversation");
373 if (fragment != null) {
374 popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
375
376 @Override
377 public boolean onMenuItemClick(MenuItem item) {
378 switch (item.getItemId()) {
379 case R.id.encryption_choice_none:
380 selConv.nextMessageEncryption = Message.ENCRYPTION_NONE;
381 item.setChecked(true);
382 break;
383 case R.id.encryption_choice_otr:
384 selConv.nextMessageEncryption = Message.ENCRYPTION_OTR;
385 item.setChecked(true);
386 break;
387 case R.id.encryption_choice_pgp:
388 selConv.nextMessageEncryption = Message.ENCRYPTION_PGP;
389 item.setChecked(true);
390 break;
391 default:
392 selConv.nextMessageEncryption = Message.ENCRYPTION_NONE;
393 break;
394 }
395 fragment.updateChatMsgHint();
396 return true;
397 }
398 });
399 popup.inflate(R.menu.encryption_choices);
400 switch (selConv.nextMessageEncryption) {
401 case Message.ENCRYPTION_NONE:
402 popup.getMenu().findItem(R.id.encryption_choice_none)
403 .setChecked(true);
404 break;
405 case Message.ENCRYPTION_OTR:
406 popup.getMenu().findItem(R.id.encryption_choice_otr)
407 .setChecked(true);
408 break;
409 case Message.ENCRYPTION_PGP:
410 popup.getMenu().findItem(R.id.encryption_choice_pgp)
411 .setChecked(true);
412 break;
413 case Message.ENCRYPTION_DECRYPTED:
414 popup.getMenu().findItem(R.id.encryption_choice_pgp)
415 .setChecked(true);
416 break;
417 default:
418 popup.getMenu().findItem(R.id.encryption_choice_none)
419 .setChecked(true);
420 break;
421 }
422 popup.show();
423 }
424
425 break;
426 case R.id.action_clear_history:
427 clearHistoryDialog(getSelectedConversation());
428 break;
429 default:
430 break;
431 }
432 return super.onOptionsItemSelected(item);
433 }
434
435 private void endConversation(Conversation conversation) {
436 conversation.setStatus(Conversation.STATUS_ARCHIVED);
437 paneShouldBeOpen = true;
438 spl.openPane();
439 xmppConnectionService.archiveConversation(conversation);
440 if (conversationList.size() > 0) {
441 selectedConversation = conversationList.get(0);
442 } else {
443 selectedConversation = null;
444 }
445 }
446
447 protected void clearHistoryDialog(final Conversation conversation) {
448 AlertDialog.Builder builder = new AlertDialog.Builder(this);
449 builder.setTitle(getString(R.string.clear_conversation_history));
450 View dialogView = getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
451 final CheckBox endConversationCheckBox = (CheckBox) dialogView.findViewById(R.id.end_conversation_checkbox);
452 builder.setView(dialogView);
453 builder.setNegativeButton(getString(R.string.cancel), null);
454 builder.setPositiveButton(getString(R.string.delete_messages), new OnClickListener() {
455
456 @Override
457 public void onClick(DialogInterface dialog, int which) {
458 activity.xmppConnectionService.clearConversationHistory(conversation);
459 if (endConversationCheckBox.isChecked()) {
460 endConversation(conversation);
461 }
462 }
463 });
464 builder.create().show();
465 }
466
467 protected ConversationFragment swapConversationFragment() {
468 ConversationFragment selectedFragment = new ConversationFragment();
469
470 FragmentTransaction transaction = getFragmentManager()
471 .beginTransaction();
472 transaction.replace(R.id.selected_conversation, selectedFragment,
473 "conversation");
474 transaction.commit();
475 return selectedFragment;
476 }
477
478 @Override
479 public boolean onKeyDown(int keyCode, KeyEvent event) {
480 if (keyCode == KeyEvent.KEYCODE_BACK) {
481 if (!spl.isOpen()) {
482 spl.openPane();
483 return false;
484 }
485 }
486 return super.onKeyDown(keyCode, event);
487 }
488
489 @Override
490 public void onStart() {
491 super.onStart();
492 SharedPreferences preferences = PreferenceManager
493 .getDefaultSharedPreferences(this);
494 this.useSubject = preferences.getBoolean("use_subject_in_muc", true);
495 if (this.xmppConnectionServiceBound) {
496 this.onBackendConnected();
497 }
498 if (conversationList.size() >= 1) {
499 onConvChanged.onConversationListChanged();
500 }
501 }
502
503 @Override
504 protected void onStop() {
505 if (xmppConnectionServiceBound) {
506 xmppConnectionService.removeOnConversationListChangedListener();
507 }
508 super.onStop();
509 }
510
511 @Override
512 void onBackendConnected() {
513 this.registerListener();
514 if (conversationList.size() == 0) {
515 updateConversationList();
516 }
517
518 if ((getIntent().getAction() != null)
519 && (getIntent().getAction().equals(Intent.ACTION_VIEW) && (!handledViewIntent))) {
520 if (getIntent().getType().equals(
521 ConversationActivity.VIEW_CONVERSATION)) {
522 handledViewIntent = true;
523
524 String convToView = (String) getIntent().getExtras().get(
525 CONVERSATION);
526
527 for (int i = 0; i < conversationList.size(); ++i) {
528 if (conversationList.get(i).getUuid().equals(convToView)) {
529 selectedConversation = conversationList.get(i);
530 }
531 }
532 paneShouldBeOpen = false;
533 String text = getIntent().getExtras().getString(TEXT, null);
534 swapConversationFragment().setText(text);
535 }
536 } else {
537 if (xmppConnectionService.getAccounts().size() == 0) {
538 startActivity(new Intent(this, ManageAccountActivity.class));
539 finish();
540 } else if (conversationList.size() <= 0) {
541 // add no history
542 startActivity(new Intent(this, ContactsActivity.class));
543 finish();
544 } else {
545 spl.openPane();
546 // find currently loaded fragment
547 ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
548 .findFragmentByTag("conversation");
549 if (selectedFragment != null) {
550 selectedFragment.onBackendConnected();
551 } else {
552 selectedConversation = conversationList.get(0);
553 swapConversationFragment();
554 }
555 ExceptionHelper.checkForCrash(this, this.xmppConnectionService);
556 }
557 }
558 }
559
560 public void registerListener() {
561 if (xmppConnectionServiceBound) {
562 xmppConnectionService
563 .setOnConversationListChangedListener(this.onConvChanged);
564 }
565 }
566
567 @Override
568 protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
569 super.onActivityResult(requestCode, resultCode, data);
570 if (resultCode == RESULT_OK) {
571 if (requestCode == REQUEST_DECRYPT_PGP) {
572 ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
573 .findFragmentByTag("conversation");
574 if (selectedFragment != null) {
575 selectedFragment.hidePgpPassphraseBox();
576 }
577 } else if (requestCode == ATTACH_FILE) {
578 Conversation conversation = getSelectedConversation();
579 String presence = conversation.getNextPresence();
580 xmppConnectionService.attachImageToConversation(conversation, presence, data.getData());
581
582 }
583 }
584 }
585
586 public void updateConversationList() {
587 conversationList.clear();
588 conversationList.addAll(xmppConnectionService.getConversations());
589 listView.invalidateViews();
590 }
591
592 public void selectPresence(final Conversation conversation, final OnPresenceSelected listener) {
593 Contact contact = conversation.getContact();
594 if (contact==null) {
595 showAddToRosterDialog(conversation);
596 listener.onPresenceSelected(false,null);
597 } else {
598 Hashtable<String, Integer> presences = contact.getPresences();
599 if (presences.size() == 0) {
600 listener.onPresenceSelected(false, null);
601 } else if (presences.size() == 1) {
602 String presence = (String) presences.keySet().toArray()[0];
603 conversation.setNextPresence(presence);
604 listener.onPresenceSelected(true, presence);
605 } else {
606 AlertDialog.Builder builder = new AlertDialog.Builder(this);
607 builder.setTitle(getString(R.string.choose_presence));
608 final String[] presencesArray = new String[presences.size()];
609 presences.keySet().toArray(presencesArray);
610 builder.setItems(presencesArray,
611 new DialogInterface.OnClickListener() {
612
613 @Override
614 public void onClick(DialogInterface dialog,
615 int which) {
616 String presence = presencesArray[which];
617 conversation.setNextPresence(presence);
618 listener.onPresenceSelected(true,presence);
619 }
620 });
621 builder.create().show();
622 }
623 }
624 }
625
626 private void showAddToRosterDialog(final Conversation conversation) {
627 String jid = conversation.getContactJid();
628 AlertDialog.Builder builder = new AlertDialog.Builder(this);
629 builder.setTitle(jid);
630 builder.setMessage(getString(R.string.not_in_roster));
631 builder.setNegativeButton(getString(R.string.cancel), null);
632 builder.setPositiveButton(getString(R.string.add_contact), new DialogInterface.OnClickListener() {
633
634 @Override
635 public void onClick(DialogInterface dialog, int which) {
636 String jid = conversation.getContactJid();
637 Account account = getSelectedConversation().getAccount();
638 String name = jid.split("@")[0];
639 Contact contact = new Contact(account, name, jid, null);
640 xmppConnectionService.createContact(contact);
641 }
642 });
643 builder.create().show();
644 }
645
646
647 class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
648 private final WeakReference<ImageView> imageViewReference;
649 private Message message = null;
650
651 public BitmapWorkerTask(ImageView imageView) {
652 // Use a WeakReference to ensure the ImageView can be garbage collected
653 imageViewReference = new WeakReference<ImageView>(imageView);
654 }
655
656 // Decode image in background.
657 @Override
658 protected Bitmap doInBackground(Message... params) {
659 message = params[0];
660 try {
661 return xmppConnectionService.getFileBackend().getThumbnail(message, (int) (metrics.density * 288));
662 } catch (FileNotFoundException e) {
663 Log.d("xmppService","file not found!");
664 return null;
665 }
666 }
667
668 // Once complete, see if ImageView is still around and set bitmap.
669 @Override
670 protected void onPostExecute(Bitmap bitmap) {
671 if (imageViewReference != null && bitmap != null) {
672 final ImageView imageView = imageViewReference.get();
673 if (imageView != null) {
674 imageView.setImageBitmap(bitmap);
675 }
676 }
677 }
678 }
679
680 public void loadBitmap(Message message, ImageView imageView) {
681 if (cancelPotentialWork(message, imageView)) {
682 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
683 final AsyncDrawable asyncDrawable =
684 new AsyncDrawable(getResources(), null, task);
685 imageView.setImageDrawable(asyncDrawable);
686 task.execute(message);
687 }
688 }
689
690 public static boolean cancelPotentialWork(Message message, ImageView imageView) {
691 final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
692
693 if (bitmapWorkerTask != null) {
694 final Message oldMessage = bitmapWorkerTask.message;
695 // If bitmapData is not yet set or it differs from the new data
696 if (oldMessage == null || message != oldMessage) {
697 // Cancel previous task
698 bitmapWorkerTask.cancel(true);
699 } else {
700 // The same work is already in progress
701 return false;
702 }
703 }
704 // No task associated with the ImageView, or an existing task was cancelled
705 return true;
706 }
707
708 private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
709 if (imageView != null) {
710 final Drawable drawable = imageView.getDrawable();
711 if (drawable instanceof AsyncDrawable) {
712 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
713 return asyncDrawable.getBitmapWorkerTask();
714 }
715 }
716 return null;
717 }
718
719 static class AsyncDrawable extends BitmapDrawable {
720 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
721
722 public AsyncDrawable(Resources res, Bitmap bitmap,
723 BitmapWorkerTask bitmapWorkerTask) {
724 super(res, bitmap);
725 bitmapWorkerTaskReference =
726 new WeakReference<BitmapWorkerTask>(bitmapWorkerTask);
727 }
728
729 public BitmapWorkerTask getBitmapWorkerTask() {
730 return bitmapWorkerTaskReference.get();
731 }
732 }
733}