1
0
mirror of https://github.com/moparisthebest/k-9 synced 2024-11-23 18:02:15 -05:00

Don't require Application when a Context instance will do

This commit is contained in:
cketti 2014-12-12 04:40:49 +01:00
parent 86487a738d
commit 328405419a
11 changed files with 115 additions and 141 deletions

View File

@ -49,7 +49,7 @@ import android.widget.TextView;
* Currently we make no attempts to stop the background code (e.g. {@link MessagingController}) from * 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 * 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 * 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 * 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. * for this activity) it will appear as if {@link DatabaseUpgradeService} is performing the upgrade.
* </p> * </p>

View File

@ -22,7 +22,6 @@ import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import android.app.Application;
import android.app.KeyguardManager; import android.app.KeyguardManager;
import android.app.NotificationManager; import android.app.NotificationManager;
import android.app.PendingIntent; import android.app.PendingIntent;
@ -195,10 +194,7 @@ public class MessagingController implements Runnable {
private boolean mBusy; private boolean mBusy;
/** private Context context;
* {@link K9}
*/
private Application mApplication;
/** /**
* A holder class for pending notification data * A holder class for pending notification data
@ -316,14 +312,12 @@ public class MessagingController implements Runnable {
private static final Set<Flag> SYNC_FLAGS = EnumSet.of(Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED, Flag.FORWARDED); private static final Set<Flag> SYNC_FLAGS = EnumSet.of(Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED, Flag.FORWARDED);
private void suppressMessages(Account account, List<LocalMessage> messages) { private void suppressMessages(Account account, List<LocalMessage> messages) {
EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), context);
mApplication.getApplicationContext());
cache.hideMessages(messages); cache.hideMessages(messages);
} }
private void unsuppressMessages(Account account, List<? extends Message> messages) { private void unsuppressMessages(Account account, List<? extends Message> messages) {
EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), context);
mApplication.getApplicationContext());
cache.unhideMessages(messages); cache.unhideMessages(messages);
} }
@ -331,16 +325,14 @@ public class MessagingController implements Runnable {
long messageId = message.getId(); long messageId = message.getId();
long folderId = message.getFolder().getId(); long folderId = message.getFolder().getId();
EmailProviderCache cache = EmailProviderCache.getCache(message.getFolder().getAccountUuid(), EmailProviderCache cache = EmailProviderCache.getCache(message.getFolder().getAccountUuid(), context);
mApplication.getApplicationContext());
return cache.isMessageHidden(messageId, folderId); return cache.isMessageHidden(messageId, folderId);
} }
private void setFlagInCache(final Account account, final List<Long> messageIds, private void setFlagInCache(final Account account, final List<Long> messageIds,
final Flag flag, final boolean newState) { final Flag flag, final boolean newState) {
EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), context);
mApplication.getApplicationContext());
String columnName = LocalStore.getColumnNameForFlag(flag); String columnName = LocalStore.getColumnNameForFlag(flag);
String value = Integer.toString((newState) ? 1 : 0); String value = Integer.toString((newState) ? 1 : 0);
cache.setValueForMessages(messageIds, columnName, value); cache.setValueForMessages(messageIds, columnName, value);
@ -349,8 +341,7 @@ public class MessagingController implements Runnable {
private void removeFlagFromCache(final Account account, final List<Long> messageIds, private void removeFlagFromCache(final Account account, final List<Long> messageIds,
final Flag flag) { final Flag flag) {
EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), context);
mApplication.getApplicationContext());
String columnName = LocalStore.getColumnNameForFlag(flag); String columnName = LocalStore.getColumnNameForFlag(flag);
cache.removeValueForMessages(messageIds, columnName); cache.removeValueForMessages(messageIds, columnName);
} }
@ -358,8 +349,7 @@ public class MessagingController implements Runnable {
private void setFlagForThreadsInCache(final Account account, final List<Long> threadRootIds, private void setFlagForThreadsInCache(final Account account, final List<Long> threadRootIds,
final Flag flag, final boolean newState) { final Flag flag, final boolean newState) {
EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), context);
mApplication.getApplicationContext());
String columnName = LocalStore.getColumnNameForFlag(flag); String columnName = LocalStore.getColumnNameForFlag(flag);
String value = Integer.toString((newState) ? 1 : 0); String value = Integer.toString((newState) ? 1 : 0);
cache.setValueForThreads(threadRootIds, columnName, value); cache.setValueForThreads(threadRootIds, columnName, value);
@ -368,18 +358,14 @@ public class MessagingController implements Runnable {
private void removeFlagForThreadsFromCache(final Account account, final List<Long> messageIds, private void removeFlagForThreadsFromCache(final Account account, final List<Long> messageIds,
final Flag flag) { final Flag flag) {
EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), context);
mApplication.getApplicationContext());
String columnName = LocalStore.getColumnNameForFlag(flag); String columnName = LocalStore.getColumnNameForFlag(flag);
cache.removeValueForThreads(messageIds, columnName); cache.removeValueForThreads(messageIds, columnName);
} }
/** private MessagingController(Context context) {
* @param application {@link K9} this.context = context.getApplicationContext();
*/
private MessagingController(Application application) {
mApplication = application;
mThread = new Thread(this); mThread = new Thread(this);
mThread.setName("MessagingController"); mThread.setName("MessagingController");
mThread.start(); mThread.start();
@ -388,15 +374,9 @@ public class MessagingController implements Runnable {
} }
} }
/** public synchronized static MessagingController getInstance(Context context) {
* 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) {
if (inst == null) { if (inst == null) {
inst = new MessagingController(application); inst = new MessagingController(context);
} }
return inst; return inst;
} }
@ -556,7 +536,7 @@ public class MessagingController implements Runnable {
l.listFoldersStarted(account); l.listFoldersStarted(account);
} }
List <? extends Folder > localFolders = null; List <? extends Folder > localFolders = null;
if (!account.isAvailable(mApplication)) { if (!account.isAvailable(context)) {
Log.i(K9.LOG_TAG, "not listing folders of unavailable account"); Log.i(K9.LOG_TAG, "not listing folders of unavailable account");
} else { } else {
try { try {
@ -680,7 +660,7 @@ public class MessagingController implements Runnable {
public void searchLocalMessagesSynchronous(final LocalSearch search, final MessagingListener listener) { public void searchLocalMessagesSynchronous(final LocalSearch search, final MessagingListener listener) {
final AccountStats stats = new AccountStats(); final AccountStats stats = new AccountStats();
final Set<String> uuidSet = new HashSet<String>(Arrays.asList(search.getAccountUuids())); final Set<String> uuidSet = new HashSet<String>(Arrays.asList(search.getAccountUuids()));
List<Account> accounts = Preferences.getPreferences(mApplication.getApplicationContext()).getAccounts(); List<Account> accounts = Preferences.getPreferences(context).getAccounts();
boolean allAccounts = uuidSet.contains(SearchSpecification.ALL_ACCOUNTS); boolean allAccounts = uuidSet.contains(SearchSpecification.ALL_ACCOUNTS);
// for every account we want to search do the query in the localstore // 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, public void searchRemoteMessagesSynchronous(final String acctUuid, final String folderName, final String query,
final Set<Flag> requiredFlags, final Set<Flag> forbiddenFlags, final MessagingListener listener) { final Set<Flag> requiredFlags, final Set<Flag> forbiddenFlags, final MessagingListener listener) {
final Account acct = Preferences.getPreferences(mApplication.getApplicationContext()).getAccount(acctUuid); final Account acct = Preferences.getPreferences(context).getAccount(acctUuid);
if (listener != null) { if (listener != null) {
listener.remoteSearchStarted(folderName); listener.remoteSearchStarted(folderName);
@ -1175,7 +1155,7 @@ public class MessagingController implements Runnable {
for (MessagingListener l : getListeners(listener)) { for (MessagingListener l : getListeners(listener)) {
l.synchronizeMailboxFailed(account, folder, rootMessage); l.synchronizeMailboxFailed(account, folder, rootMessage);
} }
notifyUserIfCertificateProblem(mApplication, e, account, true); notifyUserIfCertificateProblem(context, e, account, true);
addErrorMessage(account, null, e); addErrorMessage(account, null, e);
Log.e(K9.LOG_TAG, "Failed synchronizing folder " + account.getDescription() + ":" + folder + " @ " + new Date()); 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; int unreadBeforeStart = 0;
try { try {
AccountStats stats = account.getStats(mApplication); AccountStats stats = account.getStats(context);
unreadBeforeStart = stats.unreadMessageCount; unreadBeforeStart = stats.unreadMessageCount;
} catch (MessagingException e) { } catch (MessagingException e) {
@ -1390,7 +1370,7 @@ public class MessagingController implements Runnable {
if (oldestExtantMessage.before(downloadStarted) && if (oldestExtantMessage.before(downloadStarted) &&
oldestExtantMessage.after(new Date(account.getLatestOldMessageSeenTime()))) { oldestExtantMessage.after(new Date(account.getLatestOldMessageSeenTime()))) {
account.setLatestOldMessageSeenTime(oldestExtantMessage.getTime()); 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)) { if (shouldNotifyForMessage(account, localFolder, message)) {
// Notify with the localMessage so that we don't have to recalculate the content preview. // 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) { } catch (MessagingException me) {
@ -1789,7 +1769,7 @@ public class MessagingController implements Runnable {
// Send a notification of this message // Send a notification of this message
if (shouldNotifyForMessage(account, localFolder, message)) { if (shouldNotifyForMessage(account, localFolder, message)) {
// Notify with the localMessage so that we don't have to recalculate the content preview. // 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 }//for large messages
@ -1846,8 +1826,8 @@ public class MessagingController implements Runnable {
if (data != null) { if (data != null) {
synchronized (data) { synchronized (data) {
MessageReference ref = localMessage.makeMessageReference(); MessageReference ref = localMessage.makeMessageReference();
if (data.removeMatchingMessage(mApplication, ref)) { if (data.removeMatchingMessage(context, ref)) {
notifyAccountWithDataLocked(mApplication, account, null, data); notifyAccountWithDataLocked(context, account, null, data);
} }
} }
} }
@ -2007,7 +1987,7 @@ public class MessagingController implements Runnable {
} }
} }
} catch (MessagingException me) { } catch (MessagingException me) {
notifyUserIfCertificateProblem(mApplication, me, account, true); notifyUserIfCertificateProblem(context, me, account, true);
addErrorMessage(account, null, me); addErrorMessage(account, null, me);
Log.e(K9.LOG_TAG, "Could not process command '" + processingCommand + "'", me); Log.e(K9.LOG_TAG, "Could not process command '" + processingCommand + "'", me);
throw me; throw me;
@ -2679,8 +2659,8 @@ public class MessagingController implements Runnable {
CharArrayWriter baos = new CharArrayWriter(t.getStackTrace().length * 10); CharArrayWriter baos = new CharArrayWriter(t.getStackTrace().length * 10);
PrintWriter ps = new PrintWriter(baos); PrintWriter ps = new PrintWriter(baos);
try { try {
PackageInfo packageInfo = mApplication.getPackageManager().getPackageInfo( PackageInfo packageInfo = context.getPackageManager().getPackageInfo(
mApplication.getPackageName(), 0); context.getPackageName(), 0);
ps.format("K9-Mail version: %s\r\n", packageInfo.versionName); ps.format("K9-Mail version: %s\r\n", packageInfo.versionName);
} catch (Exception e) { } catch (Exception e) {
// ignore // ignore
@ -2984,7 +2964,7 @@ public class MessagingController implements Runnable {
if (uid.startsWith(K9.LOCAL_UID_PREFIX)) { if (uid.startsWith(K9.LOCAL_UID_PREFIX)) {
Log.w(K9.LOG_TAG, "Message has local UID so cannot download fully."); Log.w(K9.LOG_TAG, "Message has local UID so cannot download fully.");
// ASH move toast // ASH move toast
android.widget.Toast.makeText(mApplication, android.widget.Toast.makeText(context,
"Message has local UID so cannot download fully", "Message has local UID so cannot download fully",
android.widget.Toast.LENGTH_LONG).show(); android.widget.Toast.LENGTH_LONG).show();
// TODO: Using X_DOWNLOADED_FULL is wrong because it's only a partial message. But // 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)) { for (MessagingListener l : getListeners(listener)) {
l.loadMessageForViewFailed(account, folder, uid, e); l.loadMessageForViewFailed(account, folder, uid, e);
} }
notifyUserIfCertificateProblem(mApplication, e, account, true); notifyUserIfCertificateProblem(context, e, account, true);
addErrorMessage(account, null, e); addErrorMessage(account, null, e);
return false; return false;
} finally { } finally {
@ -3224,7 +3204,7 @@ public class MessagingController implements Runnable {
for (MessagingListener l : getListeners(listener)) { for (MessagingListener l : getListeners(listener)) {
l.loadAttachmentFailed(account, message, part, tag, me.getMessage()); l.loadAttachmentFailed(account, message, part, tag, me.getMessage());
} }
notifyUserIfCertificateProblem(mApplication, me, account, true); notifyUserIfCertificateProblem(context, me, account, true);
addErrorMessage(account, null, me); addErrorMessage(account, null, me);
} finally { } finally {
@ -3268,7 +3248,7 @@ public class MessagingController implements Runnable {
public void sendPendingMessages(MessagingListener listener) { public void sendPendingMessages(MessagingListener listener) {
final Preferences prefs = Preferences.getPreferences(mApplication.getApplicationContext()); final Preferences prefs = Preferences.getPreferences(context);
for (Account account : prefs.getAvailableAccounts()) { for (Account account : prefs.getAvailableAccounts()) {
sendPendingMessages(account, listener); sendPendingMessages(account, listener);
} }
@ -3285,7 +3265,7 @@ public class MessagingController implements Runnable {
putBackground("sendPendingMessages", listener, new Runnable() { putBackground("sendPendingMessages", listener, new Runnable() {
@Override @Override
public void run() { public void run() {
if (!account.isAvailable(mApplication)) { if (!account.isAvailable(context)) {
throw new UnavailableAccountException(); throw new UnavailableAccountException();
} }
if (messagesPendingSend(account)) { if (messagesPendingSend(account)) {
@ -3305,7 +3285,7 @@ public class MessagingController implements Runnable {
private void cancelNotification(int id) { private void cancelNotification(int id) {
NotificationManager notifMgr = NotificationManager notifMgr =
(NotificationManager) mApplication.getSystemService(Context.NOTIFICATION_SERVICE); (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notifMgr.cancel(id); notifMgr.cancel(id);
} }
@ -3328,9 +3308,9 @@ public class MessagingController implements Runnable {
} }
NotificationManager notifMgr = 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.setSmallIcon(R.drawable.ic_notify_check_mail);
builder.setWhen(System.currentTimeMillis()); builder.setWhen(System.currentTimeMillis());
builder.setOngoing(true); builder.setOngoing(true);
@ -3339,13 +3319,13 @@ public class MessagingController implements Runnable {
String accountName = (TextUtils.isEmpty(accountDescription)) ? String accountName = (TextUtils.isEmpty(accountDescription)) ?
account.getEmail() : 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)); 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()); builder.setContentText(account.getDescription());
TaskStackBuilder stack = buildMessageListBackStack(mApplication, account, TaskStackBuilder stack = buildMessageListBackStack(context, account,
account.getInboxFolderName()); account.getInboxFolderName());
builder.setContentIntent(stack.getPendingIntent(0, 0)); builder.setContentIntent(stack.getPendingIntent(0, 0));
builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
@ -3380,19 +3360,19 @@ public class MessagingController implements Runnable {
*/ */
private void notifySendFailed(Account account, Exception lastFailure, String openFolder) { private void notifySendFailed(Account account, Exception lastFailure, String openFolder) {
NotificationManager notifMgr = 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() builder.setSmallIcon(platformSupportsLockScreenNotifications()
? R.drawable.ic_notify_new_mail_vector ? R.drawable.ic_notify_new_mail_vector
: R.drawable.ic_notify_new_mail); : R.drawable.ic_notify_new_mail);
builder.setWhen(System.currentTimeMillis()); builder.setWhen(System.currentTimeMillis());
builder.setAutoCancel(true); builder.setAutoCancel(true);
builder.setTicker(mApplication.getString(R.string.send_failure_subject)); builder.setTicker(context.getString(R.string.send_failure_subject));
builder.setContentTitle(mApplication.getString(R.string.send_failure_subject)); builder.setContentTitle(context.getString(R.string.send_failure_subject));
builder.setContentText(getRootCauseMessage(lastFailure)); builder.setContentText(getRootCauseMessage(lastFailure));
TaskStackBuilder stack = buildFolderListBackStack(mApplication, account); TaskStackBuilder stack = buildFolderListBackStack(context, account);
builder.setContentIntent(stack.getPendingIntent(0, 0)); builder.setContentIntent(stack.getPendingIntent(0, 0));
builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
@ -3417,20 +3397,20 @@ public class MessagingController implements Runnable {
} }
final NotificationManager notifMgr = 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.setSmallIcon(R.drawable.ic_notify_check_mail);
builder.setWhen(System.currentTimeMillis()); builder.setWhen(System.currentTimeMillis());
builder.setOngoing(true); builder.setOngoing(true);
builder.setTicker(mApplication.getString( builder.setTicker(context.getString(
R.string.notification_bg_sync_ticker, account.getDescription(), folder.getName())); 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() + builder.setContentText(account.getDescription() +
mApplication.getString(R.string.notification_bg_title_separator) + context.getString(R.string.notification_bg_title_separator) +
folder.getName()); folder.getName());
TaskStackBuilder stack = buildMessageListBackStack(mApplication, account, TaskStackBuilder stack = buildMessageListBackStack(context, account,
account.getInboxFolderName()); account.getInboxFolderName());
builder.setContentIntent(stack.getPendingIntent(0, 0)); builder.setContentIntent(stack.getPendingIntent(0, 0));
builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
@ -3585,7 +3565,7 @@ public class MessagingController implements Runnable {
localFolder.moveMessages(Collections.singletonList(message), (LocalFolder) localStore.getFolder(account.getDraftsFolderName())); 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); addErrorMessage(account, "Failed to send message", e);
message.setFlag(Flag.X_SEND_FAILED, true); message.setFlag(Flag.X_SEND_FAILED, true);
Log.e(K9.LOG_TAG, "Failed to send message", e); 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, public AccountStats getSearchAccountStatsSynchronous(final SearchAccount searchAccount,
final MessagingListener listener) { final MessagingListener listener) {
Preferences preferences = Preferences.getPreferences(mApplication); Preferences preferences = Preferences.getPreferences(context);
LocalSearch search = searchAccount.getRelatedSearch(); LocalSearch search = searchAccount.getRelatedSearch();
// Collect accounts that belong to the search // 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 unreadMessageCount = 0;
int flaggedMessageCount = 0; int flaggedMessageCount = 0;
@ -5286,7 +5266,7 @@ public class MessagingController implements Runnable {
if (previousPusher != null) { if (previousPusher != null) {
previousPusher.stop(); previousPusher.stop();
} }
Preferences prefs = Preferences.getPreferences(mApplication); Preferences prefs = Preferences.getPreferences(context);
Account.FolderMode aDisplayMode = account.getFolderDisplayMode(); Account.FolderMode aDisplayMode = account.getFolderDisplayMode();
Account.FolderMode aPushMode = account.getFolderPushMode(); Account.FolderMode aPushMode = account.getFolderPushMode();
@ -5338,7 +5318,7 @@ public class MessagingController implements Runnable {
} }
if (!names.isEmpty()) { if (!names.isEmpty()) {
PushReceiver receiver = new MessagingControllerPushReceiver(mApplication, account, this); PushReceiver receiver = new MessagingControllerPushReceiver(context, account, this);
int maxPushFolders = account.getMaxPushFolders(); int maxPushFolders = account.getMaxPushFolders();
if (names.size() > maxPushFolders) { if (names.size() > maxPushFolders) {
@ -5422,7 +5402,7 @@ public class MessagingController implements Runnable {
Log.i(K9.LOG_TAG, "messagesArrived newCount = " + newCount + ", unread count = " + unreadMessageCount); Log.i(K9.LOG_TAG, "messagesArrived newCount = " + newCount + ", unread count = " + unreadMessageCount);
if (unreadMessageCount == 0) { if (unreadMessageCount == 0) {
notifyAccountCancel(mApplication, account); notifyAccountCancel(context, account);
} }
for (MessagingListener l : getListeners()) { for (MessagingListener l : getListeners()) {

View File

@ -1,6 +1,5 @@
package com.fsck.k9.controller; package com.fsck.k9.controller;
import android.app.Application;
import android.content.Context; import android.content.Context;
import android.util.Log; import android.util.Log;
@ -21,12 +20,12 @@ import java.util.concurrent.CountDownLatch;
public class MessagingControllerPushReceiver implements PushReceiver { public class MessagingControllerPushReceiver implements PushReceiver {
final Account account; final Account account;
final MessagingController controller; 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; account = nAccount;
controller = nController; controller = nController;
mApplication = nApplication; this.context = context;
} }
public void messagesFlagsChanged(Folder folder, public void messagesFlagsChanged(Folder folder,
@ -71,13 +70,13 @@ public class MessagingControllerPushReceiver implements PushReceiver {
@Override @Override
public void sleep(TracingWakeLock wakeLock, long millis) { 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) { public void pushError(String errorMessage, Exception e) {
String errMess = errorMessage; String errMess = errorMessage;
controller.notifyUserIfCertificateProblem(mApplication, e, account, true); controller.notifyUserIfCertificateProblem(context, e, account, true);
if (errMess == null && e != null) { if (errMess == null && e != null) {
errMess = e.getMessage(); errMess = e.getMessage();
} }
@ -110,7 +109,7 @@ public class MessagingControllerPushReceiver implements PushReceiver {
@Override @Override
public Context getContext() { public Context getContext() {
return mApplication; return context;
} }
} }

View File

@ -1,7 +1,6 @@
package com.fsck.k9.helper; package com.fsck.k9.helper;
import android.app.Application;
import android.content.Context; import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
import android.net.ConnectivityManager; import android.net.ConnectivityManager;
@ -421,12 +420,10 @@ public class Utility {
/** /**
* Check to see if we have network connectivity. * 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 = final ConnectivityManager connectivityManager =
(ConnectivityManager) app.getSystemService(Context.CONNECTIVITY_SERVICE); (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null) { if (connectivityManager == null) {
return false; return false;
} }

View File

@ -4,7 +4,7 @@ import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.InputStream; import java.io.InputStream;
import android.app.Application; import android.content.Context;
import android.net.Uri; import android.net.Uri;
import com.fsck.k9.mail.MessagingException; 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. * An attachment whose contents are loaded from an URI.
*/ */
public class LocalAttachmentBody extends BinaryAttachmentBody { public class LocalAttachmentBody extends BinaryAttachmentBody {
private Application mApplication; private Context context;
private Uri mUri; private Uri mUri;
public LocalAttachmentBody(Uri uri, Application application) { public LocalAttachmentBody(Uri uri, Context context) {
mApplication = application; this.context = context;
mUri = uri; mUri = uri;
} }
@Override @Override
public InputStream getInputStream() throws MessagingException { public InputStream getInputStream() throws MessagingException {
try { try {
return mApplication.getContentResolver().openInputStream(mUri); return context.getContentResolver().openInputStream(mUri);
} catch (FileNotFoundException fnfe) { } catch (FileNotFoundException fnfe) {
/* /*
* Since it's completely normal for us to try to serve up attachments that * Since it's completely normal for us to try to serve up attachments that

View File

@ -5,7 +5,7 @@ import java.io.OutputStream;
import org.apache.james.mime4j.util.MimeUtil; import org.apache.james.mime4j.util.MimeUtil;
import android.app.Application; import android.content.Context;
import android.net.Uri; import android.net.Uri;
import com.fsck.k9.mail.CompositeBody; import com.fsck.k9.mail.CompositeBody;
@ -17,8 +17,8 @@ import com.fsck.k9.mail.MessagingException;
*/ */
class LocalAttachmentMessageBody extends LocalAttachmentBody implements CompositeBody { class LocalAttachmentMessageBody extends LocalAttachmentBody implements CompositeBody {
public LocalAttachmentMessageBody(Uri uri, Application application) { public LocalAttachmentMessageBody(Uri uri, Context context) {
super(uri, application); super(uri, context);
} }
@Override @Override

View File

@ -737,11 +737,11 @@ public class LocalFolder extends Folder<LocalMessage> implements Serializable {
if (MimeUtil.isMessage(type)) { if (MimeUtil.isMessage(type)) {
body = new LocalAttachmentMessageBody( body = new LocalAttachmentMessageBody(
Uri.parse(contentUri), Uri.parse(contentUri),
LocalFolder.this.localStore.mApplication); LocalFolder.this.localStore.context);
} else { } else {
body = new LocalAttachmentBody( body = new LocalAttachmentBody(
Uri.parse(contentUri), Uri.parse(contentUri),
LocalFolder.this.localStore.mApplication); LocalFolder.this.localStore.context);
} }
} }
@ -1306,7 +1306,7 @@ public class LocalFolder extends Folder<LocalMessage> implements Serializable {
attachments = container.attachments; attachments = container.attachments;
} else { } else {
ViewableContainer container = ViewableContainer container =
LocalMessageExtractor.extractTextAndAttachments(LocalFolder.this.localStore.mApplication, message); LocalMessageExtractor.extractTextAndAttachments(LocalFolder.this.localStore.context, message);
attachments = container.attachments; attachments = container.attachments;
text = container.text; text = container.text;
@ -1412,7 +1412,7 @@ public class LocalFolder extends Folder<LocalMessage> implements Serializable {
message.buildMimeRepresentation(); message.buildMimeRepresentation();
ViewableContainer container = ViewableContainer container =
LocalMessageExtractor.extractTextAndAttachments(LocalFolder.this.localStore.mApplication, message); LocalMessageExtractor.extractTextAndAttachments(LocalFolder.this.localStore.context, message);
List<Part> attachments = container.attachments; List<Part> attachments = container.attachments;
String text = container.text; String text = container.text;
@ -1548,7 +1548,7 @@ public class LocalFolder extends Folder<LocalMessage> implements Serializable {
attachmentId = ((LocalAttachmentBodyPart) attachment).getAttachmentId(); 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) { if (attachment.getBody() != null) {
Body body = attachment.getBody(); Body body = attachment.getBody();
if (body instanceof LocalAttachmentBody) { if (body instanceof LocalAttachmentBody) {
@ -1653,10 +1653,10 @@ public class LocalFolder extends Folder<LocalMessage> implements Serializable {
attachmentId); attachmentId);
if (MimeUtil.isMessage(attachment.getMimeType())) { if (MimeUtil.isMessage(attachment.getMimeType())) {
attachment.setBody(new LocalAttachmentMessageBody( attachment.setBody(new LocalAttachmentMessageBody(
contentUri, LocalFolder.this.localStore.mApplication)); contentUri, LocalFolder.this.localStore.context));
} else { } else {
attachment.setBody(new LocalAttachmentBody( attachment.setBody(new LocalAttachmentBody(
contentUri, LocalFolder.this.localStore.mApplication)); contentUri, LocalFolder.this.localStore.context));
} }
ContentValues cv = new ContentValues(); ContentValues cv = new ContentValues();
cv.put("content_uri", contentUri != null ? contentUri.toString() : null); cv.put("content_uri", contentUri != null ? contentUri.toString() : null);
@ -1891,14 +1891,14 @@ public class LocalFolder extends Folder<LocalMessage> implements Serializable {
Cursor attachmentsCursor = null; Cursor attachmentsCursor = null;
try { try {
String accountUuid = getAccountUuid(); String accountUuid = getAccountUuid();
Context context = LocalFolder.this.localStore.mApplication; Context context = LocalFolder.this.localStore.context;
// Get attachment IDs // Get attachment IDs
String[] whereArgs = new String[] { Long.toString(messageId) }; String[] whereArgs = new String[] { Long.toString(messageId) };
attachmentsCursor = db.query("attachments", new String[] { "id" }, attachmentsCursor = db.query("attachments", new String[] { "id" },
"message_id = ?", whereArgs, null, null, null); "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()); .getAttachmentDirectory(LocalFolder.this.localStore.uUid, LocalFolder.this.localStore.database.getStorageProviderId());
while (attachmentsCursor.moveToNext()) { while (attachmentsCursor.moveToNext()) {

View File

@ -145,7 +145,7 @@ public class LocalStore extends Store implements Serializable {
protected String uUid = null; protected String uUid = null;
final Application mApplication; final Context context;
LockableDatabase database; LockableDatabase database;
@ -154,17 +154,17 @@ public class LocalStore extends Store implements Serializable {
/** /**
* local://localhost/path/to/database/uuid.db * 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 account
* @param application * @param context
* @throws UnavailableStorageException if not {@link StorageProvider#isReady(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; mAccount = account;
database = new LockableDatabase(application, account.getUuid(), new StoreSchemaDefinition(this)); database = new LockableDatabase(context, account.getUuid(), new StoreSchemaDefinition(this));
mApplication = application; this.context = context;
mContentResolver = application.getContentResolver(); mContentResolver = context.getContentResolver();
database.setStorageProviderId(account.getLocalStorageProviderId()); database.setStorageProviderId(account.getLocalStorageProviderId());
uUid = account.getUuid(); uUid = account.getUuid();
@ -227,12 +227,12 @@ public class LocalStore extends Store implements Serializable {
} }
protected SharedPreferences getPreferences() { protected SharedPreferences getPreferences() {
return Preferences.getPreferences(mApplication).getPreferences(); return Preferences.getPreferences(context).getPreferences();
} }
public long getSize() throws MessagingException { public long getSize() throws MessagingException {
final StorageManager storageManager = StorageManager.getInstance(mApplication); final StorageManager storageManager = StorageManager.getInstance(context);
final File attachmentDirectory = storageManager.getAttachmentDirectory(uUid, final File attachmentDirectory = storageManager.getAttachmentDirectory(uUid,
database.getStorageProviderId()); database.getStorageProviderId());
@ -421,7 +421,7 @@ public class LocalStore extends Store implements Serializable {
cv.putNull("content_uri"); cv.putNull("content_uri");
db.update("attachments", cv, null, null); 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(); File[] files = storageManager.getAttachmentDirectory(uUid, database.getStorageProviderId()).listFiles();
for (File file : files) { for (File file : files) {
if (file.exists()) { if (file.exists()) {

View File

@ -6,7 +6,6 @@ import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock;
import android.annotation.TargetApi; import android.annotation.TargetApi;
import android.app.Application;
import android.content.Context; import android.content.Context;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteException;
@ -128,7 +127,7 @@ public class LockableDatabase {
private final StorageListener mStorageListener = new StorageListener(); private final StorageListener mStorageListener = new StorageListener();
private Application mApplication; private Context context;
/** /**
* {@link ThreadLocal} to check whether a DB transaction is occuring in the * {@link ThreadLocal} to check whether a DB transaction is occuring in the
@ -143,15 +142,15 @@ public class LockableDatabase {
private String uUid; private String uUid;
/** /**
* @param application * @param context
* Never <code>null</code>. * Never <code>null</code>.
* @param uUid * @param uUid
* Never <code>null</code>. * Never <code>null</code>.
* @param schemaDefinition * @param schemaDefinition
* Never <code>null</code * Never <code>null</code
*/ */
public LockableDatabase(final Application application, final String uUid, final SchemaDefinition schemaDefinition) { public LockableDatabase(final Context context, final String uUid, final SchemaDefinition schemaDefinition) {
this.mApplication = application; this.context = context;
this.uUid = uUid; this.uUid = uUid;
this.mSchemaDefinition = schemaDefinition; this.mSchemaDefinition = schemaDefinition;
} }
@ -165,7 +164,7 @@ public class LockableDatabase {
} }
private StorageManager getStorageManager() { private StorageManager getStorageManager() {
return StorageManager.getInstance(mApplication); return StorageManager.getInstance(context);
} }
/** /**
@ -364,7 +363,7 @@ public class LockableDatabase {
} finally { } finally {
unlockWrite(); unlockWrite();
} }
StorageManager.getInstance(mApplication).addListener(mStorageListener); StorageManager.getInstance(context).addListener(mStorageListener);
} }
/** /**
@ -395,7 +394,7 @@ public class LockableDatabase {
private void doOpenOrCreateDb(final File databaseFile) { private void doOpenOrCreateDb(final File databaseFile) {
if (StorageManager.InternalStorageProvider.ID.equals(mStorageProviderId)) { if (StorageManager.InternalStorageProvider.ID.equals(mStorageProviderId)) {
// internal storage // internal storage
mDb = mApplication.openOrCreateDatabase(databaseFile.getName(), Context.MODE_PRIVATE, mDb = context.openOrCreateDatabase(databaseFile.getName(), Context.MODE_PRIVATE,
null); null);
} else { } else {
// external storage // external storage

View File

@ -12,7 +12,6 @@ import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock;
import android.app.Application;
import android.content.Context; import android.content.Context;
import android.os.Build; import android.os.Build;
import android.os.Environment; import android.os.Environment;
@ -486,7 +485,7 @@ public class StorageManager {
*/ */
private final Map<StorageProvider, SynchronizationAid> mProviderLocks = new IdentityHashMap<StorageProvider, SynchronizationAid>(); private final Map<StorageProvider, SynchronizationAid> mProviderLocks = new IdentityHashMap<StorageProvider, SynchronizationAid>();
protected final Application mApplication; protected final Context context;
/** /**
* Listener to be notified for storage related events. * Listener to be notified for storage related events.
@ -495,9 +494,9 @@ public class StorageManager {
private static transient StorageManager instance; private static transient StorageManager instance;
public static synchronized StorageManager getInstance(final Application application) { public static synchronized StorageManager getInstance(final Context context) {
if (instance == null) { if (instance == null) {
instance = new StorageManager(application); instance = new StorageManager(context);
} }
return instance; return instance;
} }
@ -518,17 +517,17 @@ public class StorageManager {
} }
/** /**
* @param application * @param context
* Never <code>null</code>. * Never <code>null</code>.
* @throws NullPointerException * @throws NullPointerException
* If <tt>application</tt> is <code>null</code>. * If <tt>context</tt> is <code>null</code>.
*/ */
protected StorageManager(final Application application) throws NullPointerException { protected StorageManager(final Context context) throws NullPointerException {
if (application == null) { if (context == null) {
throw new NullPointerException("No application instance given"); throw new NullPointerException("No Context given");
} }
mApplication = application; this.context = context;
/* /*
* 20101113/fiouzy: * 20101113/fiouzy:
@ -547,10 +546,10 @@ public class StorageManager {
new ExternalStorageProvider()); new ExternalStorageProvider());
for (final StorageProvider provider : allProviders) { for (final StorageProvider provider : allProviders) {
// check for provider compatibility // check for provider compatibility
if (provider.isSupported(mApplication)) { if (provider.isSupported(context)) {
// provider is compatible! proceeding // provider is compatible! proceeding
provider.init(application); provider.init(context);
mProviders.put(provider.getId(), provider); mProviders.put(provider.getId(), provider);
mProviderLocks.put(provider, new SynchronizationAid()); mProviderLocks.put(provider, new SynchronizationAid());
} }
@ -585,7 +584,7 @@ public class StorageManager {
public File getDatabase(final String dbName, final String providerId) { public File getDatabase(final String dbName, final String providerId) {
StorageProvider provider = getProvider(providerId); StorageProvider provider = getProvider(providerId);
// TODO fallback to internal storage if no provider // 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) { public File getAttachmentDirectory(final String dbName, final String providerId) {
StorageProvider provider = getProvider(providerId); StorageProvider provider = getProvider(providerId);
// TODO fallback to internal storage if no provider // 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"); Log.w(K9.LOG_TAG, "Storage-Provider \"" + providerId + "\" does not exist");
return false; return false;
} }
return provider.isReady(mApplication); return provider.isReady(context);
} }
/** /**
@ -624,7 +623,7 @@ public class StorageManager {
public Map<String, String> getAvailableProviders() { public Map<String, String> getAvailableProviders() {
final Map<String, String> result = new LinkedHashMap<String, String>(); final Map<String, String> result = new LinkedHashMap<String, String>();
for (final Map.Entry<String, StorageProvider> entry : mProviders.entrySet()) { for (final Map.Entry<String, StorageProvider> entry : mProviders.entrySet()) {
result.put(entry.getKey(), entry.getValue().getName(mApplication)); result.put(entry.getKey(), entry.getValue().getName(context));
} }
return result; return result;
} }
@ -698,7 +697,7 @@ public class StorageManager {
*/ */
protected StorageProvider resolveProvider(final String path) { protected StorageProvider resolveProvider(final String path) {
for (final StorageProvider provider : mProviders.values()) { for (final StorageProvider provider : mProviders.values()) {
if (path.equals(provider.getRoot(mApplication).getAbsolutePath())) { if (path.equals(provider.getRoot(context).getAbsolutePath())) {
return provider; return provider;
} }
} }
@ -738,7 +737,7 @@ public class StorageManager {
sync.readLock.unlock(); sync.readLock.unlock();
} }
throw new UnavailableStorageException("StorageProvider is unmounting"); throw new UnavailableStorageException("StorageProvider is unmounting");
} else if (locked && !provider.isReady(mApplication)) { } else if (locked && !provider.isReady(context)) {
sync.readLock.unlock(); sync.readLock.unlock();
throw new UnavailableStorageException("StorageProvider not ready"); throw new UnavailableStorageException("StorageProvider not ready");
} }

View File

@ -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", Log.i(K9.LOG_TAG, String.format(Locale.US, "Upgrading database from version %d to version %d",
db.getVersion(), LocalStore.DB_VERSION)); db.getVersion(), LocalStore.DB_VERSION));
AttachmentProvider.clear(this.localStore.mApplication); AttachmentProvider.clear(this.localStore.context);
db.beginTransaction(); db.beginTransaction();
try { try {
@ -595,4 +595,4 @@ class StoreSchemaDefinition implements LockableDatabase.SchemaDefinition {
new Object[] { integrate, inTopGroup, syncClass, pushClass, displayClass, id }); new Object[] { integrate, inTopGroup, syncClass, pushClass, displayClass, id });
} }
} }