From acff8c1f5c3e724cf835cbad46c2cf95fec0020c Mon Sep 17 00:00:00 2001 From: Felix Ableitner Date: Fri, 29 Dec 2017 14:07:05 +0900 Subject: [PATCH] Simplify code with anko library --- app/build.gradle | 1 + .../lite/activities/FolderBrowserActivity.kt | 3 +- .../lite/fragments/FoldersFragment.kt | 5 +- .../lite/library/DownloadFileTask.kt | 81 ++++++++++--------- .../syncthing/lite/library/InitLibraryTask.kt | 27 +++---- .../syncthing/lite/library/LibraryHandler.kt | 7 +- .../syncthing/lite/library/UpdateIndexTask.kt | 20 +++-- .../syncthing/lite/library/UploadFileTask.kt | 34 +++++--- 8 files changed, 94 insertions(+), 84 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index df1b712..ac615f7 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -25,6 +25,7 @@ android { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + compile "org.jetbrains.anko:anko-commons:0.10.4" kapt "com.android.databinding:compiler:$build_tools_version" implementation "com.android.support:appcompat-v7:$support_version" implementation "com.android.support:support-v4:$support_version" diff --git a/app/src/main/kotlin/net/syncthing/lite/activities/FolderBrowserActivity.kt b/app/src/main/kotlin/net/syncthing/lite/activities/FolderBrowserActivity.kt index 71eddb8..a2771c3 100644 --- a/app/src/main/kotlin/net/syncthing/lite/activities/FolderBrowserActivity.kt +++ b/app/src/main/kotlin/net/syncthing/lite/activities/FolderBrowserActivity.kt @@ -26,6 +26,7 @@ import net.syncthing.lite.databinding.ActivityFolderBrowserBinding import net.syncthing.lite.databinding.DialogLoadingBinding import net.syncthing.lite.library.DownloadFileTask import net.syncthing.lite.library.UploadFileTask +import org.jetbrains.anko.intentFor class FolderBrowserActivity : SyncthingActivity() { @@ -170,7 +171,7 @@ class FolderBrowserActivity : SyncthingActivity() { private fun showUploadHereDialog() { executeWithPermissions(Runnable { - startActivityForResult(Intent(this, FilePickerActivity::class.java), REQUEST_SELECT_UPLOAD_FILE) + startActivityForResult(intentFor(), REQUEST_SELECT_UPLOAD_FILE) }) } diff --git a/app/src/main/kotlin/net/syncthing/lite/fragments/FoldersFragment.kt b/app/src/main/kotlin/net/syncthing/lite/fragments/FoldersFragment.kt index de22a3e..15e8766 100644 --- a/app/src/main/kotlin/net/syncthing/lite/fragments/FoldersFragment.kt +++ b/app/src/main/kotlin/net/syncthing/lite/fragments/FoldersFragment.kt @@ -1,6 +1,5 @@ package net.syncthing.lite.fragments -import android.content.Intent import android.databinding.DataBindingUtil import android.os.Bundle import android.util.Log @@ -16,6 +15,7 @@ import net.syncthing.lite.activities.FolderBrowserActivity import net.syncthing.lite.adapters.FoldersListAdapter import net.syncthing.lite.databinding.FragmentFoldersBinding import org.apache.commons.lang3.tuple.Pair +import org.jetbrains.anko.intentFor import java.util.* class FoldersFragment : SyncthingFragment() { @@ -46,8 +46,7 @@ class FoldersFragment : SyncthingFragment() { binding.list.adapter = adapter binding.list.setOnItemClickListener { _, _, position, _ -> val folder = adapter.getItem(position)!!.left.folder - val intent = Intent(context, FolderBrowserActivity::class.java) - intent.putExtra(FolderBrowserActivity.EXTRA_FOLDER_NAME, folder) + val intent = context?.intentFor(FolderBrowserActivity.EXTRA_FOLDER_NAME to folder) startActivity(intent) } } diff --git a/app/src/main/kotlin/net/syncthing/lite/library/DownloadFileTask.kt b/app/src/main/kotlin/net/syncthing/lite/library/DownloadFileTask.kt index fcb11a3..e09f9d9 100644 --- a/app/src/main/kotlin/net/syncthing/lite/library/DownloadFileTask.kt +++ b/app/src/main/kotlin/net/syncthing/lite/library/DownloadFileTask.kt @@ -6,57 +6,57 @@ import android.content.Context import android.content.Intent import android.net.Uri import android.os.Environment -import android.os.Handler import android.support.annotation.StringRes import android.util.Log import android.webkit.MimeTypeMap -import android.widget.Toast import net.syncthing.java.bep.BlockPuller import net.syncthing.java.client.SyncthingClient import net.syncthing.java.core.beans.FileInfo import net.syncthing.lite.R import org.apache.commons.io.FileUtils import org.apache.commons.io.FilenameUtils +import org.jetbrains.anko.doAsync +import org.jetbrains.anko.newTask +import org.jetbrains.anko.toast +import org.jetbrains.anko.uiThread import java.io.File import java.io.IOException class DownloadFileTask(private val mContext: Context, private val mSyncthingClient: SyncthingClient, private val mFileInfo: FileInfo) { - private val mMainHandler: Handler = Handler() + private val TAG = "DownloadFileTask" private lateinit var progressDialog: ProgressDialog private var cancelled = false fun downloadFile() { showDialog() // TODO: can just pass FileInfo directly? - Thread { - mSyncthingClient.pullFile(mFileInfo.folder, mFileInfo.path, { observer -> - onProgress(observer) - try { - while (!observer.isCompleted) { - if (cancelled) - return@pullFile + mSyncthingClient.pullFile(mFileInfo.folder, mFileInfo.path, { observer -> + onProgress(observer) + try { + while (!observer.isCompleted) { + if (cancelled) + return@pullFile - observer.waitForProgressUpdate() - Log.i("pullFile", "download progress = " + observer.progressMessage) - onProgress(observer) - } - - val outputDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) - val outputFile = File(outputDir, mFileInfo.fileName) - FileUtils.copyInputStreamToFile(observer.inputStream, outputFile) - Log.i(TAG, "downloaded file = " + mFileInfo.path) - onComplete(outputFile) - } catch (e: IOException) { - onError(R.string.toast_file_download_failed) - Log.w(TAG, "Failed to download file " + mFileInfo, e) - } catch (e: InterruptedException) { - onError(R.string.toast_file_download_failed) - Log.w(TAG, "Failed to download file " + mFileInfo, e) + observer.waitForProgressUpdate() + Log.i("pullFile", "download progress = " + observer.progressMessage) + onProgress(observer) } - }) { onError(R.string.toast_file_download_failed) } - }.start() + + val outputDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + val outputFile = File(outputDir, mFileInfo.fileName) + FileUtils.copyInputStreamToFile(observer.inputStream, outputFile) + Log.i(TAG, "downloaded file = " + mFileInfo.path) + onComplete(outputFile) + } catch (e: IOException) { + onError(R.string.toast_file_download_failed) + Log.w(TAG, "Failed to download file " + mFileInfo, e) + } catch (e: InterruptedException) { + onError(R.string.toast_file_download_failed) + Log.w(TAG, "Failed to download file " + mFileInfo, e) + } + }) { onError(R.string.toast_file_download_failed) } } private fun showDialog() { @@ -70,10 +70,12 @@ class DownloadFileTask(private val mContext: Context, private val mSyncthingClie } private fun onProgress(fileDownloadObserver: BlockPuller.FileDownloadObserver) { - mMainHandler.post { - progressDialog.isIndeterminate = false - progressDialog.max = (mFileInfo.size as Long).toInt() - progressDialog.progress = (fileDownloadObserver.progress * mFileInfo.size!!).toInt() + doAsync { + uiThread { + progressDialog.isIndeterminate = false + progressDialog.max = (mFileInfo.size as Long).toInt() + progressDialog.progress = (fileDownloadObserver.progress * mFileInfo.size!!).toInt() + } } } @@ -85,7 +87,7 @@ class DownloadFileTask(private val mContext: Context, private val mSyncthingClie val mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(FilenameUtils.getExtension(file.name)) val intent = Intent(Intent.ACTION_VIEW) intent.setDataAndType(Uri.fromFile(file), mimeType) - intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK + intent.newTask() try { mContext.startActivity(intent) } catch (e: ActivityNotFoundException) { @@ -96,12 +98,11 @@ class DownloadFileTask(private val mContext: Context, private val mSyncthingClie } private fun onError(@StringRes error: Int) { - progressDialog.dismiss() - mMainHandler.post { Toast.makeText(mContext, error, Toast.LENGTH_SHORT).show() } - } - - companion object { - - private val TAG = "DownloadFileTask" + doAsync { + uiThread { + progressDialog.dismiss() + mContext.toast(error) + } + } } } \ No newline at end of file diff --git a/app/src/main/kotlin/net/syncthing/lite/library/InitLibraryTask.kt b/app/src/main/kotlin/net/syncthing/lite/library/InitLibraryTask.kt index af0a3d5..7af64ec 100644 --- a/app/src/main/kotlin/net/syncthing/lite/library/InitLibraryTask.kt +++ b/app/src/main/kotlin/net/syncthing/lite/library/InitLibraryTask.kt @@ -1,10 +1,11 @@ package net.syncthing.lite.library import android.content.Context -import android.os.Handler import android.preference.PreferenceManager import android.util.Log import net.syncthing.java.core.beans.FolderInfo +import org.jetbrains.anko.doAsync +import org.jetbrains.anko.uiThread import java.util.* class InitLibraryTask(private val context: Context, private val onLibraryLoaded: (LibraryHandler) -> Unit, @@ -12,10 +13,9 @@ class InitLibraryTask(private val context: Context, private val onLibraryLoaded: private val onIndexUpdateCompleteListener: () -> Unit) { private val TAG = "InitLibraryTask" - private val mainHandler = Handler() init { - Thread(Runnable { + doAsync { val libraryHandler = LibraryHandler() libraryHandler.init(context) libraryHandler.setOnIndexUpdatedListener(object : LibraryHandler.OnIndexUpdatedListener { @@ -27,18 +27,17 @@ class InitLibraryTask(private val context: Context, private val onLibraryLoaded: onIndexUpdateCompleteListener() } }) - - mainHandler.post { - //trigger update if last was more than 10mins ago - val lastUpdateMillis = PreferenceManager.getDefaultSharedPreferences(context) - .getLong(UpdateIndexTask.LAST_INDEX_UPDATE_TS_PREF, -1) - val lastUpdateTimeAgo = Date().time - lastUpdateMillis - if (lastUpdateMillis == -1L || lastUpdateTimeAgo > 10 * 60 * 1000) { - Log.d(TAG, "trigger index update, last was " + Date(lastUpdateMillis)) - UpdateIndexTask(context, libraryHandler.syncthingClient!!).updateIndex() - } + //trigger update if last was more than 10mins ago + val lastUpdateMillis = PreferenceManager.getDefaultSharedPreferences(context) + .getLong(UpdateIndexTask.LAST_INDEX_UPDATE_TS_PREF, -1) + val lastUpdateTimeAgo = Date().time - lastUpdateMillis + if (lastUpdateMillis == -1L || lastUpdateTimeAgo > 10 * 60 * 1000) { + Log.d(TAG, "trigger index update, last was " + Date(lastUpdateMillis)) + UpdateIndexTask(context, libraryHandler.syncthingClient!!).updateIndex() + } + uiThread { onLibraryLoaded(libraryHandler) } - }).start() + } } } \ No newline at end of file diff --git a/app/src/main/kotlin/net/syncthing/lite/library/LibraryHandler.kt b/app/src/main/kotlin/net/syncthing/lite/library/LibraryHandler.kt index dd49ed8..12c5463 100644 --- a/app/src/main/kotlin/net/syncthing/lite/library/LibraryHandler.kt +++ b/app/src/main/kotlin/net/syncthing/lite/library/LibraryHandler.kt @@ -16,6 +16,8 @@ import java.io.IOException class LibraryHandler { + private val TAG = "LibConnectionHandler" + private var mOnIndexUpdatedListener: OnIndexUpdatedListener? = null var configuration: ConfigurationService? = null private set @@ -77,9 +79,4 @@ class LibraryHandler { syncthingClient!!.close() configuration!!.close() } - - companion object { - - private val TAG = "LibConnectionHandler" - } } diff --git a/app/src/main/kotlin/net/syncthing/lite/library/UpdateIndexTask.kt b/app/src/main/kotlin/net/syncthing/lite/library/UpdateIndexTask.kt index 36b2557..6a3312c 100644 --- a/app/src/main/kotlin/net/syncthing/lite/library/UpdateIndexTask.kt +++ b/app/src/main/kotlin/net/syncthing/lite/library/UpdateIndexTask.kt @@ -1,16 +1,16 @@ package net.syncthing.lite.library import android.content.Context -import android.os.Handler import android.preference.PreferenceManager -import android.widget.Toast import net.syncthing.java.client.SyncthingClient import net.syncthing.lite.R +import org.jetbrains.anko.doAsync +import org.jetbrains.anko.toast +import org.jetbrains.anko.uiThread import java.util.* -class UpdateIndexTask(private val context: Context, private val syncthingClient: SyncthingClient) { - private val mPreferences = PreferenceManager.getDefaultSharedPreferences(context) - private val mMainHandler = Handler() +class UpdateIndexTask(private val androidContext: Context, private val syncthingClient: SyncthingClient) { + private val mPreferences = PreferenceManager.getDefaultSharedPreferences(androidContext) fun updateIndex() { if (sIndexUpdateInProgress) @@ -20,9 +20,9 @@ class UpdateIndexTask(private val context: Context, private val syncthingClient: syncthingClient.updateIndexFromPeers { _, failures -> sIndexUpdateInProgress = false if (failures.isEmpty()) { - showToast(context.getString(R.string.toast_index_update_successful)) + showToast(androidContext.getString(R.string.toast_index_update_successful)) } else { - showToast(context.getString(R.string.toast_index_update_failed, failures.size)) + showToast(androidContext.getString(R.string.toast_index_update_failed, failures.size)) } mPreferences.edit() .putLong(LAST_INDEX_UPDATE_TS_PREF, Date().time) @@ -31,7 +31,11 @@ class UpdateIndexTask(private val context: Context, private val syncthingClient: } private fun showToast(message: String) { - mMainHandler.post { Toast.makeText(context, message, Toast.LENGTH_SHORT).show() } + doAsync { + uiThread { + androidContext.toast(message) + } + } } companion object { diff --git a/app/src/main/kotlin/net/syncthing/lite/library/UploadFileTask.kt b/app/src/main/kotlin/net/syncthing/lite/library/UploadFileTask.kt index 7c42931..9975866 100644 --- a/app/src/main/kotlin/net/syncthing/lite/library/UploadFileTask.kt +++ b/app/src/main/kotlin/net/syncthing/lite/library/UploadFileTask.kt @@ -3,14 +3,15 @@ package net.syncthing.lite.library import android.app.ProgressDialog import android.content.Context import android.net.Uri -import android.os.Handler import android.util.Log -import android.widget.Toast import net.syncthing.java.bep.BlockPusher import net.syncthing.java.client.SyncthingClient import net.syncthing.java.core.utils.PathUtils import net.syncthing.lite.R import net.syncthing.lite.utils.Util +import org.jetbrains.anko.doAsync +import org.jetbrains.anko.toast +import org.jetbrains.anko.uiThread import java.io.IOException // TODO: this should be an IntentService with notification @@ -25,7 +26,6 @@ class UploadFileTask(private val context: Context, private val syncthingClient: private val fileName = Util.getContentFileName(context, localFile) private val syncthingPath = PathUtils.buildPath(syncthingSubFolder, fileName) - private val mainHandler = Handler() private lateinit var mProgressDialog: ProgressDialog private var mCancelled = false @@ -69,27 +69,35 @@ class UploadFileTask(private val context: Context, private val syncthingClient: } private fun onProgress(observer: BlockPusher.FileUploadObserver) { - mainHandler.post { - mProgressDialog.isIndeterminate = false - mProgressDialog.max = observer.dataSource.size.toInt() - mProgressDialog.progress = (observer.progress * observer.dataSource.size).toInt() + doAsync { + uiThread { + mProgressDialog.isIndeterminate = false + mProgressDialog.max = observer.dataSource.size.toInt() + mProgressDialog.progress = (observer.progress * observer.dataSource.size).toInt() + } } } private fun onComplete() { - mProgressDialog.dismiss() if (mCancelled) return Log.i(TAG, "Uploaded file $fileName to folder $syncthingFolder:$syncthingPath") - mainHandler.post { - Toast.makeText(context, R.string.toast_upload_complete, Toast.LENGTH_SHORT).show() - onUploadCompleteListener() + doAsync { + uiThread { + mProgressDialog.dismiss() + context.toast(R.string.toast_upload_complete) + onUploadCompleteListener() + } } } private fun onError() { - mProgressDialog.dismiss() - mainHandler.post { Toast.makeText(context, R.string.toast_file_upload_failed, Toast.LENGTH_SHORT).show() } + doAsync { + uiThread { + mProgressDialog.dismiss() + context.toast(R.string.toast_file_upload_failed) + } + } } } \ No newline at end of file