From 328405419a469a310ed1254064f296b17675a798 Mon Sep 17 00:00:00 2001 From: cketti Date: Fri, 12 Dec 2014 04:40:49 +0100 Subject: [PATCH 1/2] Don't require Application when a Context instance will do --- .../fsck/k9/activity/UpgradeDatabases.java | 2 +- .../k9/controller/MessagingController.java | 126 ++++++++---------- .../MessagingControllerPushReceiver.java | 13 +- src/com/fsck/k9/helper/Utility.java | 7 +- .../k9/mailstore/LocalAttachmentBody.java | 10 +- .../mailstore/LocalAttachmentMessageBody.java | 6 +- src/com/fsck/k9/mailstore/LocalFolder.java | 18 +-- src/com/fsck/k9/mailstore/LocalStore.java | 20 +-- .../fsck/k9/mailstore/LockableDatabase.java | 15 +-- src/com/fsck/k9/mailstore/StorageManager.java | 35 +++-- .../k9/mailstore/StoreSchemaDefinition.java | 4 +- 11 files changed, 115 insertions(+), 141 deletions(-) diff --git a/src/com/fsck/k9/activity/UpgradeDatabases.java b/src/com/fsck/k9/activity/UpgradeDatabases.java index ae8cd6fd7..f8a697213 100644 --- a/src/com/fsck/k9/activity/UpgradeDatabases.java +++ b/src/com/fsck/k9/activity/UpgradeDatabases.java @@ -49,7 +49,7 @@ import android.widget.TextView; * Currently we make no attempts to stop the background code (e.g. {@link MessagingController}) from * opening the accounts' databases. If this happens the upgrade is performed in one of the * background threads and not by {@link DatabaseUpgradeService}. But this is not a problem. Due to - * the locking in {@link Store#getLocalInstance(Account, android.app.Application)} the upgrade + * the locking in {@link Store#getLocalInstance(Account, Context)} the upgrade * service will block in the {@link Account#getLocalStore()} call and from the outside (especially * for this activity) it will appear as if {@link DatabaseUpgradeService} is performing the upgrade. *

diff --git a/src/com/fsck/k9/controller/MessagingController.java b/src/com/fsck/k9/controller/MessagingController.java index 770742256..189a0681e 100644 --- a/src/com/fsck/k9/controller/MessagingController.java +++ b/src/com/fsck/k9/controller/MessagingController.java @@ -22,7 +22,6 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; -import android.app.Application; import android.app.KeyguardManager; import android.app.NotificationManager; import android.app.PendingIntent; @@ -195,10 +194,7 @@ public class MessagingController implements Runnable { private boolean mBusy; - /** - * {@link K9} - */ - private Application mApplication; + private Context context; /** * A holder class for pending notification data @@ -316,14 +312,12 @@ public class MessagingController implements Runnable { private static final Set SYNC_FLAGS = EnumSet.of(Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED, Flag.FORWARDED); private void suppressMessages(Account account, List messages) { - EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), - mApplication.getApplicationContext()); + EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), context); cache.hideMessages(messages); } private void unsuppressMessages(Account account, List messages) { - EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), - mApplication.getApplicationContext()); + EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), context); cache.unhideMessages(messages); } @@ -331,16 +325,14 @@ public class MessagingController implements Runnable { long messageId = message.getId(); long folderId = message.getFolder().getId(); - EmailProviderCache cache = EmailProviderCache.getCache(message.getFolder().getAccountUuid(), - mApplication.getApplicationContext()); + EmailProviderCache cache = EmailProviderCache.getCache(message.getFolder().getAccountUuid(), context); return cache.isMessageHidden(messageId, folderId); } private void setFlagInCache(final Account account, final List messageIds, final Flag flag, final boolean newState) { - EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), - mApplication.getApplicationContext()); + EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), context); String columnName = LocalStore.getColumnNameForFlag(flag); String value = Integer.toString((newState) ? 1 : 0); cache.setValueForMessages(messageIds, columnName, value); @@ -349,8 +341,7 @@ public class MessagingController implements Runnable { private void removeFlagFromCache(final Account account, final List messageIds, final Flag flag) { - EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), - mApplication.getApplicationContext()); + EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), context); String columnName = LocalStore.getColumnNameForFlag(flag); cache.removeValueForMessages(messageIds, columnName); } @@ -358,8 +349,7 @@ public class MessagingController implements Runnable { private void setFlagForThreadsInCache(final Account account, final List threadRootIds, final Flag flag, final boolean newState) { - EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), - mApplication.getApplicationContext()); + EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), context); String columnName = LocalStore.getColumnNameForFlag(flag); String value = Integer.toString((newState) ? 1 : 0); cache.setValueForThreads(threadRootIds, columnName, value); @@ -368,18 +358,14 @@ public class MessagingController implements Runnable { private void removeFlagForThreadsFromCache(final Account account, final List messageIds, final Flag flag) { - EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), - mApplication.getApplicationContext()); + EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), context); String columnName = LocalStore.getColumnNameForFlag(flag); cache.removeValueForThreads(messageIds, columnName); } - /** - * @param application {@link K9} - */ - private MessagingController(Application application) { - mApplication = application; + private MessagingController(Context context) { + this.context = context.getApplicationContext(); mThread = new Thread(this); mThread.setName("MessagingController"); mThread.start(); @@ -388,15 +374,9 @@ public class MessagingController implements Runnable { } } - /** - * Gets or creates the singleton instance of MessagingController. Application is used to - * provide a Context to classes that need it. - * @param application {@link K9} - * @return - */ - public synchronized static MessagingController getInstance(Application application) { + public synchronized static MessagingController getInstance(Context context) { if (inst == null) { - inst = new MessagingController(application); + inst = new MessagingController(context); } return inst; } @@ -556,7 +536,7 @@ public class MessagingController implements Runnable { l.listFoldersStarted(account); } List localFolders = null; - if (!account.isAvailable(mApplication)) { + if (!account.isAvailable(context)) { Log.i(K9.LOG_TAG, "not listing folders of unavailable account"); } else { try { @@ -680,7 +660,7 @@ public class MessagingController implements Runnable { public void searchLocalMessagesSynchronous(final LocalSearch search, final MessagingListener listener) { final AccountStats stats = new AccountStats(); final Set uuidSet = new HashSet(Arrays.asList(search.getAccountUuids())); - List accounts = Preferences.getPreferences(mApplication.getApplicationContext()).getAccounts(); + List accounts = Preferences.getPreferences(context).getAccounts(); boolean allAccounts = uuidSet.contains(SearchSpecification.ALL_ACCOUNTS); // for every account we want to search do the query in the localstore @@ -761,7 +741,7 @@ public class MessagingController implements Runnable { } public void searchRemoteMessagesSynchronous(final String acctUuid, final String folderName, final String query, final Set requiredFlags, final Set forbiddenFlags, final MessagingListener listener) { - final Account acct = Preferences.getPreferences(mApplication.getApplicationContext()).getAccount(acctUuid); + final Account acct = Preferences.getPreferences(context).getAccount(acctUuid); if (listener != null) { listener.remoteSearchStarted(folderName); @@ -1175,7 +1155,7 @@ public class MessagingController implements Runnable { for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFailed(account, folder, rootMessage); } - notifyUserIfCertificateProblem(mApplication, e, account, true); + notifyUserIfCertificateProblem(context, e, account, true); addErrorMessage(account, null, e); Log.e(K9.LOG_TAG, "Failed synchronizing folder " + account.getDescription() + ":" + folder + " @ " + new Date()); @@ -1258,7 +1238,7 @@ public class MessagingController implements Runnable { int unreadBeforeStart = 0; try { - AccountStats stats = account.getStats(mApplication); + AccountStats stats = account.getStats(context); unreadBeforeStart = stats.unreadMessageCount; } catch (MessagingException e) { @@ -1390,7 +1370,7 @@ public class MessagingController implements Runnable { if (oldestExtantMessage.before(downloadStarted) && oldestExtantMessage.after(new Date(account.getLatestOldMessageSeenTime()))) { account.setLatestOldMessageSeenTime(oldestExtantMessage.getTime()); - account.save(Preferences.getPreferences(mApplication.getApplicationContext())); + account.save(Preferences.getPreferences(context)); } } @@ -1651,7 +1631,7 @@ public class MessagingController implements Runnable { if (shouldNotifyForMessage(account, localFolder, message)) { // Notify with the localMessage so that we don't have to recalculate the content preview. - notifyAccount(mApplication, account, localMessage, unreadBeforeStart); + notifyAccount(context, account, localMessage, unreadBeforeStart); } } catch (MessagingException me) { @@ -1789,7 +1769,7 @@ public class MessagingController implements Runnable { // Send a notification of this message if (shouldNotifyForMessage(account, localFolder, message)) { // Notify with the localMessage so that we don't have to recalculate the content preview. - notifyAccount(mApplication, account, localMessage, unreadBeforeStart); + notifyAccount(context, account, localMessage, unreadBeforeStart); } }//for large messages @@ -1846,8 +1826,8 @@ public class MessagingController implements Runnable { if (data != null) { synchronized (data) { MessageReference ref = localMessage.makeMessageReference(); - if (data.removeMatchingMessage(mApplication, ref)) { - notifyAccountWithDataLocked(mApplication, account, null, data); + if (data.removeMatchingMessage(context, ref)) { + notifyAccountWithDataLocked(context, account, null, data); } } } @@ -2007,7 +1987,7 @@ public class MessagingController implements Runnable { } } } catch (MessagingException me) { - notifyUserIfCertificateProblem(mApplication, me, account, true); + notifyUserIfCertificateProblem(context, me, account, true); addErrorMessage(account, null, me); Log.e(K9.LOG_TAG, "Could not process command '" + processingCommand + "'", me); throw me; @@ -2679,8 +2659,8 @@ public class MessagingController implements Runnable { CharArrayWriter baos = new CharArrayWriter(t.getStackTrace().length * 10); PrintWriter ps = new PrintWriter(baos); try { - PackageInfo packageInfo = mApplication.getPackageManager().getPackageInfo( - mApplication.getPackageName(), 0); + PackageInfo packageInfo = context.getPackageManager().getPackageInfo( + context.getPackageName(), 0); ps.format("K9-Mail version: %s\r\n", packageInfo.versionName); } catch (Exception e) { // ignore @@ -2984,7 +2964,7 @@ public class MessagingController implements Runnable { if (uid.startsWith(K9.LOCAL_UID_PREFIX)) { Log.w(K9.LOG_TAG, "Message has local UID so cannot download fully."); // ASH move toast - android.widget.Toast.makeText(mApplication, + android.widget.Toast.makeText(context, "Message has local UID so cannot download fully", android.widget.Toast.LENGTH_LONG).show(); // TODO: Using X_DOWNLOADED_FULL is wrong because it's only a partial message. But @@ -3061,7 +3041,7 @@ public class MessagingController implements Runnable { for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewFailed(account, folder, uid, e); } - notifyUserIfCertificateProblem(mApplication, e, account, true); + notifyUserIfCertificateProblem(context, e, account, true); addErrorMessage(account, null, e); return false; } finally { @@ -3224,7 +3204,7 @@ public class MessagingController implements Runnable { for (MessagingListener l : getListeners(listener)) { l.loadAttachmentFailed(account, message, part, tag, me.getMessage()); } - notifyUserIfCertificateProblem(mApplication, me, account, true); + notifyUserIfCertificateProblem(context, me, account, true); addErrorMessage(account, null, me); } finally { @@ -3268,7 +3248,7 @@ public class MessagingController implements Runnable { public void sendPendingMessages(MessagingListener listener) { - final Preferences prefs = Preferences.getPreferences(mApplication.getApplicationContext()); + final Preferences prefs = Preferences.getPreferences(context); for (Account account : prefs.getAvailableAccounts()) { sendPendingMessages(account, listener); } @@ -3285,7 +3265,7 @@ public class MessagingController implements Runnable { putBackground("sendPendingMessages", listener, new Runnable() { @Override public void run() { - if (!account.isAvailable(mApplication)) { + if (!account.isAvailable(context)) { throw new UnavailableAccountException(); } if (messagesPendingSend(account)) { @@ -3305,7 +3285,7 @@ public class MessagingController implements Runnable { private void cancelNotification(int id) { NotificationManager notifMgr = - (NotificationManager) mApplication.getSystemService(Context.NOTIFICATION_SERVICE); + (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); notifMgr.cancel(id); } @@ -3328,9 +3308,9 @@ public class MessagingController implements Runnable { } NotificationManager notifMgr = - (NotificationManager) mApplication.getSystemService(Context.NOTIFICATION_SERVICE); + (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); - NotificationCompat.Builder builder = new NotificationCompat.Builder(mApplication); + NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setSmallIcon(R.drawable.ic_notify_check_mail); builder.setWhen(System.currentTimeMillis()); builder.setOngoing(true); @@ -3339,13 +3319,13 @@ public class MessagingController implements Runnable { String accountName = (TextUtils.isEmpty(accountDescription)) ? account.getEmail() : accountDescription; - builder.setTicker(mApplication.getString(R.string.notification_bg_send_ticker, + builder.setTicker(context.getString(R.string.notification_bg_send_ticker, accountName)); - builder.setContentTitle(mApplication.getString(R.string.notification_bg_send_title)); + builder.setContentTitle(context.getString(R.string.notification_bg_send_title)); builder.setContentText(account.getDescription()); - TaskStackBuilder stack = buildMessageListBackStack(mApplication, account, + TaskStackBuilder stack = buildMessageListBackStack(context, account, account.getInboxFolderName()); builder.setContentIntent(stack.getPendingIntent(0, 0)); builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); @@ -3380,19 +3360,19 @@ public class MessagingController implements Runnable { */ private void notifySendFailed(Account account, Exception lastFailure, String openFolder) { NotificationManager notifMgr = - (NotificationManager) mApplication.getSystemService(Context.NOTIFICATION_SERVICE); + (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); - NotificationCompat.Builder builder = new NotificationCompat.Builder(mApplication); + NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setSmallIcon(platformSupportsLockScreenNotifications() ? R.drawable.ic_notify_new_mail_vector : R.drawable.ic_notify_new_mail); builder.setWhen(System.currentTimeMillis()); builder.setAutoCancel(true); - builder.setTicker(mApplication.getString(R.string.send_failure_subject)); - builder.setContentTitle(mApplication.getString(R.string.send_failure_subject)); + builder.setTicker(context.getString(R.string.send_failure_subject)); + builder.setContentTitle(context.getString(R.string.send_failure_subject)); builder.setContentText(getRootCauseMessage(lastFailure)); - TaskStackBuilder stack = buildFolderListBackStack(mApplication, account); + TaskStackBuilder stack = buildFolderListBackStack(context, account); builder.setContentIntent(stack.getPendingIntent(0, 0)); builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); @@ -3417,20 +3397,20 @@ public class MessagingController implements Runnable { } final NotificationManager notifMgr = - (NotificationManager) mApplication.getSystemService(Context.NOTIFICATION_SERVICE); + (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); - NotificationCompat.Builder builder = new NotificationCompat.Builder(mApplication); + NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setSmallIcon(R.drawable.ic_notify_check_mail); builder.setWhen(System.currentTimeMillis()); builder.setOngoing(true); - builder.setTicker(mApplication.getString( + builder.setTicker(context.getString( R.string.notification_bg_sync_ticker, account.getDescription(), folder.getName())); - builder.setContentTitle(mApplication.getString(R.string.notification_bg_sync_title)); + builder.setContentTitle(context.getString(R.string.notification_bg_sync_title)); builder.setContentText(account.getDescription() + - mApplication.getString(R.string.notification_bg_title_separator) + + context.getString(R.string.notification_bg_title_separator) + folder.getName()); - TaskStackBuilder stack = buildMessageListBackStack(mApplication, account, + TaskStackBuilder stack = buildMessageListBackStack(context, account, account.getInboxFolderName()); builder.setContentIntent(stack.getPendingIntent(0, 0)); builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); @@ -3585,7 +3565,7 @@ public class MessagingController implements Runnable { localFolder.moveMessages(Collections.singletonList(message), (LocalFolder) localStore.getFolder(account.getDraftsFolderName())); } - notifyUserIfCertificateProblem(mApplication, e, account, false); + notifyUserIfCertificateProblem(context, e, account, false); addErrorMessage(account, "Failed to send message", e); message.setFlag(Flag.X_SEND_FAILED, true); Log.e(K9.LOG_TAG, "Failed to send message", e); @@ -3662,7 +3642,7 @@ public class MessagingController implements Runnable { public AccountStats getSearchAccountStatsSynchronous(final SearchAccount searchAccount, final MessagingListener listener) { - Preferences preferences = Preferences.getPreferences(mApplication); + Preferences preferences = Preferences.getPreferences(context); LocalSearch search = searchAccount.getRelatedSearch(); // Collect accounts that belong to the search @@ -3678,7 +3658,7 @@ public class MessagingController implements Runnable { } } - ContentResolver cr = mApplication.getContentResolver(); + ContentResolver cr = context.getContentResolver(); int unreadMessageCount = 0; int flaggedMessageCount = 0; @@ -5286,7 +5266,7 @@ public class MessagingController implements Runnable { if (previousPusher != null) { previousPusher.stop(); } - Preferences prefs = Preferences.getPreferences(mApplication); + Preferences prefs = Preferences.getPreferences(context); Account.FolderMode aDisplayMode = account.getFolderDisplayMode(); Account.FolderMode aPushMode = account.getFolderPushMode(); @@ -5338,7 +5318,7 @@ public class MessagingController implements Runnable { } if (!names.isEmpty()) { - PushReceiver receiver = new MessagingControllerPushReceiver(mApplication, account, this); + PushReceiver receiver = new MessagingControllerPushReceiver(context, account, this); int maxPushFolders = account.getMaxPushFolders(); if (names.size() > maxPushFolders) { @@ -5422,7 +5402,7 @@ public class MessagingController implements Runnable { Log.i(K9.LOG_TAG, "messagesArrived newCount = " + newCount + ", unread count = " + unreadMessageCount); if (unreadMessageCount == 0) { - notifyAccountCancel(mApplication, account); + notifyAccountCancel(context, account); } for (MessagingListener l : getListeners()) { diff --git a/src/com/fsck/k9/controller/MessagingControllerPushReceiver.java b/src/com/fsck/k9/controller/MessagingControllerPushReceiver.java index 3bdec8c22..7e471068c 100644 --- a/src/com/fsck/k9/controller/MessagingControllerPushReceiver.java +++ b/src/com/fsck/k9/controller/MessagingControllerPushReceiver.java @@ -1,6 +1,5 @@ package com.fsck.k9.controller; -import android.app.Application; import android.content.Context; import android.util.Log; @@ -21,12 +20,12 @@ import java.util.concurrent.CountDownLatch; public class MessagingControllerPushReceiver implements PushReceiver { final Account account; final MessagingController controller; - final Application mApplication; + final Context context; - public MessagingControllerPushReceiver(Application nApplication, Account nAccount, MessagingController nController) { + public MessagingControllerPushReceiver(Context context, Account nAccount, MessagingController nController) { account = nAccount; controller = nController; - mApplication = nApplication; + this.context = context; } public void messagesFlagsChanged(Folder folder, @@ -71,13 +70,13 @@ public class MessagingControllerPushReceiver implements PushReceiver { @Override public void sleep(TracingWakeLock wakeLock, long millis) { - SleepService.sleep(mApplication, millis, wakeLock, K9.PUSH_WAKE_LOCK_TIMEOUT); + SleepService.sleep(context, millis, wakeLock, K9.PUSH_WAKE_LOCK_TIMEOUT); } public void pushError(String errorMessage, Exception e) { String errMess = errorMessage; - controller.notifyUserIfCertificateProblem(mApplication, e, account, true); + controller.notifyUserIfCertificateProblem(context, e, account, true); if (errMess == null && e != null) { errMess = e.getMessage(); } @@ -110,7 +109,7 @@ public class MessagingControllerPushReceiver implements PushReceiver { @Override public Context getContext() { - return mApplication; + return context; } } diff --git a/src/com/fsck/k9/helper/Utility.java b/src/com/fsck/k9/helper/Utility.java index ffd6270a2..6be32825d 100644 --- a/src/com/fsck/k9/helper/Utility.java +++ b/src/com/fsck/k9/helper/Utility.java @@ -1,7 +1,6 @@ package com.fsck.k9.helper; -import android.app.Application; import android.content.Context; import android.database.Cursor; import android.net.ConnectivityManager; @@ -421,12 +420,10 @@ public class Utility { /** * Check to see if we have network connectivity. - * @param app Current application (Hint: see if your base class has a getApplication() method.) - * @return true if we have connectivity, false otherwise. */ - public static boolean hasConnectivity(final Application app) { + public static boolean hasConnectivity(final Context context) { final ConnectivityManager connectivityManager = - (ConnectivityManager) app.getSystemService(Context.CONNECTIVITY_SERVICE); + (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivityManager == null) { return false; } diff --git a/src/com/fsck/k9/mailstore/LocalAttachmentBody.java b/src/com/fsck/k9/mailstore/LocalAttachmentBody.java index 0accef810..0b191472a 100644 --- a/src/com/fsck/k9/mailstore/LocalAttachmentBody.java +++ b/src/com/fsck/k9/mailstore/LocalAttachmentBody.java @@ -4,7 +4,7 @@ import java.io.ByteArrayInputStream; import java.io.FileNotFoundException; import java.io.InputStream; -import android.app.Application; +import android.content.Context; import android.net.Uri; import com.fsck.k9.mail.MessagingException; @@ -13,18 +13,18 @@ import com.fsck.k9.mail.MessagingException; * An attachment whose contents are loaded from an URI. */ public class LocalAttachmentBody extends BinaryAttachmentBody { - private Application mApplication; + private Context context; private Uri mUri; - public LocalAttachmentBody(Uri uri, Application application) { - mApplication = application; + public LocalAttachmentBody(Uri uri, Context context) { + this.context = context; mUri = uri; } @Override public InputStream getInputStream() throws MessagingException { try { - return mApplication.getContentResolver().openInputStream(mUri); + return context.getContentResolver().openInputStream(mUri); } catch (FileNotFoundException fnfe) { /* * Since it's completely normal for us to try to serve up attachments that diff --git a/src/com/fsck/k9/mailstore/LocalAttachmentMessageBody.java b/src/com/fsck/k9/mailstore/LocalAttachmentMessageBody.java index bd0a4329f..82d62e092 100644 --- a/src/com/fsck/k9/mailstore/LocalAttachmentMessageBody.java +++ b/src/com/fsck/k9/mailstore/LocalAttachmentMessageBody.java @@ -5,7 +5,7 @@ import java.io.OutputStream; import org.apache.james.mime4j.util.MimeUtil; -import android.app.Application; +import android.content.Context; import android.net.Uri; import com.fsck.k9.mail.CompositeBody; @@ -17,8 +17,8 @@ import com.fsck.k9.mail.MessagingException; */ class LocalAttachmentMessageBody extends LocalAttachmentBody implements CompositeBody { - public LocalAttachmentMessageBody(Uri uri, Application application) { - super(uri, application); + public LocalAttachmentMessageBody(Uri uri, Context context) { + super(uri, context); } @Override diff --git a/src/com/fsck/k9/mailstore/LocalFolder.java b/src/com/fsck/k9/mailstore/LocalFolder.java index 63e958ec9..e4572f40a 100644 --- a/src/com/fsck/k9/mailstore/LocalFolder.java +++ b/src/com/fsck/k9/mailstore/LocalFolder.java @@ -737,11 +737,11 @@ public class LocalFolder extends Folder implements Serializable { if (MimeUtil.isMessage(type)) { body = new LocalAttachmentMessageBody( Uri.parse(contentUri), - LocalFolder.this.localStore.mApplication); + LocalFolder.this.localStore.context); } else { body = new LocalAttachmentBody( Uri.parse(contentUri), - LocalFolder.this.localStore.mApplication); + LocalFolder.this.localStore.context); } } @@ -1306,7 +1306,7 @@ public class LocalFolder extends Folder implements Serializable { attachments = container.attachments; } else { ViewableContainer container = - LocalMessageExtractor.extractTextAndAttachments(LocalFolder.this.localStore.mApplication, message); + LocalMessageExtractor.extractTextAndAttachments(LocalFolder.this.localStore.context, message); attachments = container.attachments; text = container.text; @@ -1412,7 +1412,7 @@ public class LocalFolder extends Folder implements Serializable { message.buildMimeRepresentation(); ViewableContainer container = - LocalMessageExtractor.extractTextAndAttachments(LocalFolder.this.localStore.mApplication, message); + LocalMessageExtractor.extractTextAndAttachments(LocalFolder.this.localStore.context, message); List attachments = container.attachments; String text = container.text; @@ -1548,7 +1548,7 @@ public class LocalFolder extends Folder implements Serializable { attachmentId = ((LocalAttachmentBodyPart) attachment).getAttachmentId(); } - final File attachmentDirectory = StorageManager.getInstance(LocalFolder.this.localStore.mApplication).getAttachmentDirectory(LocalFolder.this.localStore.uUid, LocalFolder.this.localStore.database.getStorageProviderId()); + final File attachmentDirectory = StorageManager.getInstance(LocalFolder.this.localStore.context).getAttachmentDirectory(LocalFolder.this.localStore.uUid, LocalFolder.this.localStore.database.getStorageProviderId()); if (attachment.getBody() != null) { Body body = attachment.getBody(); if (body instanceof LocalAttachmentBody) { @@ -1653,10 +1653,10 @@ public class LocalFolder extends Folder implements Serializable { attachmentId); if (MimeUtil.isMessage(attachment.getMimeType())) { attachment.setBody(new LocalAttachmentMessageBody( - contentUri, LocalFolder.this.localStore.mApplication)); + contentUri, LocalFolder.this.localStore.context)); } else { attachment.setBody(new LocalAttachmentBody( - contentUri, LocalFolder.this.localStore.mApplication)); + contentUri, LocalFolder.this.localStore.context)); } ContentValues cv = new ContentValues(); cv.put("content_uri", contentUri != null ? contentUri.toString() : null); @@ -1891,14 +1891,14 @@ public class LocalFolder extends Folder implements Serializable { Cursor attachmentsCursor = null; try { String accountUuid = getAccountUuid(); - Context context = LocalFolder.this.localStore.mApplication; + Context context = LocalFolder.this.localStore.context; // Get attachment IDs String[] whereArgs = new String[] { Long.toString(messageId) }; attachmentsCursor = db.query("attachments", new String[] { "id" }, "message_id = ?", whereArgs, null, null, null); - final File attachmentDirectory = StorageManager.getInstance(LocalFolder.this.localStore.mApplication) + final File attachmentDirectory = StorageManager.getInstance(LocalFolder.this.localStore.context) .getAttachmentDirectory(LocalFolder.this.localStore.uUid, LocalFolder.this.localStore.database.getStorageProviderId()); while (attachmentsCursor.moveToNext()) { diff --git a/src/com/fsck/k9/mailstore/LocalStore.java b/src/com/fsck/k9/mailstore/LocalStore.java index 46dfaa0b3..349e9188d 100644 --- a/src/com/fsck/k9/mailstore/LocalStore.java +++ b/src/com/fsck/k9/mailstore/LocalStore.java @@ -145,7 +145,7 @@ public class LocalStore extends Store implements Serializable { protected String uUid = null; - final Application mApplication; + final Context context; LockableDatabase database; @@ -154,17 +154,17 @@ public class LocalStore extends Store implements Serializable { /** * local://localhost/path/to/database/uuid.db - * This constructor is only used by {@link Store#getLocalInstance(Account, Application)} + * This constructor is only used by {@link Store#getLocalInstance(Account, Context)} * @param account - * @param application + * @param context * @throws UnavailableStorageException if not {@link StorageProvider#isReady(Context)} */ - public LocalStore(final Account account, final Application application) throws MessagingException { + public LocalStore(final Account account, final Context context) throws MessagingException { mAccount = account; - database = new LockableDatabase(application, account.getUuid(), new StoreSchemaDefinition(this)); + database = new LockableDatabase(context, account.getUuid(), new StoreSchemaDefinition(this)); - mApplication = application; - mContentResolver = application.getContentResolver(); + this.context = context; + mContentResolver = context.getContentResolver(); database.setStorageProviderId(account.getLocalStorageProviderId()); uUid = account.getUuid(); @@ -227,12 +227,12 @@ public class LocalStore extends Store implements Serializable { } protected SharedPreferences getPreferences() { - return Preferences.getPreferences(mApplication).getPreferences(); + return Preferences.getPreferences(context).getPreferences(); } public long getSize() throws MessagingException { - final StorageManager storageManager = StorageManager.getInstance(mApplication); + final StorageManager storageManager = StorageManager.getInstance(context); final File attachmentDirectory = storageManager.getAttachmentDirectory(uUid, database.getStorageProviderId()); @@ -421,7 +421,7 @@ public class LocalStore extends Store implements Serializable { cv.putNull("content_uri"); db.update("attachments", cv, null, null); } - final StorageManager storageManager = StorageManager.getInstance(mApplication); + final StorageManager storageManager = StorageManager.getInstance(context); File[] files = storageManager.getAttachmentDirectory(uUid, database.getStorageProviderId()).listFiles(); for (File file : files) { if (file.exists()) { diff --git a/src/com/fsck/k9/mailstore/LockableDatabase.java b/src/com/fsck/k9/mailstore/LockableDatabase.java index f7c0a2258..11cb478e1 100644 --- a/src/com/fsck/k9/mailstore/LockableDatabase.java +++ b/src/com/fsck/k9/mailstore/LockableDatabase.java @@ -6,7 +6,6 @@ import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import android.annotation.TargetApi; -import android.app.Application; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; @@ -128,7 +127,7 @@ public class LockableDatabase { private final StorageListener mStorageListener = new StorageListener(); - private Application mApplication; + private Context context; /** * {@link ThreadLocal} to check whether a DB transaction is occuring in the @@ -143,15 +142,15 @@ public class LockableDatabase { private String uUid; /** - * @param application + * @param context * Never null. * @param uUid * Never null. * @param schemaDefinition * Never null mProviderLocks = new IdentityHashMap(); - protected final Application mApplication; + protected final Context context; /** * Listener to be notified for storage related events. @@ -495,9 +494,9 @@ public class StorageManager { private static transient StorageManager instance; - public static synchronized StorageManager getInstance(final Application application) { + public static synchronized StorageManager getInstance(final Context context) { if (instance == null) { - instance = new StorageManager(application); + instance = new StorageManager(context); } return instance; } @@ -518,17 +517,17 @@ public class StorageManager { } /** - * @param application + * @param context * Never null. * @throws NullPointerException - * If application is null. + * If context is null. */ - protected StorageManager(final Application application) throws NullPointerException { - if (application == null) { - throw new NullPointerException("No application instance given"); + protected StorageManager(final Context context) throws NullPointerException { + if (context == null) { + throw new NullPointerException("No Context given"); } - mApplication = application; + this.context = context; /* * 20101113/fiouzy: @@ -547,10 +546,10 @@ public class StorageManager { new ExternalStorageProvider()); for (final StorageProvider provider : allProviders) { // check for provider compatibility - if (provider.isSupported(mApplication)) { + if (provider.isSupported(context)) { // provider is compatible! proceeding - provider.init(application); + provider.init(context); mProviders.put(provider.getId(), provider); mProviderLocks.put(provider, new SynchronizationAid()); } @@ -585,7 +584,7 @@ public class StorageManager { public File getDatabase(final String dbName, final String providerId) { StorageProvider provider = getProvider(providerId); // TODO fallback to internal storage if no provider - return provider.getDatabase(mApplication, dbName); + return provider.getDatabase(context, dbName); } /** @@ -598,7 +597,7 @@ public class StorageManager { public File getAttachmentDirectory(final String dbName, final String providerId) { StorageProvider provider = getProvider(providerId); // TODO fallback to internal storage if no provider - return provider.getAttachmentDirectory(mApplication, dbName); + return provider.getAttachmentDirectory(context, dbName); } /** @@ -612,7 +611,7 @@ public class StorageManager { Log.w(K9.LOG_TAG, "Storage-Provider \"" + providerId + "\" does not exist"); return false; } - return provider.isReady(mApplication); + return provider.isReady(context); } /** @@ -624,7 +623,7 @@ public class StorageManager { public Map getAvailableProviders() { final Map result = new LinkedHashMap(); for (final Map.Entry entry : mProviders.entrySet()) { - result.put(entry.getKey(), entry.getValue().getName(mApplication)); + result.put(entry.getKey(), entry.getValue().getName(context)); } return result; } @@ -698,7 +697,7 @@ public class StorageManager { */ protected StorageProvider resolveProvider(final String path) { for (final StorageProvider provider : mProviders.values()) { - if (path.equals(provider.getRoot(mApplication).getAbsolutePath())) { + if (path.equals(provider.getRoot(context).getAbsolutePath())) { return provider; } } @@ -738,7 +737,7 @@ public class StorageManager { sync.readLock.unlock(); } throw new UnavailableStorageException("StorageProvider is unmounting"); - } else if (locked && !provider.isReady(mApplication)) { + } else if (locked && !provider.isReady(context)) { sync.readLock.unlock(); throw new UnavailableStorageException("StorageProvider not ready"); } diff --git a/src/com/fsck/k9/mailstore/StoreSchemaDefinition.java b/src/com/fsck/k9/mailstore/StoreSchemaDefinition.java index f9e786dba..4148ba2ce 100644 --- a/src/com/fsck/k9/mailstore/StoreSchemaDefinition.java +++ b/src/com/fsck/k9/mailstore/StoreSchemaDefinition.java @@ -53,7 +53,7 @@ class StoreSchemaDefinition implements LockableDatabase.SchemaDefinition { Log.i(K9.LOG_TAG, String.format(Locale.US, "Upgrading database from version %d to version %d", db.getVersion(), LocalStore.DB_VERSION)); - AttachmentProvider.clear(this.localStore.mApplication); + AttachmentProvider.clear(this.localStore.context); db.beginTransaction(); try { @@ -595,4 +595,4 @@ class StoreSchemaDefinition implements LockableDatabase.SchemaDefinition { new Object[] { integrate, inTopGroup, syncClass, pushClass, displayClass, id }); } -} \ No newline at end of file +} From e447257414a5fb89b2ceec3c40599c728565f9fd Mon Sep 17 00:00:00 2001 From: cketti Date: Fri, 12 Dec 2014 06:32:24 +0100 Subject: [PATCH 2/2] Stop using K9.app where easily possible --- src/com/fsck/k9/Account.java | 4 ++-- src/com/fsck/k9/Preferences.java | 2 +- src/com/fsck/k9/activity/setup/AccountSettings.java | 2 +- src/com/fsck/k9/controller/MessagingController.java | 4 ++-- src/com/fsck/k9/mailstore/LocalStore.java | 4 ++-- src/com/fsck/k9/mailstore/StorageManager.java | 6 +++--- src/com/fsck/k9/mailstore/StoreSchemaDefinition.java | 2 +- src/com/fsck/k9/provider/AttachmentProvider.java | 6 +++--- src/com/fsck/k9/provider/MessageProvider.java | 6 +++--- src/com/fsck/k9/provider/UnreadWidgetProvider.java | 2 +- src/com/fsck/k9/service/StorageGoneReceiver.java | 4 ++-- src/com/fsck/k9/service/StorageReceiver.java | 2 +- 12 files changed, 22 insertions(+), 22 deletions(-) diff --git a/src/com/fsck/k9/Account.java b/src/com/fsck/k9/Account.java index e86ee07a1..a1c491ee6 100644 --- a/src/com/fsck/k9/Account.java +++ b/src/com/fsck/k9/Account.java @@ -265,7 +265,7 @@ public class Account implements BaseAccount, StoreConfig { protected Account(Context context) { mUuid = UUID.randomUUID().toString(); - mLocalStorageProviderId = StorageManager.getInstance(K9.app).getDefaultProviderId(); + mLocalStorageProviderId = StorageManager.getInstance(context).getDefaultProviderId(); mAutomaticCheckIntervalMinutes = -1; mIdleRefreshMinutes = 24; mPushPollOnConnect = true; @@ -1701,7 +1701,7 @@ public class Account implements BaseAccount, StoreConfig { if (localStorageProviderId == null) { return true; // defaults to internal memory } - return StorageManager.getInstance(K9.app).isReady(localStorageProviderId); + return StorageManager.getInstance(context).isReady(localStorageProviderId); } public synchronized boolean isEnabled() { diff --git a/src/com/fsck/k9/Preferences.java b/src/com/fsck/k9/Preferences.java index 03a3cd1be..7d03b668e 100644 --- a/src/com/fsck/k9/Preferences.java +++ b/src/com/fsck/k9/Preferences.java @@ -107,7 +107,7 @@ public class Preferences { } public synchronized Account newAccount() { - newAccount = new Account(K9.app); + newAccount = new Account(mContext); accounts.put(newAccount.getUuid(), newAccount); accountsInOrder.add(newAccount); diff --git a/src/com/fsck/k9/activity/setup/AccountSettings.java b/src/com/fsck/k9/activity/setup/AccountSettings.java index c6ee715de..c9127b2d7 100644 --- a/src/com/fsck/k9/activity/setup/AccountSettings.java +++ b/src/com/fsck/k9/activity/setup/AccountSettings.java @@ -470,7 +470,7 @@ public class AccountSettings extends K9PreferenceActivity { mLocalStorageProvider = (ListPreference) findPreference(PREFERENCE_LOCAL_STORAGE_PROVIDER); { final Map providers; - providers = StorageManager.getInstance(K9.app).getAvailableProviders(); + providers = StorageManager.getInstance(this).getAvailableProviders(); int i = 0; final String[] providerLabels = new String[providers.size()]; final String[] providerIds = new String[providers.size()]; diff --git a/src/com/fsck/k9/controller/MessagingController.java b/src/com/fsck/k9/controller/MessagingController.java index 189a0681e..643e41d4b 100644 --- a/src/com/fsck/k9/controller/MessagingController.java +++ b/src/com/fsck/k9/controller/MessagingController.java @@ -365,7 +365,7 @@ public class MessagingController implements Runnable { private MessagingController(Context context) { - this.context = context.getApplicationContext(); + this.context = context; mThread = new Thread(this); mThread.setName("MessagingController"); mThread.start(); @@ -376,7 +376,7 @@ public class MessagingController implements Runnable { public synchronized static MessagingController getInstance(Context context) { if (inst == null) { - inst = new MessagingController(context); + inst = new MessagingController(context.getApplicationContext()); } return inst; } diff --git a/src/com/fsck/k9/mailstore/LocalStore.java b/src/com/fsck/k9/mailstore/LocalStore.java index 349e9188d..41b97e742 100644 --- a/src/com/fsck/k9/mailstore/LocalStore.java +++ b/src/com/fsck/k9/mailstore/LocalStore.java @@ -177,7 +177,7 @@ public class LocalStore extends Store implements Serializable { * @throws UnavailableStorageException * if not {@link StorageProvider#isReady(Context)} */ - public static LocalStore getInstance(Account account, Application application) + public static LocalStore getInstance(Account account, Context context) throws MessagingException { String accountUuid = account.getUuid(); @@ -196,7 +196,7 @@ public class LocalStore extends Store implements Serializable { if (store == null) { // Creating a LocalStore instance will create or upgrade the database if // necessary. This could take some time. - store = new LocalStore(account, application); + store = new LocalStore(account, context); sLocalStores.put(accountUuid, store); } diff --git a/src/com/fsck/k9/mailstore/StorageManager.java b/src/com/fsck/k9/mailstore/StorageManager.java index 2fbc3a981..1086aff41 100644 --- a/src/com/fsck/k9/mailstore/StorageManager.java +++ b/src/com/fsck/k9/mailstore/StorageManager.java @@ -496,7 +496,7 @@ public class StorageManager { public static synchronized StorageManager getInstance(final Context context) { if (instance == null) { - instance = new StorageManager(context); + instance = new StorageManager(context.getApplicationContext()); } return instance; } @@ -661,7 +661,7 @@ public class StorageManager { sync.unmounting = false; sync.writeLock.unlock(); - K9.setServicesEnabled(K9.app); + K9.setServicesEnabled(context); } /** @@ -687,7 +687,7 @@ public class StorageManager { } // XXX we should reset mail service ONLY if there are accounts using the storage (this is not done in a regular listener because it has to be invoked afterward) - K9.setServicesEnabled(K9.app); + K9.setServicesEnabled(context); } /** diff --git a/src/com/fsck/k9/mailstore/StoreSchemaDefinition.java b/src/com/fsck/k9/mailstore/StoreSchemaDefinition.java index 4148ba2ce..39bed6b3e 100644 --- a/src/com/fsck/k9/mailstore/StoreSchemaDefinition.java +++ b/src/com/fsck/k9/mailstore/StoreSchemaDefinition.java @@ -304,7 +304,7 @@ class StoreSchemaDefinition implements LockableDatabase.SchemaDefinition { } // Check if old (pre v3.800) localized outbox folder exists - String localizedOutbox = K9.app.getString(R.string.special_mailbox_name_outbox); + String localizedOutbox = localStore.context.getString(R.string.special_mailbox_name_outbox); LocalFolder obsoleteOutbox = new LocalFolder(this.localStore, localizedOutbox); if (obsoleteOutbox.exists()) { // Get all messages from the localized outbox ... diff --git a/src/com/fsck/k9/provider/AttachmentProvider.java b/src/com/fsck/k9/provider/AttachmentProvider.java index 6516f60ef..d59de5592 100644 --- a/src/com/fsck/k9/provider/AttachmentProvider.java +++ b/src/com/fsck/k9/provider/AttachmentProvider.java @@ -215,7 +215,7 @@ public class AttachmentProvider extends ContentProvider { final AttachmentInfo attachmentInfo; try { final Account account = Preferences.getPreferences(getContext()).getAccount(dbName); - attachmentInfo = LocalStore.getInstance(account, K9.app).getAttachmentInfo(id); + attachmentInfo = LocalStore.getInstance(account, getContext()).getAttachmentInfo(id); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to retrieve attachment info from local store for ID: " + id, e); return null; @@ -269,7 +269,7 @@ public class AttachmentProvider extends ContentProvider { final Account account = Preferences.getPreferences(getContext()).getAccount(dbName); try { - final LocalStore localStore = LocalStore.getInstance(account, K9.app); + final LocalStore localStore = LocalStore.getInstance(account, getContext()); AttachmentInfo attachmentInfo = localStore.getAttachmentInfo(id); if (FORMAT_VIEW.equals(format) && mimeType != null) { @@ -289,7 +289,7 @@ public class AttachmentProvider extends ContentProvider { private File getFile(String dbName, String id) throws FileNotFoundException { Account account = Preferences.getPreferences(getContext()).getAccount(dbName); - File attachmentsDir = StorageManager.getInstance(K9.app).getAttachmentDirectory(dbName, + File attachmentsDir = StorageManager.getInstance(getContext()).getAttachmentDirectory(dbName, account.getLocalStorageProviderId()); File file = new File(attachmentsDir, id); diff --git a/src/com/fsck/k9/provider/MessageProvider.java b/src/com/fsck/k9/provider/MessageProvider.java index 4508edf1b..2917eab0b 100644 --- a/src/com/fsck/k9/provider/MessageProvider.java +++ b/src/com/fsck/k9/provider/MessageProvider.java @@ -303,7 +303,7 @@ public class MessageProvider extends ContentProvider { // new code for integrated inbox, only execute this once as it will be processed afterwards via the listener final SearchAccount integratedInboxAccount = SearchAccount.createUnifiedInboxAccount(getContext()); - final MessagingController msgController = MessagingController.getInstance(K9.app); + final MessagingController msgController = MessagingController.getInstance(getContext()); msgController.searchLocalMessages(integratedInboxAccount.getRelatedSearch(), new MesssageInfoHolderRetrieverListener(queue)); @@ -1041,7 +1041,7 @@ public class MessageProvider extends ContentProvider { // get localstore parameter LocalMessage msg = null; try { - LocalFolder lf = LocalStore.getInstance(myAccount, K9.app).getFolder(folderName); + LocalFolder lf = LocalStore.getInstance(myAccount, getContext()).getFolder(folderName); int msgCount = lf.getMessageCount(); if (K9.DEBUG) { Log.d(K9.LOG_TAG, "folder msg count = " + msgCount); @@ -1053,7 +1053,7 @@ public class MessageProvider extends ContentProvider { // launch command to delete the message if ((myAccount != null) && (msg != null)) { - MessagingController controller = MessagingController.getInstance(K9.app); + MessagingController controller = MessagingController.getInstance(getContext()); controller.deleteMessages(Collections.singletonList(msg), null); } diff --git a/src/com/fsck/k9/provider/UnreadWidgetProvider.java b/src/com/fsck/k9/provider/UnreadWidgetProvider.java index aba2211c5..f46091f62 100644 --- a/src/com/fsck/k9/provider/UnreadWidgetProvider.java +++ b/src/com/fsck/k9/provider/UnreadWidgetProvider.java @@ -68,7 +68,7 @@ public class UnreadWidgetProvider extends AppWidgetProvider { if (searchAccount != null) { account = searchAccount; - MessagingController controller = MessagingController.getInstance(K9.app); + MessagingController controller = MessagingController.getInstance(context); stats = controller.getSearchAccountStatsSynchronous(searchAccount, null); clickIntent = MessageList.intentDisplaySearch(context, searchAccount.getRelatedSearch(), false, true, true); diff --git a/src/com/fsck/k9/service/StorageGoneReceiver.java b/src/com/fsck/k9/service/StorageGoneReceiver.java index 592656f9d..26be4da34 100644 --- a/src/com/fsck/k9/service/StorageGoneReceiver.java +++ b/src/com/fsck/k9/service/StorageGoneReceiver.java @@ -35,9 +35,9 @@ public class StorageGoneReceiver extends BroadcastReceiver { final String path = uri.getPath(); if (Intent.ACTION_MEDIA_EJECT.equals(action)) { - StorageManager.getInstance(K9.app).onBeforeUnmount(path); + StorageManager.getInstance(context).onBeforeUnmount(path); } else if (Intent.ACTION_MEDIA_UNMOUNTED.equals(action)) { - StorageManager.getInstance(K9.app).onAfterUnmount(path); + StorageManager.getInstance(context).onAfterUnmount(path); } } diff --git a/src/com/fsck/k9/service/StorageReceiver.java b/src/com/fsck/k9/service/StorageReceiver.java index abf36dd13..0d34fbb94 100644 --- a/src/com/fsck/k9/service/StorageReceiver.java +++ b/src/com/fsck/k9/service/StorageReceiver.java @@ -30,7 +30,7 @@ public class StorageReceiver extends BroadcastReceiver { final String path = uri.getPath(); if (Intent.ACTION_MEDIA_MOUNTED.equals(action)) { - StorageManager.getInstance(K9.app).onMount(path, + StorageManager.getInstance(context).onMount(path, intent.getBooleanExtra("read-only", true)); } }