recheck google events every 4 hours if the app isnt launched meanwhile

This commit is contained in:
tibbi 2017-07-26 20:15:37 +02:00
parent ccede052a8
commit 891bae5378
8 changed files with 76 additions and 29 deletions

View File

@ -135,6 +135,8 @@
</intent-filter>
</receiver>
<receiver android:name=".receivers.GoogleSyncReceiver"/>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.simplemobiletools.calendar.fileprovider"

View File

@ -91,8 +91,9 @@ class MainActivity : SimpleActivity(), NavigationListener {
}
if (isGoogleSyncActive()) {
FetchGoogleEventsTask(this, googleSyncListener).execute()
FetchGoogleEventsTask(applicationContext, googleSyncListener).execute()
}
scheduleGoogleSync(isGoogleSyncActive())
}
override fun onResume() {

View File

@ -14,6 +14,7 @@ import android.support.v4.app.ActivityCompat
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException
import com.google.api.client.util.ExponentialBackOff
import com.google.api.services.calendar.CalendarScopes
import com.simplemobiletools.calendar.R
@ -48,6 +49,7 @@ class SettingsActivity : SimpleActivity() {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
res = resources
setupGoogleSync()
}
override fun onResume() {
@ -58,7 +60,6 @@ class SettingsActivity : SimpleActivity() {
setupHourFormat()
setupSundayFirst()
setupWeekNumbers()
setupGoogleSync()
setupWeeklyStart()
setupWeeklyEnd()
setupVibrate()
@ -130,7 +131,6 @@ class SettingsActivity : SimpleActivity() {
private fun toggleGoogleSync() {
settings_google_sync.toggle()
config.googleSync = settings_google_sync.isChecked
if (settings_google_sync.isChecked) {
tryEnablingSync()
@ -331,7 +331,9 @@ class SettingsActivity : SimpleActivity() {
} else if (config.syncAccountName.isEmpty()) {
showAccountChooser()
} else {
FetchGoogleEventsTask(this).execute()
Thread({
fetchEventsIfHasPermissions()
}).start()
}
}
@ -349,6 +351,23 @@ class SettingsActivity : SimpleActivity() {
}
}
private fun fetchEventsIfHasPermissions() {
try {
getGoogleSyncService().colors().get().execute() // just checking if we have the permission for fetching user data
config.googleSync = true
runOnUiThread {
settings_google_sync.isChecked = true
}
FetchGoogleEventsTask(applicationContext).execute()
} catch (e: Exception) {
if (e is UserRecoverableAuthIOException) {
startActivityForResult(e.intent, REQUEST_AUTHORIZATION)
} else {
toast(R.string.unknown_error_occurred)
}
}
}
private fun disableGoogleSync() {
settings_google_sync.isChecked = false
config.googleSync = false

View File

@ -1,18 +1,13 @@
package com.simplemobiletools.calendar.asynctasks
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.os.AsyncTask
import android.util.SparseIntArray
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.reflect.TypeToken
import com.simplemobiletools.calendar.activities.SettingsActivity
import com.simplemobiletools.calendar.extensions.config
import com.simplemobiletools.calendar.extensions.dbHelper
import com.simplemobiletools.calendar.extensions.getGoogleSyncService
import com.simplemobiletools.calendar.extensions.seconds
import com.simplemobiletools.calendar.extensions.*
import com.simplemobiletools.calendar.helpers.*
import com.simplemobiletools.calendar.interfaces.GoogleSyncListener
import com.simplemobiletools.calendar.models.*
@ -20,23 +15,24 @@ import org.joda.time.DateTime
import java.util.*
// more info about event fields at https://developers.google.com/google-apps/calendar/v3/reference/events/insert
class FetchGoogleEventsTask(val activity: Activity, val googleSyncListener: GoogleSyncListener? = null) : AsyncTask<Void, Void, String>() {
class FetchGoogleEventsTask(val context: Context, val googleSyncListener: GoogleSyncListener? = null) : AsyncTask<Void, Void, String>() {
private val ITEMS = "items"
private val OVERRIDES = "overrides"
private val NEXT_PAGE_TOKEN = "nextPageToken"
private var lastError: Exception? = null
private var dbHelper = activity.dbHelper
private var dbHelper = context.dbHelper
private var eventTypes = ArrayList<EventType>()
private var eventColors = SparseIntArray()
private var service = activity.getGoogleSyncService()
private var service = context.getGoogleSyncService()
override fun doInBackground(vararg params: Void): String {
if (!context.isGoogleSyncActive())
return ""
try {
getColors()
getDataFromApi()
} catch (e: Exception) {
lastError = e
cancel(true)
}
googleSyncListener?.syncCompleted()
@ -53,6 +49,7 @@ class FetchGoogleEventsTask(val activity: Activity, val googleSyncListener: Goog
private fun getDataFromApi() {
var currToken = ""
while (true) {
service.colors().get().execute()
val events = service.events().list(PRIMARY)
.setPageToken(currToken)
.execute()
@ -78,7 +75,7 @@ class FetchGoogleEventsTask(val activity: Activity, val googleSyncListener: Goog
val remoteImportIds = ArrayList<String>()
var updateEvent = false
var eventId = 0
val importIDs = activity.dbHelper.getImportIds()
val importIDs = context.dbHelper.getImportIds()
val token = object : TypeToken<List<GoogleEvent>>() {}.type
val googleEvents = Gson().fromJson<ArrayList<GoogleEvent>>(json, token) ?: ArrayList<GoogleEvent>(8)
for (googleEvent in googleEvents) {
@ -152,7 +149,7 @@ class FetchGoogleEventsTask(val activity: Activity, val googleSyncListener: Goog
}
if (eventTypeId == -1) {
val newColor = if (eventColors[colorId] != 0) eventColors[colorId] else activity.config.primaryColor
val newColor = if (eventColors[colorId] != 0) eventColors[colorId] else context.config.primaryColor
val newEventType = EventType(0, eventType, newColor)
eventTypeId = dbHelper.insertEventType(newEventType)
eventTypes.add(newEventType)
@ -182,12 +179,4 @@ class FetchGoogleEventsTask(val activity: Activity, val googleSyncListener: Goog
}
return reminderMinutes
}
override fun onCancelled() {
if (lastError != null) {
if (lastError is UserRecoverableAuthIOException) {
activity.startActivityForResult((lastError as UserRecoverableAuthIOException).intent, SettingsActivity.REQUEST_AUTHORIZATION)
}
}
}
}

View File

@ -24,6 +24,7 @@ import com.simplemobiletools.calendar.activities.EventActivity
import com.simplemobiletools.calendar.helpers.*
import com.simplemobiletools.calendar.helpers.Formatter
import com.simplemobiletools.calendar.models.Event
import com.simplemobiletools.calendar.receivers.GoogleSyncReceiver
import com.simplemobiletools.calendar.receivers.NotificationReceiver
import com.simplemobiletools.calendar.services.SnoozeService
import com.simplemobiletools.commons.extensions.getContrastColor
@ -245,6 +246,19 @@ fun Context.isOnline(): Boolean {
return connectivityManager.activeNetworkInfo != null
}
fun Context.scheduleGoogleSync(activate: Boolean) {
val syncIntent = Intent(this, GoogleSyncReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(this, 0, syncIntent, PendingIntent.FLAG_CANCEL_CURRENT)
val alarm = getSystemService(Context.ALARM_SERVICE) as AlarmManager
if (activate) {
val syncCheckInterval = 4 * AlarmManager.INTERVAL_HOUR
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + syncCheckInterval, syncCheckInterval, pendingIntent)
} else {
alarm.cancel(pendingIntent)
}
}
fun Context.getNewEventTimestampFromCode(dayCode: String) = Formatter.getLocalDateTimeFromCode(dayCode).withTime(13, 0, 0, 0).seconds()
fun Context.getCurrentOffset() = SimpleDateFormat("Z", Locale.getDefault()).format(Date())

View File

@ -4,6 +4,7 @@ import android.content.Context
import android.media.RingtoneManager
import android.text.format.DateFormat
import com.simplemobiletools.calendar.R
import com.simplemobiletools.calendar.extensions.scheduleGoogleSync
import com.simplemobiletools.commons.helpers.BaseConfig
import java.util.*
@ -72,7 +73,10 @@ class Config(context: Context) : BaseConfig(context) {
var googleSync: Boolean
get() = prefs.getBoolean(GOOGLE_SYNC, false)
set(googleSync) = prefs.edit().putBoolean(GOOGLE_SYNC, googleSync).apply()
set(googleSync) {
context.scheduleGoogleSync(googleSync)
prefs.edit().putBoolean(GOOGLE_SYNC, googleSync).apply()
}
var syncAccountName: String
get() = prefs.getString(SYNC_ACCOUNT_NAME, "")

View File

@ -3,13 +3,18 @@ package com.simplemobiletools.calendar.receivers
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.simplemobiletools.calendar.extensions.isGoogleSyncActive
import com.simplemobiletools.calendar.extensions.notifyRunningEvents
import com.simplemobiletools.calendar.extensions.scheduleAllEvents
import com.simplemobiletools.calendar.extensions.scheduleGoogleSync
class BootCompletedReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, arg1: Intent) {
context.scheduleAllEvents()
context.notifyRunningEvents()
context.apply {
scheduleAllEvents()
notifyRunningEvents()
scheduleGoogleSync(isGoogleSyncActive())
}
}
}

View File

@ -0,0 +1,13 @@
package com.simplemobiletools.calendar.receivers
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.simplemobiletools.calendar.asynctasks.FetchGoogleEventsTask
class GoogleSyncReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, arg1: Intent) {
FetchGoogleEventsTask(context).execute()
}
}