1package eu.siacs.conversations.ui;
2
3import android.annotation.SuppressLint;
4import android.app.Activity;
5import android.app.AlertDialog;
6import android.app.AlertDialog.Builder;
7import android.app.PendingIntent;
8import android.content.ClipData;
9import android.content.ClipboardManager;
10import android.content.ComponentName;
11import android.content.Context;
12import android.content.DialogInterface;
13import android.content.DialogInterface.OnClickListener;
14import android.content.Intent;
15import android.content.IntentSender.SendIntentException;
16import android.content.ServiceConnection;
17import android.content.SharedPreferences;
18import android.content.pm.PackageManager;
19import android.content.pm.ResolveInfo;
20import android.content.res.Resources;
21import android.graphics.Bitmap;
22import android.graphics.Color;
23import android.graphics.Point;
24import android.graphics.drawable.BitmapDrawable;
25import android.graphics.drawable.Drawable;
26import android.net.Uri;
27import android.nfc.NdefMessage;
28import android.nfc.NdefRecord;
29import android.nfc.NfcAdapter;
30import android.nfc.NfcEvent;
31import android.os.AsyncTask;
32import android.os.Bundle;
33import android.os.IBinder;
34import android.preference.PreferenceManager;
35import android.text.InputType;
36import android.util.DisplayMetrics;
37import android.util.Log;
38import android.view.MenuItem;
39import android.view.View;
40import android.view.inputmethod.InputMethodManager;
41import android.widget.EditText;
42import android.widget.ImageView;
43
44import com.google.zxing.BarcodeFormat;
45import com.google.zxing.EncodeHintType;
46import com.google.zxing.WriterException;
47import com.google.zxing.common.BitMatrix;
48import com.google.zxing.qrcode.QRCodeWriter;
49import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
50
51import java.io.FileNotFoundException;
52import java.lang.ref.WeakReference;
53import java.util.Hashtable;
54import java.util.List;
55import java.util.concurrent.RejectedExecutionException;
56
57import eu.siacs.conversations.Config;
58import eu.siacs.conversations.R;
59import eu.siacs.conversations.entities.Account;
60import eu.siacs.conversations.entities.Contact;
61import eu.siacs.conversations.entities.Conversation;
62import eu.siacs.conversations.entities.Message;
63import eu.siacs.conversations.entities.Presences;
64import eu.siacs.conversations.services.AvatarService;
65import eu.siacs.conversations.services.XmppConnectionService;
66import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
67import eu.siacs.conversations.utils.ExceptionHelper;
68import eu.siacs.conversations.xmpp.jid.InvalidJidException;
69import eu.siacs.conversations.xmpp.jid.Jid;
70
71public abstract class XmppActivity extends Activity {
72
73 protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
74 protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
75
76 public XmppConnectionService xmppConnectionService;
77 public boolean xmppConnectionServiceBound = false;
78
79 protected int mPrimaryTextColor;
80 protected int mSecondaryTextColor;
81 protected int mSecondaryBackgroundColor;
82 protected int mColorRed;
83 protected int mColorOrange;
84 protected int mColorGreen;
85 protected int mPrimaryColor;
86
87 protected boolean mUseSubject = true;
88
89 private DisplayMetrics metrics;
90
91 protected interface OnValueEdited {
92 public void onValueEdited(String value);
93 }
94
95 public interface OnPresenceSelected {
96 public void onPresenceSelected();
97 }
98
99 protected ServiceConnection mConnection = new ServiceConnection() {
100
101 @Override
102 public void onServiceConnected(ComponentName className, IBinder service) {
103 XmppConnectionBinder binder = (XmppConnectionBinder) service;
104 xmppConnectionService = binder.getService();
105 xmppConnectionServiceBound = true;
106 onBackendConnected();
107 }
108
109 @Override
110 public void onServiceDisconnected(ComponentName arg0) {
111 xmppConnectionServiceBound = false;
112 }
113 };
114
115 @Override
116 protected void onStart() {
117 super.onStart();
118 if (!xmppConnectionServiceBound) {
119 connectToBackend();
120 }
121 }
122
123 public void connectToBackend() {
124 Intent intent = new Intent(this, XmppConnectionService.class);
125 intent.setAction("ui");
126 startService(intent);
127 bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
128 }
129
130 @Override
131 protected void onStop() {
132 super.onStop();
133 if (xmppConnectionServiceBound) {
134 unbindService(mConnection);
135 xmppConnectionServiceBound = false;
136 }
137 }
138
139 protected void hideKeyboard() {
140 InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
141
142 View focus = getCurrentFocus();
143
144 if (focus != null) {
145
146 inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
147 InputMethodManager.HIDE_NOT_ALWAYS);
148 }
149 }
150
151 public boolean hasPgp() {
152 return xmppConnectionService.getPgpEngine() != null;
153 }
154
155 public void showInstallPgpDialog() {
156 Builder builder = new AlertDialog.Builder(this);
157 builder.setTitle(getString(R.string.openkeychain_required));
158 builder.setIconAttribute(android.R.attr.alertDialogIcon);
159 builder.setMessage(getText(R.string.openkeychain_required_long));
160 builder.setNegativeButton(getString(R.string.cancel), null);
161 builder.setNeutralButton(getString(R.string.restart),
162 new OnClickListener() {
163
164 @Override
165 public void onClick(DialogInterface dialog, int which) {
166 if (xmppConnectionServiceBound) {
167 unbindService(mConnection);
168 xmppConnectionServiceBound = false;
169 }
170 stopService(new Intent(XmppActivity.this,
171 XmppConnectionService.class));
172 finish();
173 }
174 });
175 builder.setPositiveButton(getString(R.string.install),
176 new OnClickListener() {
177
178 @Override
179 public void onClick(DialogInterface dialog, int which) {
180 Uri uri = Uri
181 .parse("market://details?id=org.sufficientlysecure.keychain");
182 Intent marketIntent = new Intent(Intent.ACTION_VIEW,
183 uri);
184 PackageManager manager = getApplicationContext()
185 .getPackageManager();
186 List<ResolveInfo> infos = manager
187 .queryIntentActivities(marketIntent, 0);
188 if (infos.size() > 0) {
189 startActivity(marketIntent);
190 } else {
191 uri = Uri.parse("http://www.openkeychain.org/");
192 Intent browserIntent = new Intent(
193 Intent.ACTION_VIEW, uri);
194 startActivity(browserIntent);
195 }
196 finish();
197 }
198 });
199 builder.create().show();
200 }
201
202 abstract void onBackendConnected();
203
204 public boolean onOptionsItemSelected(MenuItem item) {
205 switch (item.getItemId()) {
206 case R.id.action_settings:
207 startActivity(new Intent(this, SettingsActivity.class));
208 break;
209 case R.id.action_accounts:
210 startActivity(new Intent(this, ManageAccountActivity.class));
211 break;
212 case android.R.id.home:
213 finish();
214 break;
215 case R.id.action_show_qr_code:
216 showQrCode();
217 break;
218 }
219 return super.onOptionsItemSelected(item);
220 }
221
222 @Override
223 protected void onCreate(Bundle savedInstanceState) {
224 super.onCreate(savedInstanceState);
225 metrics = getResources().getDisplayMetrics();
226 ExceptionHelper.init(getApplicationContext());
227 mPrimaryTextColor = getResources().getColor(R.color.primarytext);
228 mSecondaryTextColor = getResources().getColor(R.color.secondarytext);
229 mColorRed = getResources().getColor(R.color.red);
230 mColorOrange = getResources().getColor(R.color.orange);
231 mColorGreen = getResources().getColor(R.color.green);
232 mPrimaryColor = getResources().getColor(R.color.primary);
233 mSecondaryBackgroundColor = getResources().getColor(
234 R.color.secondarybackground);
235 if (getPreferences().getBoolean("use_larger_font", false)) {
236 setTheme(R.style.ConversationsTheme_LargerText);
237 }
238 mUseSubject = getPreferences().getBoolean("use_subject", true);
239 }
240
241 protected SharedPreferences getPreferences() {
242 return PreferenceManager
243 .getDefaultSharedPreferences(getApplicationContext());
244 }
245
246 public boolean useSubjectToIdentifyConference() {
247 return mUseSubject;
248 }
249
250 public void switchToConversation(Conversation conversation) {
251 switchToConversation(conversation, null, false);
252 }
253
254 public void switchToConversation(Conversation conversation, String text,
255 boolean newTask) {
256 Intent viewConversationIntent = new Intent(this,
257 ConversationActivity.class);
258 viewConversationIntent.setAction(Intent.ACTION_VIEW);
259 viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
260 conversation.getUuid());
261 if (text != null) {
262 viewConversationIntent.putExtra(ConversationActivity.TEXT, text);
263 }
264 viewConversationIntent.setType(ConversationActivity.VIEW_CONVERSATION);
265 if (newTask) {
266 viewConversationIntent.setFlags(viewConversationIntent.getFlags()
267 | Intent.FLAG_ACTIVITY_NEW_TASK
268 | Intent.FLAG_ACTIVITY_SINGLE_TOP);
269 } else {
270 viewConversationIntent.setFlags(viewConversationIntent.getFlags()
271 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
272 }
273 startActivity(viewConversationIntent);
274 finish();
275 }
276
277 public void switchToContactDetails(Contact contact) {
278 Intent intent = new Intent(this, ContactDetailsActivity.class);
279 intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
280 intent.putExtra("account", contact.getAccount().getJid().toBareJid().toString());
281 intent.putExtra("contact", contact.getJid().toString());
282 startActivity(intent);
283 }
284
285 public void switchToAccount(Account account) {
286 Intent intent = new Intent(this, EditAccountActivity.class);
287 intent.putExtra("jid", account.getJid().toBareJid().toString());
288 startActivity(intent);
289 }
290
291 protected void inviteToConversation(Conversation conversation) {
292 Intent intent = new Intent(getApplicationContext(),
293 ChooseContactActivity.class);
294 intent.putExtra("conversation", conversation.getUuid());
295 startActivityForResult(intent, REQUEST_INVITE_TO_CONVERSATION);
296 }
297
298 protected void announcePgp(Account account, final Conversation conversation) {
299 xmppConnectionService.getPgpEngine().generateSignature(account,
300 "online", new UiCallback<Account>() {
301
302 @Override
303 public void userInputRequried(PendingIntent pi,
304 Account account) {
305 try {
306 startIntentSenderForResult(pi.getIntentSender(),
307 REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
308 } catch (final SendIntentException ignored) {
309 }
310 }
311
312 @Override
313 public void success(Account account) {
314 xmppConnectionService.databaseBackend
315 .updateAccount(account);
316 xmppConnectionService.sendPresencePacket(account,
317 xmppConnectionService.getPresenceGenerator()
318 .sendPresence(account));
319 if (conversation != null) {
320 conversation
321 .setNextEncryption(Message.ENCRYPTION_PGP);
322 xmppConnectionService.databaseBackend
323 .updateConversation(conversation);
324 }
325 }
326
327 @Override
328 public void error(int error, Account account) {
329 displayErrorDialog(error);
330 }
331 });
332 }
333
334 protected void displayErrorDialog(final int errorCode) {
335 runOnUiThread(new Runnable() {
336
337 @Override
338 public void run() {
339 AlertDialog.Builder builder = new AlertDialog.Builder(
340 XmppActivity.this);
341 builder.setIconAttribute(android.R.attr.alertDialogIcon);
342 builder.setTitle(getString(R.string.error));
343 builder.setMessage(errorCode);
344 builder.setNeutralButton(R.string.accept, null);
345 builder.create().show();
346 }
347 });
348
349 }
350
351 protected void showAddToRosterDialog(final Conversation conversation) {
352 final Jid jid = conversation.getContactJid();
353 AlertDialog.Builder builder = new AlertDialog.Builder(this);
354 builder.setTitle(jid.toString());
355 builder.setMessage(getString(R.string.not_in_roster));
356 builder.setNegativeButton(getString(R.string.cancel), null);
357 builder.setPositiveButton(getString(R.string.add_contact),
358 new DialogInterface.OnClickListener() {
359
360 @Override
361 public void onClick(DialogInterface dialog, int which) {
362 final Jid jid = conversation.getContactJid();
363 Account account = conversation.getAccount();
364 Contact contact = account.getRoster().getContact(jid);
365 xmppConnectionService.createContact(contact);
366 switchToContactDetails(contact);
367 }
368 });
369 builder.create().show();
370 }
371
372 private void showAskForPresenceDialog(final Contact contact) {
373 AlertDialog.Builder builder = new AlertDialog.Builder(this);
374 builder.setTitle(contact.getJid().toString());
375 builder.setMessage(R.string.request_presence_updates);
376 builder.setNegativeButton(R.string.cancel, null);
377 builder.setPositiveButton(R.string.request_now,
378 new DialogInterface.OnClickListener() {
379
380 @Override
381 public void onClick(DialogInterface dialog, int which) {
382 if (xmppConnectionServiceBound) {
383 xmppConnectionService.sendPresencePacket(contact
384 .getAccount(), xmppConnectionService
385 .getPresenceGenerator()
386 .requestPresenceUpdatesFrom(contact));
387 }
388 }
389 });
390 builder.create().show();
391 }
392
393 private void warnMutalPresenceSubscription(final Conversation conversation,
394 final OnPresenceSelected listener) {
395 AlertDialog.Builder builder = new AlertDialog.Builder(this);
396 builder.setTitle(conversation.getContact().getJid().toString());
397 builder.setMessage(R.string.without_mutual_presence_updates);
398 builder.setNegativeButton(R.string.cancel, null);
399 builder.setPositiveButton(R.string.ignore, new OnClickListener() {
400
401 @Override
402 public void onClick(DialogInterface dialog, int which) {
403 conversation.setNextCounterpart(null);
404 if (listener != null) {
405 listener.onPresenceSelected();
406 }
407 }
408 });
409 builder.create().show();
410 }
411
412 protected void quickEdit(String previousValue, OnValueEdited callback) {
413 quickEdit(previousValue, callback, false);
414 }
415
416 protected void quickPasswordEdit(String previousValue,
417 OnValueEdited callback) {
418 quickEdit(previousValue, callback, true);
419 }
420
421 @SuppressLint("InflateParams")
422 private void quickEdit(final String previousValue,
423 final OnValueEdited callback, boolean password) {
424 AlertDialog.Builder builder = new AlertDialog.Builder(this);
425 View view = getLayoutInflater().inflate(R.layout.quickedit, null);
426 final EditText editor = (EditText) view.findViewById(R.id.editor);
427 OnClickListener mClickListener = new OnClickListener() {
428
429 @Override
430 public void onClick(DialogInterface dialog, int which) {
431 String value = editor.getText().toString();
432 if (!previousValue.equals(value) && value.trim().length() > 0) {
433 callback.onValueEdited(value);
434 }
435 }
436 };
437 if (password) {
438 editor.setInputType(InputType.TYPE_CLASS_TEXT
439 | InputType.TYPE_TEXT_VARIATION_PASSWORD);
440 editor.setHint(R.string.password);
441 builder.setPositiveButton(R.string.accept, mClickListener);
442 } else {
443 builder.setPositiveButton(R.string.edit, mClickListener);
444 }
445 editor.requestFocus();
446 editor.setText(previousValue);
447 builder.setView(view);
448 builder.setNegativeButton(R.string.cancel, null);
449 builder.create().show();
450 }
451
452 public void selectPresence(final Conversation conversation,
453 final OnPresenceSelected listener) {
454 final Contact contact = conversation.getContact();
455 if (!contact.showInRoster()) {
456 showAddToRosterDialog(conversation);
457 } else {
458 Presences presences = contact.getPresences();
459 if (presences.size() == 0) {
460 if (!contact.getOption(Contact.Options.TO)
461 && !contact.getOption(Contact.Options.ASKING)
462 && contact.getAccount().getStatus() == Account.STATUS_ONLINE) {
463 showAskForPresenceDialog(contact);
464 } else if (!contact.getOption(Contact.Options.TO)
465 || !contact.getOption(Contact.Options.FROM)) {
466 warnMutalPresenceSubscription(conversation, listener);
467 } else {
468 conversation.setNextCounterpart(null);
469 listener.onPresenceSelected();
470 }
471 } else if (presences.size() == 1) {
472 String presence = presences.asStringArray()[0];
473 try {
474 conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),presence));
475 } catch (InvalidJidException e) {
476 conversation.setNextCounterpart(null);
477 }
478 listener.onPresenceSelected();
479 } else {
480 final StringBuilder presence = new StringBuilder();
481 AlertDialog.Builder builder = new AlertDialog.Builder(this);
482 builder.setTitle(getString(R.string.choose_presence));
483 final String[] presencesArray = presences.asStringArray();
484 int preselectedPresence = 0;
485 for (int i = 0; i < presencesArray.length; ++i) {
486 if (presencesArray[i].equals(contact.lastseen.presence)) {
487 preselectedPresence = i;
488 break;
489 }
490 }
491 presence.append(presencesArray[preselectedPresence]);
492 builder.setSingleChoiceItems(presencesArray,
493 preselectedPresence,
494 new DialogInterface.OnClickListener() {
495
496 @Override
497 public void onClick(DialogInterface dialog,
498 int which) {
499 presence.delete(0, presence.length());
500 presence.append(presencesArray[which]);
501 }
502 });
503 builder.setNegativeButton(R.string.cancel, null);
504 builder.setPositiveButton(R.string.ok, new OnClickListener() {
505
506 @Override
507 public void onClick(DialogInterface dialog, int which) {
508 try {
509 conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),presence.toString()));
510 } catch (InvalidJidException e) {
511 conversation.setNextCounterpart(null);
512 }
513 listener.onPresenceSelected();
514 }
515 });
516 builder.create().show();
517 }
518 }
519 }
520
521 protected void onActivityResult(int requestCode, int resultCode,
522 final Intent data) {
523 super.onActivityResult(requestCode, resultCode, data);
524 if (requestCode == REQUEST_INVITE_TO_CONVERSATION
525 && resultCode == RESULT_OK) {
526 String contactJid = data.getStringExtra("contact");
527 String conversationUuid = data.getStringExtra("conversation");
528 Conversation conversation = xmppConnectionService
529 .findConversationByUuid(conversationUuid);
530 if (conversation.getMode() == Conversation.MODE_MULTI) {
531 xmppConnectionService.invite(conversation, contactJid);
532 }
533 Log.d(Config.LOGTAG, "inviting " + contactJid + " to "
534 + conversation.getName());
535 }
536 }
537
538 public int getSecondaryTextColor() {
539 return this.mSecondaryTextColor;
540 }
541
542 public int getPrimaryTextColor() {
543 return this.mPrimaryTextColor;
544 }
545
546 public int getWarningTextColor() {
547 return this.mColorRed;
548 }
549
550 public int getPrimaryColor() {
551 return this.mPrimaryColor;
552 }
553
554 public int getSecondaryBackgroundColor() {
555 return this.mSecondaryBackgroundColor;
556 }
557
558 public int getPixel(int dp) {
559 DisplayMetrics metrics = getResources().getDisplayMetrics();
560 return ((int) (dp * metrics.density));
561 }
562
563 public boolean copyTextToClipboard(String text, int labelResId) {
564 ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
565 String label = getResources().getString(labelResId);
566 if (mClipBoardManager != null) {
567 ClipData mClipData = ClipData.newPlainText(label, text);
568 mClipBoardManager.setPrimaryClip(mClipData);
569 return true;
570 }
571 return false;
572 }
573
574 protected void registerNdefPushMessageCallback() {
575 NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
576 if (nfcAdapter != null && nfcAdapter.isEnabled()) {
577 nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
578 @Override
579 public NdefMessage createNdefMessage(NfcEvent nfcEvent) {
580 return new NdefMessage(new NdefRecord[]{
581 NdefRecord.createUri(getShareableUri()),
582 NdefRecord.createApplicationRecord("eu.siacs.conversations")
583 });
584 }
585 }, this);
586 }
587 }
588
589 protected void unregisterNdefPushMessageCallback() {
590 NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
591 if (nfcAdapter != null && nfcAdapter.isEnabled()) {
592 nfcAdapter.setNdefPushMessageCallback(null,this);
593 }
594 }
595
596 protected String getShareableUri() {
597 return null;
598 }
599
600 @Override
601 public void onResume() {
602 super.onResume();
603 if (this.getShareableUri()!=null) {
604 this.registerNdefPushMessageCallback();
605 }
606 }
607
608 @Override
609 public void onPause() {
610 super.onPause();
611 this.unregisterNdefPushMessageCallback();
612 }
613
614 protected void showQrCode() {
615 String uri = getShareableUri();
616 if (uri!=null) {
617 Point size = new Point();
618 getWindowManager().getDefaultDisplay().getSize(size);
619 final int width = (size.x < size.y ? size.x : size.y);
620 Bitmap bitmap = createQrCodeBitmap(uri, width);
621 ImageView view = new ImageView(this);
622 view.setImageBitmap(bitmap);
623 AlertDialog.Builder builder = new AlertDialog.Builder(this);
624 builder.setView(view);
625 builder.create().show();
626 }
627 }
628
629 protected Bitmap createQrCodeBitmap(String input, int size) {
630 try {
631 final QRCodeWriter QR_CODE_WRITER = new QRCodeWriter();
632 final Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
633 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
634 final BitMatrix result = QR_CODE_WRITER.encode(input, BarcodeFormat.QR_CODE, size, size, hints);
635 final int width = result.getWidth();
636 final int height = result.getHeight();
637 final int[] pixels = new int[width * height];
638 for (int y = 0; y < height; y++) {
639 final int offset = y * width;
640 for (int x = 0; x < width; x++) {
641 pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.TRANSPARENT;
642 }
643 }
644 final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
645 bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
646 return bitmap;
647 } catch (final WriterException e) {
648 return null;
649 }
650 }
651
652 public AvatarService avatarService() {
653 return xmppConnectionService.getAvatarService();
654 }
655
656 class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
657 private final WeakReference<ImageView> imageViewReference;
658 private Message message = null;
659
660 public BitmapWorkerTask(ImageView imageView) {
661 imageViewReference = new WeakReference<>(imageView);
662 }
663
664 @Override
665 protected Bitmap doInBackground(Message... params) {
666 message = params[0];
667 try {
668 return xmppConnectionService.getFileBackend().getThumbnail(
669 message, (int) (metrics.density * 288), false);
670 } catch (FileNotFoundException e) {
671 return null;
672 }
673 }
674
675 @Override
676 protected void onPostExecute(Bitmap bitmap) {
677 if (bitmap != null) {
678 final ImageView imageView = imageViewReference.get();
679 if (imageView != null) {
680 imageView.setImageBitmap(bitmap);
681 imageView.setBackgroundColor(0x00000000);
682 }
683 }
684 }
685 }
686
687 public void loadBitmap(Message message, ImageView imageView) {
688 Bitmap bm;
689 try {
690 bm = xmppConnectionService.getFileBackend().getThumbnail(message,
691 (int) (metrics.density * 288), true);
692 } catch (FileNotFoundException e) {
693 bm = null;
694 }
695 if (bm != null) {
696 imageView.setImageBitmap(bm);
697 imageView.setBackgroundColor(0x00000000);
698 } else {
699 if (cancelPotentialWork(message, imageView)) {
700 imageView.setBackgroundColor(0xff333333);
701 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
702 final AsyncDrawable asyncDrawable = new AsyncDrawable(
703 getResources(), null, task);
704 imageView.setImageDrawable(asyncDrawable);
705 try {
706 task.execute(message);
707 } catch (final RejectedExecutionException ignored) {
708 }
709 }
710 }
711 }
712
713 public static boolean cancelPotentialWork(Message message,
714 ImageView imageView) {
715 final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
716
717 if (bitmapWorkerTask != null) {
718 final Message oldMessage = bitmapWorkerTask.message;
719 if (oldMessage == null || message != oldMessage) {
720 bitmapWorkerTask.cancel(true);
721 } else {
722 return false;
723 }
724 }
725 return true;
726 }
727
728 private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
729 if (imageView != null) {
730 final Drawable drawable = imageView.getDrawable();
731 if (drawable instanceof AsyncDrawable) {
732 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
733 return asyncDrawable.getBitmapWorkerTask();
734 }
735 }
736 return null;
737 }
738
739 static class AsyncDrawable extends BitmapDrawable {
740 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
741
742 public AsyncDrawable(Resources res, Bitmap bitmap,
743 BitmapWorkerTask bitmapWorkerTask) {
744 super(res, bitmap);
745 bitmapWorkerTaskReference = new WeakReference<>(
746 bitmapWorkerTask);
747 }
748
749 public BitmapWorkerTask getBitmapWorkerTask() {
750 return bitmapWorkerTaskReference.get();
751 }
752 }
753}