XmppActivity.java

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