Add InjectingService

pull/143/head
Alex Baker 11 years ago
parent de9e68fba0
commit c10a704ea8

@ -1,163 +0,0 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.sync;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import com.todoroo.andlib.service.ContextManager;
import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.andlib.utility.Preferences;
import com.todoroo.astrid.api.AstridApiConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Performs synchronization service logic in background service to avoid
* ANR (application not responding) messages.
* <p>
* Starting this service
* schedules a repeating alarm which handles
* synchronization with your serv
*
* @author Tim Su
*
*/
abstract public class SyncV2BackgroundService extends Service {
private static final Logger log = LoggerFactory.getLogger(SyncV2BackgroundService.class);
/** Minimum time before an auto-sync */
private static final long AUTO_SYNC_MIN_OFFSET = 5*60*1000L;
abstract protected SyncV2Provider getSyncProvider();
abstract protected SyncProviderUtilities getSyncUtilities();
private final AtomicBoolean started = new AtomicBoolean(false);
/** Receive the alarm - start the synchronize service! */
@Override
public void onStart(Intent intent, int startId) {
try {
if(intent != null && !started.getAndSet(true)) {
startSynchronization(this);
}
} catch (Exception e) {
log.error("{}-bg-sync", getSyncUtilities().getIdentifier(), e);
}
}
/** Start the actual synchronization */
private void startSynchronization(final Context context) {
if(context == null || context.getResources() == null) {
return;
}
ContextManager.setContext(context);
if(!getSyncUtilities().isLoggedIn()) {
return;
}
SyncV2Provider provider = getSyncProvider();
if (provider.isActive()) {
provider.synchronizeActiveTasks(false, new SyncResultCallbackAdapter() {
@Override
public void finished() {
getSyncUtilities().recordSuccessfulSync();
context.sendBroadcast(new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH));
}
});
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
// --- alarm management
/**
* Schedules repeating alarm for auto-synchronization
*/
public void scheduleService() {
int syncFrequencySeconds = 0;
try {
syncFrequencySeconds = Preferences.getIntegerFromString(
getSyncUtilities().getSyncIntervalKey(), -1);
} catch(ClassCastException e) {
Preferences.setStringFromInteger(getSyncUtilities().getSyncIntervalKey(), 0);
}
Context context = ContextManager.getContext();
if(syncFrequencySeconds <= 0) {
unscheduleService(context);
return;
}
// figure out synchronization frequency
long interval = 1000L * syncFrequencySeconds;
long offset = computeNextSyncOffset(interval);
// give a little padding
offset = Math.max(offset, AUTO_SYNC_MIN_OFFSET);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(context, getSyncUtilities().getSyncIntervalKey(),
createAlarmIntent(context), PendingIntent.FLAG_UPDATE_CURRENT);
Log.i("Astrid", "Autosync set for " + offset / 1000 //$NON-NLS-1$ //$NON-NLS-2$
+ " seconds repeating every " + syncFrequencySeconds); //$NON-NLS-1$
// cancel all existing
am.cancel(pendingIntent);
// schedule new
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + offset,
interval, pendingIntent);
}
/**
* Removes repeating alarm for auto-synchronization
*/
private void unscheduleService(Context context) {
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(context, getSyncUtilities().getSyncIntervalKey(),
createAlarmIntent(context), PendingIntent.FLAG_UPDATE_CURRENT);
am.cancel(pendingIntent);
}
/** Create the alarm intent */
private Intent createAlarmIntent(Context context) {
return new Intent(context, getClass());
}
// --- utility methods
private long computeNextSyncOffset(long interval) {
// figure out last synchronize time
long lastSyncDate = getSyncUtilities().getLastSyncDate();
// if user never synchronized, give them a full offset period before bg sync
if(lastSyncDate != 0) {
return Math.max(0, lastSyncDate + interval - DateUtilities.now());
} else {
return interval;
}
}
}

@ -5,28 +5,151 @@
*/
package com.todoroo.astrid.gtasks;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.service.DependencyInjectionService;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import com.todoroo.andlib.service.ContextManager;
import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.andlib.utility.Preferences;
import com.todoroo.astrid.api.AstridApiConstants;
import com.todoroo.astrid.gtasks.sync.GtasksSyncV2Provider;
import com.todoroo.astrid.sync.SyncProviderUtilities;
import com.todoroo.astrid.sync.SyncV2BackgroundService;
import com.todoroo.astrid.sync.SyncResultCallbackAdapter;
import com.todoroo.astrid.sync.SyncV2Provider;
public class GtasksBackgroundService extends SyncV2BackgroundService {
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tasks.injection.InjectingService;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.inject.Inject;
public class GtasksBackgroundService extends InjectingService {
private static final Logger log = LoggerFactory.getLogger(GtasksBackgroundService.class);
@Autowired private GtasksPreferenceService gtasksPreferenceService;
@Autowired private GtasksSyncV2Provider gtasksSyncV2Provider;
@Inject GtasksPreferenceService gtasksPreferenceService;
@Inject GtasksSyncV2Provider gtasksSyncV2Provider;
/** Minimum time before an auto-sync */
private static final long AUTO_SYNC_MIN_OFFSET = 5*60*1000L;
private final AtomicBoolean started = new AtomicBoolean(false);
/** Receive the alarm - start the synchronize service! */
@Override
protected SyncV2Provider getSyncProvider() {
return gtasksSyncV2Provider;
public void onStart(Intent intent, int startId) {
try {
if(intent != null && !started.getAndSet(true)) {
startSynchronization(this);
}
} catch (Exception e) {
log.error("{}-bg-sync", gtasksPreferenceService.getIdentifier(), e);
}
}
/** Start the actual synchronization */
private void startSynchronization(final Context context) {
if(context == null || context.getResources() == null) {
return;
}
ContextManager.setContext(context);
if(!gtasksPreferenceService.isLoggedIn()) {
return;
}
SyncV2Provider provider = gtasksSyncV2Provider;
if (provider.isActive()) {
provider.synchronizeActiveTasks(false, new SyncResultCallbackAdapter() {
@Override
public void finished() {
gtasksPreferenceService.recordSuccessfulSync();
context.sendBroadcast(new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH));
}
});
}
}
@Override
protected SyncProviderUtilities getSyncUtilities() {
if(gtasksPreferenceService == null) {
DependencyInjectionService.getInstance().inject(this);
public IBinder onBind(Intent intent) {
return null;
}
// --- alarm management
/**
* Schedules repeating alarm for auto-synchronization
*/
public void scheduleService() {
int syncFrequencySeconds = 0;
try {
syncFrequencySeconds = Preferences.getIntegerFromString(
gtasksPreferenceService.getSyncIntervalKey(), -1);
} catch(ClassCastException e) {
Preferences.setStringFromInteger(gtasksPreferenceService.getSyncIntervalKey(), 0);
}
return gtasksPreferenceService;
Context context = ContextManager.getContext();
if(syncFrequencySeconds <= 0) {
unscheduleService(context);
return;
}
// figure out synchronization frequency
long interval = 1000L * syncFrequencySeconds;
long offset = computeNextSyncOffset(interval);
// give a little padding
offset = Math.max(offset, AUTO_SYNC_MIN_OFFSET);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(context, gtasksPreferenceService.getSyncIntervalKey(),
createAlarmIntent(context), PendingIntent.FLAG_UPDATE_CURRENT);
Log.i("Astrid", "Autosync set for " + offset / 1000 //$NON-NLS-1$ //$NON-NLS-2$
+ " seconds repeating every " + syncFrequencySeconds); //$NON-NLS-1$
// cancel all existing
am.cancel(pendingIntent);
// schedule new
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + offset,
interval, pendingIntent);
}
/**
* Removes repeating alarm for auto-synchronization
*/
private void unscheduleService(Context context) {
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(context, gtasksPreferenceService.getSyncIntervalKey(),
createAlarmIntent(context), PendingIntent.FLAG_UPDATE_CURRENT);
am.cancel(pendingIntent);
}
/** Create the alarm intent */
private Intent createAlarmIntent(Context context) {
return new Intent(context, getClass());
}
// --- utility methods
private long computeNextSyncOffset(long interval) {
// figure out last synchronize time
long lastSyncDate = gtasksPreferenceService.getLastSyncDate();
// if user never synchronized, give them a full offset period before bg sync
if(lastSyncDate != 0) {
return Math.max(0, lastSyncDate + interval - DateUtilities.now());
} else {
return interval;
}
}
}

@ -5,32 +5,28 @@
*/
package com.todoroo.astrid.reminders;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.service.ContextManager;
import com.todoroo.andlib.service.DependencyInjectionService;
import com.todoroo.andlib.utility.AndroidUtilities;
import com.todoroo.astrid.alarms.AlarmService;
import org.tasks.injection.InjectingService;
import org.tasks.scheduling.RefreshScheduler;
import javax.inject.Inject;
/**
* Schedules reminders in the background to prevent ANR's
*
* @author Tim Su
*
*/
public class ReminderSchedulingService extends Service {
@Autowired private RefreshScheduler refreshScheduler;
public class ReminderSchedulingService extends InjectingService {
public ReminderSchedulingService() {
DependencyInjectionService.getInstance().inject(this);
}
@Inject RefreshScheduler refreshScheduler;
/** Receive the alarm - start the synchronize service! */
@Override

@ -1,7 +1,6 @@
package com.todoroo.astrid.widget;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
@ -14,9 +13,7 @@ import android.view.View;
import android.widget.RemoteViews;
import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.service.ContextManager;
import com.todoroo.andlib.service.DependencyInjectionService;
import com.todoroo.andlib.utility.Preferences;
import com.todoroo.astrid.actfm.TagViewFragment;
import com.todoroo.astrid.api.Filter;
@ -25,7 +22,6 @@ import com.todoroo.astrid.core.SortHelper;
import com.todoroo.astrid.dao.Database;
import com.todoroo.astrid.dao.TaskListMetadataDao;
import com.todoroo.astrid.data.Task;
import com.todoroo.astrid.service.AstridDependencyInjector;
import com.todoroo.astrid.service.TagDataService;
import com.todoroo.astrid.service.TaskService;
import com.todoroo.astrid.service.ThemeService;
@ -34,27 +30,22 @@ import com.todoroo.astrid.utility.AstridPreferences;
import com.todoroo.astrid.utility.Constants;
import org.tasks.R;
import org.tasks.injection.InjectingService;
import org.tasks.widget.WidgetHelper;
public class WidgetUpdateService extends Service {
import javax.inject.Inject;
static {
AstridDependencyInjector.initialize();
}
public class WidgetUpdateService extends InjectingService {
private static final int NUM_VISIBLE_TASKS = 25;
public static final String EXTRA_WIDGET_ID = "widget_id"; //$NON-NLS-1$
@Autowired Database database;
@Autowired TaskService taskService;
@Autowired TaskListMetadataDao taskListMetadataDao;
@Autowired TagDataService tagDataService;
@Autowired WidgetHelper widgetHelper;
@Inject Database database;
@Inject TaskService taskService;
@Inject TaskListMetadataDao taskListMetadataDao;
@Inject TagDataService tagDataService;
@Inject WidgetHelper widgetHelper;
@Override
public void onStart(final Intent intent, int startId) {
@ -101,8 +92,6 @@ public class WidgetUpdateService extends Service {
}
public RemoteViews buildUpdate(Context context, int widgetId) {
DependencyInjectionService.getInstance().inject(this);
RemoteViews views = getThemedRemoteViews(context);
int numberOfTasks = NUM_VISIBLE_TASKS;

@ -0,0 +1,12 @@
package org.tasks.injection;
import android.app.Service;
public abstract class InjectingService extends Service {
@Override
public void onCreate() {
super.onCreate();
((Injector) getApplication()).inject(this, new ServiceModule());
}
}

@ -0,0 +1,14 @@
package org.tasks.injection;
import com.todoroo.astrid.gtasks.GtasksBackgroundService;
import com.todoroo.astrid.reminders.ReminderSchedulingService;
import dagger.Module;
@Module(library = true,
injects = {
GtasksBackgroundService.class,
ReminderSchedulingService.class
})
public class ServiceModule {
}
Loading…
Cancel
Save