├── .gitignore ├── LICENSE.md ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── horizon │ │ └── taskdemo │ │ ├── activity │ │ ├── ChainTestActivity.kt │ │ ├── ConcurrentTestActivity.kt │ │ ├── ConcurrentTestActivity2.kt │ │ ├── CountingTestActivity.kt │ │ ├── LoadingTestActivity.kt │ │ ├── MainActivity.kt │ │ ├── NotChainTestActivity.kt │ │ └── SerialTestActivity.kt │ │ ├── application │ │ └── DemoApplication.kt │ │ └── base │ │ ├── BaseActivity.kt │ │ ├── BaseFragment.kt │ │ ├── HttpClient.kt │ │ └── TaskSchedulers.kt │ └── res │ ├── drawable │ └── ic_launcher_background.xml │ ├── layout │ ├── activity_chain_test.xml │ ├── activity_concurrent_test.xml │ ├── activity_concurrent_test2.xml │ ├── activity_counting_test.xml │ ├── activity_loading_test.xml │ ├── activity_main.xml │ └── activity_serial_test.xml │ ├── mipmap-xhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ └── values │ ├── colors.xml │ ├── strings.xml │ └── styles.xml ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── task ├── .gitignore ├── build.gradle ├── proguard-rules.pro ├── publish.gradle └── src └── main ├── AndroidManifest.xml └── java └── com └── horizon └── task ├── ChainTask.kt ├── TaskCenter.kt ├── UITask.kt ├── base ├── CircularQueue.kt ├── LogProxy.kt ├── Priority.kt ├── PriorityQueue.kt └── TaskLogger.kt ├── executor ├── LaneExecutor.kt ├── PipeExecutor.kt ├── RunnableWrapper.kt ├── TaskExecutor.kt └── Trigger.kt └── lifecycle ├── Holder.kt ├── LifeEvent.kt ├── LifeListener.kt └── LifecycleManager.kt /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | .DS_Store 5 | /build 6 | /captures 7 | .externalNativeBuild 8 | .idea 9 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Billy Wei 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | ## Task 3 | 4 | AsyncTask Plus 5 | 6 | ## New Feature 7 | 1、More concurrency control
8 | 2、Support Priority
9 | 3、Support Task grouping
10 | 4、Support lifecycle
11 | 5、Support chain invocation 12 | 13 | 14 | 15 | ## Prepare 16 | 17 | 1. Initialization(optional) 18 | 19 | ```kotlin 20 | LogProxy.init(object : TaskLogger { 21 | override val isDebug: Boolean 22 | get() = BuildConfig.DEBUG 23 | 24 | override fun e(tag: String, e: Throwable) { 25 | Log.e(tag, e.message, e) 26 | } 27 | }) 28 | ``` 29 | 30 | 2. Notify Lifecycle Events 31 | 32 | ```kotlin 33 | abstract class BaseActivity : Activity() { 34 | override fun onDestroy() { 35 | super.onDestroy() 36 | LifecycleManager.notify(this, LifeEvent.DESTROY) 37 | } 38 | 39 | override fun onPause() { 40 | super.onPause() 41 | LifecycleManager.notify(this, LifeEvent.HIDE) 42 | } 43 | 44 | override fun onResume() { 45 | super.onResume() 46 | LifecycleManager.notify(this, LifeEvent.SHOW) 47 | } 48 | } 49 | ``` 50 | 51 | 52 | ## How to use 53 | ### 1、Standard usage 54 | 55 | Just like AsyncTask: 56 | 57 | ```kotlin 58 | override fun onCreate(savedInstanceState: Bundle?) { 59 | // ... 60 | TestTask() 61 | .priority(Priority.IMMEDIATE) 62 | .host(this) 63 | .execute("hello") 64 | } 65 | 66 | private inner class TestTask: UITask(){ 67 | override fun generateTag(): String { 68 | // Normally, you don't need to override this function 69 | return "custom tag" 70 | } 71 | 72 | override fun onPreExecute() { 73 | result_tv.text = "running" 74 | } 75 | 76 | override fun doInBackground(vararg params: String): String? { 77 | for (i in 0..100 step 2) { 78 | Thread.sleep(10) 79 | publishProgress(Integer(i)) 80 | } 81 | return "result is:" + params[0].toUpperCase() 82 | } 83 | 84 | override fun onProgressUpdate(vararg values: Integer) { 85 | val progress = values[0] 86 | progress_bar.progress = progress.toInt() 87 | progress_tv.text = "$progress%" 88 | } 89 | 90 | override fun onPostExecute(result: String?) { 91 | result_tv.text = result 92 | } 93 | 94 | override fun onCancelled() { 95 | showTips("Task cancel ") 96 | } 97 | } 98 | ``` 99 | 100 | 101 | ### 2、Executor 102 | 103 | ``` 104 | TaskCenter.io.execute{ 105 | // do something 106 | } 107 | 108 | TaskCenter.laneIO.execute("tag", { 109 | // do something 110 | }) 111 | 112 | val serialExecutor = PipeExecutor(1) 113 | serialExecutor.execute{ 114 | // do something 115 | } 116 | 117 | TaskCenter.serial.execute ("your tag", { 118 | // do something 119 | }) 120 | ``` 121 | 122 | ### 3、For RxJava 123 | 124 | ```kotlin 125 | object TaskSchedulers { 126 | val io: Scheduler by lazy { Schedulers.from(TaskCenter.io) } 127 | val computation: Scheduler by lazy { Schedulers.from(TaskCenter.computation) } 128 | val single by lazy { Schedulers.from(PipeExecutor(1)) } 129 | } 130 | ``` 131 | 132 | ```kotlin 133 | Observable.range(1, 8) 134 | .subscribeOn(TaskSchedulers.computation) 135 | .subscribe { Log.d(tag, "number:$it") } 136 | ``` 137 | 138 | ### 4、Chain invocation 139 | ```kotlin 140 | override fun onCreate(savedInstanceState: Bundle?) { 141 | val task = ChainTask() 142 | task.tag("ChainTest") 143 | .preExecute { result_tv.text = "running" } 144 | .background { params -> 145 | for (i in 0..100 step 2) { 146 | // do something 147 | task.publishProgress(i) 148 | } 149 | "result is:" + (params[0] * 100) 150 | } 151 | .progressUpdate { values -> 152 | val progress = values[0] 153 | progress_bar.progress = progress 154 | progress_tv.text = "$progress%" 155 | } 156 | .postExecute { result_tv.text = it } 157 | .cancel { showTips("ChainTask cancel") } 158 | .priority(Priority.IMMEDIATE) 159 | .host(this) 160 | .execute(3.14) 161 | } 162 | ``` 163 | 164 | ## Link 165 | https://www.jianshu.com/p/8afb6cf64eec 166 | 167 | 168 | 169 | ## License 170 | See the [LICENSE](LICENSE.md) file for license rights and limitations. 171 | 172 | 173 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | apply plugin: 'kotlin-android' 4 | apply plugin: 'kotlin-android-extensions' 5 | 6 | android { 7 | compileSdkVersion 28 8 | defaultConfig { 9 | applicationId "com.horizon.taskdemo" 10 | minSdkVersion 14 11 | targetSdkVersion 28 12 | versionCode 1 13 | versionName "1.0" 14 | } 15 | buildTypes { 16 | debug{ 17 | 18 | } 19 | release { 20 | minifyEnabled false 21 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 22 | } 23 | } 24 | } 25 | 26 | 27 | 28 | dependencies { 29 | implementation fileTree(dir: 'libs', include: ['*.jar']) 30 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3' 31 | implementation 'com.squareup.okhttp3:okhttp:3.12.0' 32 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.31" 33 | implementation 'io.reactivex.rxjava2:rxandroid:2.1.1' 34 | implementation "io.reactivex.rxjava2:rxjava:2.2.8" 35 | implementation project(':task') 36 | } 37 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /app/src/main/java/com/horizon/taskdemo/activity/ChainTestActivity.kt: -------------------------------------------------------------------------------- 1 | package com.horizon.taskdemo.activity 2 | 3 | import android.annotation.SuppressLint 4 | import android.os.Bundle 5 | import com.horizon.task.ChainTask 6 | import com.horizon.task.base.Priority 7 | import com.horizon.taskdemo.R 8 | import com.horizon.taskdemo.base.BaseActivity 9 | import kotlinx.android.synthetic.main.activity_chain_test.* 10 | 11 | class ChainTestActivity : BaseActivity() { 12 | 13 | @SuppressLint("SetTextI18n") 14 | override fun onCreate(savedInstanceState: Bundle?) { 15 | super.onCreate(savedInstanceState) 16 | setContentView(R.layout.activity_chain_test) 17 | 18 | // 可在构造函数传入其他的TaskExecutor 19 | //val task = ChainTask(TaskCenter.laneCP) 20 | 21 | // 使用ChainTask,并且executor是LaneExecutor的话,最好设置tag, 否则讲退化为PipeExecutor。 22 | val task = ChainTask() 23 | task.tag("ChainTest") 24 | .preExecute { result_tv.text = "running" } 25 | .background { params -> 26 | for (i in 0..100 step 2) { 27 | Thread.sleep(10) 28 | task.publishProgress(i) 29 | } 30 | "result is:" + (params[0] * 100) 31 | } 32 | .progressUpdate { values -> 33 | val progress = values[0] 34 | progress_bar.progress = progress 35 | progress_tv.text = "$progress%" 36 | } 37 | .postExecute { result_tv.text = it } 38 | .cancel { showTips("ChainTask cancel ") } 39 | .priority(Priority.IMMEDIATE) 40 | .host(this) 41 | .execute(3.14) 42 | } 43 | 44 | } -------------------------------------------------------------------------------- /app/src/main/java/com/horizon/taskdemo/activity/ConcurrentTestActivity.kt: -------------------------------------------------------------------------------- 1 | package com.horizon.taskdemo.activity 2 | 3 | import android.annotation.SuppressLint 4 | import android.os.Bundle 5 | import android.util.Log 6 | import com.horizon.task.TaskCenter 7 | import com.horizon.task.executor.PipeExecutor 8 | import com.horizon.taskdemo.R 9 | import com.horizon.taskdemo.base.BaseActivity 10 | import kotlinx.android.synthetic.main.activity_concurrent_test.* 11 | import java.util.concurrent.atomic.AtomicInteger 12 | 13 | 14 | class ConcurrentTestActivity : BaseActivity() { 15 | 16 | @SuppressLint("SetTextI18n") 17 | override fun onCreate(savedInstanceState: Bundle?) { 18 | super.onCreate(savedInstanceState) 19 | setContentView(R.layout.activity_concurrent_test) 20 | 21 | val a = AtomicInteger() 22 | val b = AtomicInteger() 23 | val c = AtomicInteger() 24 | 25 | TaskCenter.io.execute{ 26 | // do something 27 | } 28 | 29 | TaskCenter.laneIO.execute("laneIO", { 30 | // do something 31 | }) 32 | 33 | val serialExecutor = PipeExecutor(1) 34 | serialExecutor.execute{ 35 | // do something 36 | } 37 | 38 | TaskCenter.serial.execute ("your tag", { 39 | // do something 40 | }) 41 | 42 | // TaskCenter.io 没做任务去重,所以a=5 43 | for (i in 1..5) { 44 | TaskCenter.io.execute { 45 | Thread.sleep(100) 46 | Log.d(tag, "TaskCenter.io") 47 | a.incrementAndGet() 48 | } 49 | } 50 | 51 | // TaskCenter.serial 不会忽略任务(但会串行执行),所以b=5 52 | for (i in 1..5) { 53 | TaskCenter.serial.execute ("serial", { 54 | Thread.sleep(100) 55 | Log.d(tag, "TaskCenter.serial") 56 | b.incrementAndGet() 57 | }) 58 | } 59 | 60 | // TaskCenter.laneIO 会只保留一个在等待的任务,后来者会被忽略,所以c=2 61 | for (i in 1..5) { 62 | TaskCenter.laneIO.execute("laneIO", { 63 | Thread.sleep(100) 64 | Log.d(tag, "TaskCenter.laneCP $i") 65 | c.incrementAndGet() 66 | }) 67 | } 68 | 69 | // 观察log, 将会看到: 70 | // TaskCenter.io 几乎同时打印 71 | // TaskCenter.serial 每隔100ms打印一条 72 | // TaskCenter.laneIO 也是每隔100ms打印一条,但只会打印2条, 73 | // 因为在几乎同一时刻提交了5个任务,被过滤了3个 74 | 75 | state_tv.postDelayed({ 76 | state_tv.text = "a:$a b:$b c:$c" 77 | }, 1000) 78 | } 79 | 80 | 81 | } 82 | -------------------------------------------------------------------------------- /app/src/main/java/com/horizon/taskdemo/activity/ConcurrentTestActivity2.kt: -------------------------------------------------------------------------------- 1 | package com.horizon.taskdemo.activity 2 | 3 | import android.annotation.SuppressLint 4 | import android.os.Bundle 5 | import android.util.Log 6 | import android.widget.TextView 7 | import com.horizon.task.UITask 8 | import com.horizon.task.executor.LaneExecutor 9 | import com.horizon.task.executor.PipeExecutor 10 | import com.horizon.task.executor.TaskExecutor 11 | import com.horizon.taskdemo.R 12 | import com.horizon.taskdemo.base.BaseActivity 13 | import java.util.concurrent.CountDownLatch 14 | import java.util.concurrent.TimeUnit 15 | 16 | // 这个用例有点复杂, ConcurrentTestActivity会好理解一些 17 | class ConcurrentTestActivity2 : BaseActivity() { 18 | companion object { 19 | private const val CONCURRENT_SIZE = 4 20 | } 21 | 22 | private val mCustomExecutor = LaneExecutor(PipeExecutor(CONCURRENT_SIZE), true) 23 | 24 | private var mCount = 0 25 | internal lateinit var mProgressTv: TextView 26 | internal lateinit var mStateTv: TextView 27 | internal lateinit var mResultTv: TextView 28 | 29 | // 32个任务同时启动,8个可以马上执行,8个进入等待,16个被丢弃 30 | internal val mTagCount = 8 31 | internal val mExpectedCount = mTagCount * 2 32 | private val mTaskCount = mTagCount * 4 33 | 34 | internal val mSleepTime = 200 35 | private val mWaitTime = 1000L 36 | internal val mExpectedTime = mExpectedCount * mSleepTime / CONCURRENT_SIZE + mWaitTime 37 | 38 | override fun onCreate(savedInstanceState: Bundle?) { 39 | super.onCreate(savedInstanceState) 40 | setContentView(R.layout.activity_concurrent_test2) 41 | 42 | mStateTv = findViewById(R.id.state_tv) 43 | mProgressTv = findViewById(R.id.progess_tv) 44 | mResultTv = findViewById(R.id.result_tv) 45 | 46 | object : UITask() { 47 | private var actuallyTime: Long = 0 48 | 49 | override fun doInBackground(vararg params: Void): String? { 50 | val start = System.nanoTime() 51 | startTest() 52 | val end = System.nanoTime() 53 | actuallyTime = (end - start) / 1000000 54 | return null 55 | } 56 | 57 | @SuppressLint("SetTextI18n") 58 | override fun onPostExecute(result: String?) { 59 | mStateTv.text = "done" 60 | 61 | // Thread.sleep(long) 通常会多sleep()一点时间 62 | // 所以 mExpectedTim 一般预计的多一点 63 | // 但是mCount是准的,和mExpectedCount一样多 64 | mResultTv.text = ("use time:" + actuallyTime 65 | + "\nexpectedTime:" + mExpectedTime 66 | + "\nfinish count:" + mCount 67 | + "\nexpectedCount: " + mExpectedCount) 68 | } 69 | } 70 | .host(this) 71 | .execute() 72 | 73 | } 74 | 75 | private fun startTest() { 76 | val latch = CountDownLatch(mExpectedCount) 77 | 78 | for (i in 0 until mTaskCount) { 79 | // 如果 onPreExecute()不做UI操作 80 | // 在后台线程中启动UITask也是没有问题的 81 | object : UITask() { 82 | override val executor: TaskExecutor 83 | get() = mCustomExecutor 84 | 85 | override fun generateTag(): String { 86 | // 给任务打标签 87 | return "TASK" + i % mTagCount 88 | } 89 | 90 | override fun doInBackground(vararg params: Void): Void? { 91 | try { 92 | Thread.sleep(mSleepTime.toLong()) 93 | } catch (e: InterruptedException) { 94 | Log.w(tag, e.javaClass.simpleName + " occurred") 95 | } finally { 96 | latch.countDown() 97 | } 98 | return null 99 | } 100 | 101 | @SuppressLint("SetTextI18n") 102 | override fun onPostExecute(result: Void?) { 103 | mProgressTv.text = (++mCount).toString() + " task finish" 104 | } 105 | }.host(this).execute() 106 | } 107 | 108 | try { 109 | latch.await((mExpectedTime + 3000), TimeUnit.MILLISECONDS) 110 | 111 | Thread.sleep(mWaitTime) 112 | } catch (e: InterruptedException) { 113 | Log.e(tag, e.message, e) 114 | } 115 | 116 | } 117 | 118 | 119 | 120 | } 121 | -------------------------------------------------------------------------------- /app/src/main/java/com/horizon/taskdemo/activity/CountingTestActivity.kt: -------------------------------------------------------------------------------- 1 | package com.horizon.taskdemo.activity 2 | 3 | import android.os.Bundle 4 | import android.util.Log 5 | import android.widget.TextView 6 | import com.horizon.task.TaskCenter 7 | import com.horizon.task.UITask 8 | import com.horizon.task.base.Priority 9 | import com.horizon.task.executor.TaskExecutor 10 | import com.horizon.taskdemo.R 11 | import com.horizon.taskdemo.base.BaseActivity 12 | 13 | 14 | class CountingTestActivity : BaseActivity() { 15 | private lateinit var mCountingTv: TextView 16 | 17 | override fun onCreate(savedInstanceState: Bundle?) { 18 | super.onCreate(savedInstanceState) 19 | setContentView(R.layout.activity_counting_test) 20 | 21 | mCountingTv = findViewById(R.id.counting_tv) 22 | 23 | CountingTask() 24 | .host(this) 25 | .priority(Priority.IMMEDIATE) 26 | .execute(20 as Integer) 27 | } 28 | 29 | private inner class CountingTask : UITask(){ 30 | // 事实上这里不需要 TaskCenter.laneCP, 只是为了展示使用方法 31 | override val executor: TaskExecutor 32 | get() = TaskCenter.laneCP 33 | 34 | override fun doInBackground(vararg params: Integer): String? { 35 | val n = params[0] as Int 36 | return try { 37 | for (count in n downTo 1) { 38 | publishProgress(Integer.toString(count)) 39 | Thread.sleep(1000) 40 | } 41 | "done" 42 | } catch (e: InterruptedException) { 43 | Log.w(tag, e.javaClass.simpleName + " occurred") 44 | "cancel" 45 | } 46 | } 47 | 48 | override fun onProgressUpdate(vararg values: String) { 49 | mCountingTv.text = values[0] 50 | } 51 | 52 | override fun onCancelled(result: String?) { 53 | Log.i(tag, "task result: " + result!!) 54 | } 55 | 56 | override fun onPostExecute(result: String?) { 57 | mCountingTv.text = result 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /app/src/main/java/com/horizon/taskdemo/activity/LoadingTestActivity.kt: -------------------------------------------------------------------------------- 1 | package com.horizon.taskdemo.activity 2 | 3 | import android.graphics.Bitmap 4 | import android.graphics.BitmapFactory 5 | import android.os.Bundle 6 | import android.util.Log 7 | import com.horizon.task.UITask 8 | import com.horizon.taskdemo.R 9 | import com.horizon.taskdemo.base.BaseActivity 10 | import com.horizon.taskdemo.base.HttpClient 11 | import kotlinx.android.synthetic.main.activity_loading_test.* 12 | import okhttp3.Request 13 | 14 | 15 | class LoadingTestActivity : BaseActivity() { 16 | override fun onCreate(savedInstanceState: Bundle?) { 17 | super.onCreate(savedInstanceState) 18 | setContentView(R.layout.activity_loading_test) 19 | 20 | val url = "https://pic1.zhimg.com/80/63536f2f01409f750162828a980a0380_hd.jpg" 21 | LoadingTask().host(this).execute(url) 22 | } 23 | 24 | private inner class LoadingTask : UITask() { 25 | override fun doInBackground(vararg params: String): Bitmap? { 26 | val url = params[0] 27 | val builder = Request.Builder().url(url) 28 | try { 29 | val response = HttpClient.execute(builder.build()) 30 | if (response.isSuccessful) { 31 | return BitmapFactory.decodeStream(response.body()!!.byteStream()) 32 | } 33 | } catch (e: Exception) { 34 | Log.e(tag, e.message, e) 35 | } 36 | 37 | return null 38 | } 39 | 40 | override fun onPostExecute(result: Bitmap?) { 41 | if (result != null) { 42 | test_iv.setImageBitmap(result) 43 | } 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /app/src/main/java/com/horizon/taskdemo/activity/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.horizon.taskdemo.activity 2 | 3 | import android.os.Bundle 4 | import android.util.Log 5 | import android.view.View 6 | import com.horizon.taskdemo.R 7 | import com.horizon.taskdemo.base.BaseActivity 8 | import com.horizon.taskdemo.base.TaskSchedulers 9 | import io.reactivex.Observable 10 | import io.reactivex.android.schedulers.AndroidSchedulers 11 | import io.reactivex.disposables.Disposable 12 | import kotlinx.android.synthetic.main.activity_main.* 13 | 14 | class MainActivity : BaseActivity(), View.OnClickListener { 15 | private var disposable: Disposable? = null 16 | 17 | override fun onCreate(savedInstanceState: Bundle?) { 18 | super.onCreate(savedInstanceState) 19 | setContentView(R.layout.activity_main) 20 | 21 | loading_btn.setOnClickListener(this) 22 | counting_btn.setOnClickListener(this) 23 | serial_btn.setOnClickListener(this) 24 | concurrent_btn.setOnClickListener(this) 25 | chain_btn.setOnClickListener(this) 26 | 27 | disposable = Observable.range(1, 8) 28 | .flatMap { i -> 29 | Observable.just(i) 30 | .subscribeOn(TaskSchedulers.computation) 31 | .map { Thread.sleep(1050); "param:$it" } 32 | } 33 | .observeOn(AndroidSchedulers.mainThread()) 34 | .subscribe { result -> 35 | Log.d(tag, result) 36 | } 37 | } 38 | 39 | override fun onDestroy() { 40 | super.onDestroy() 41 | disposable?.dispose() 42 | } 43 | 44 | override fun onClick(v: View) { 45 | when (v.id) { 46 | R.id.loading_btn -> startActivity(LoadingTestActivity::class.java) 47 | R.id.counting_btn -> startActivity(CountingTestActivity::class.java) 48 | R.id.serial_btn -> startActivity(SerialTestActivity::class.java) 49 | R.id.concurrent_btn -> startActivity(ConcurrentTestActivity::class.java) 50 | R.id.chain_btn -> startActivity(ChainTestActivity::class.java) 51 | //R.id.chain_btn -> startActivity(NotChainTestActivity::class.java) 52 | } 53 | } 54 | 55 | } 56 | 57 | -------------------------------------------------------------------------------- /app/src/main/java/com/horizon/taskdemo/activity/NotChainTestActivity.kt: -------------------------------------------------------------------------------- 1 | package com.horizon.taskdemo.activity 2 | 3 | import android.annotation.SuppressLint 4 | import android.os.Bundle 5 | import com.horizon.task.UITask 6 | import com.horizon.task.base.Priority 7 | import com.horizon.taskdemo.R 8 | import com.horizon.taskdemo.base.BaseActivity 9 | import kotlinx.android.synthetic.main.activity_chain_test.* 10 | 11 | // 此类用于与 ChainTestActivity对比 12 | class NotChainTestActivity : BaseActivity() { 13 | @SuppressLint("SetTextI18n") 14 | override fun onCreate(savedInstanceState: Bundle?) { 15 | super.onCreate(savedInstanceState) 16 | setContentView(R.layout.activity_chain_test) 17 | 18 | NotChainTask() 19 | .priority(Priority.IMMEDIATE) 20 | .host(this) 21 | .execute("hello") 22 | } 23 | 24 | private inner class NotChainTask : UITask() { 25 | override fun generateTag(): String { 26 | // 一般情况下不需要重写这个函数,这里只是为了演示 27 | return "custom tag" 28 | } 29 | 30 | override fun onPreExecute() { 31 | result_tv.text = "running" 32 | } 33 | 34 | override fun doInBackground(vararg params: String): String? { 35 | for (i in 0..100 step 2) { 36 | Thread.sleep(10) 37 | publishProgress(Integer(i)) 38 | } 39 | return "result is:" + params[0].toUpperCase() 40 | } 41 | 42 | override fun onProgressUpdate(vararg values: Integer) { 43 | val progress = values[0] 44 | progress_bar.progress = progress.toInt() 45 | progress_tv.text = "$progress%" 46 | } 47 | 48 | override fun onPostExecute(result: String?) { 49 | result_tv.text = result 50 | } 51 | 52 | override fun onCancelled() { 53 | showTips("ChainTask cancel ") 54 | } 55 | } 56 | 57 | 58 | } -------------------------------------------------------------------------------- /app/src/main/java/com/horizon/taskdemo/activity/SerialTestActivity.kt: -------------------------------------------------------------------------------- 1 | package com.horizon.taskdemo.activity 2 | 3 | import android.os.Bundle 4 | import android.util.Log 5 | import android.widget.TextView 6 | import com.horizon.task.executor.PipeExecutor 7 | import com.horizon.taskdemo.R 8 | import com.horizon.taskdemo.base.BaseActivity 9 | 10 | 11 | class SerialTestActivity : BaseActivity() { 12 | private var mCountingTv: TextView? = null 13 | private var destroy = false 14 | private var count = 0 15 | private var createTime: Long = 0 16 | 17 | private val mSerialExecutor = PipeExecutor(1) 18 | 19 | override fun onCreate(savedInstanceState: Bundle?) { 20 | super.onCreate(savedInstanceState) 21 | setContentView(R.layout.activity_serial_test) 22 | 23 | mCountingTv = findViewById(R.id.counting_tv) 24 | createTime = System.nanoTime() 25 | for (i in 0 until N) { 26 | // 两种方式实现串行:TaskCenter.serial更方便一些;PipeExecutor(1)更独立一些 27 | // TaskCenter.serial.execute("CountingTask", CountingTask()) 28 | mSerialExecutor.execute(CountingTask()) 29 | } 30 | } 31 | 32 | private inner class CountingTask : Runnable { 33 | override fun run() { 34 | count++ 35 | Log.d(tag, "task count: $count") 36 | 37 | if (!destroy) { 38 | try { 39 | Thread.sleep(1000L) 40 | } catch (ignore: InterruptedException) { 41 | } 42 | 43 | val t = (System.nanoTime() - createTime) / 1000000 44 | val text = "$count task finished, \nuse time: $t" 45 | runOnUiThread { mCountingTv!!.text = text } 46 | } 47 | } 48 | } 49 | 50 | override fun onDestroy() { 51 | super.onDestroy() 52 | destroy = true 53 | } 54 | 55 | companion object { 56 | private const val N = 5 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /app/src/main/java/com/horizon/taskdemo/application/DemoApplication.kt: -------------------------------------------------------------------------------- 1 | package com.horizon.taskdemo.application 2 | 3 | import android.app.Application 4 | import android.content.Context 5 | import android.util.Log 6 | 7 | import com.horizon.task.base.LogProxy 8 | import com.horizon.task.base.TaskLogger 9 | import com.horizon.taskdemo.BuildConfig 10 | import com.horizon.taskdemo.base.HttpClient 11 | 12 | 13 | class DemoApplication : Application() { 14 | 15 | companion object { 16 | lateinit var context : Context 17 | } 18 | 19 | override fun onCreate() { 20 | super.onCreate() 21 | 22 | context = applicationContext 23 | 24 | HttpClient.init(this) 25 | 26 | LogProxy.init(object : TaskLogger { 27 | override val isDebug: Boolean 28 | get() = BuildConfig.DEBUG 29 | 30 | override fun e(tag: String, e: Throwable) { 31 | Log.e(tag, e.message, e) 32 | } 33 | }) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /app/src/main/java/com/horizon/taskdemo/base/BaseActivity.kt: -------------------------------------------------------------------------------- 1 | package com.horizon.taskdemo.base 2 | 3 | import android.app.Activity 4 | import android.content.Intent 5 | import android.widget.Toast 6 | import com.horizon.task.lifecycle.LifeEvent 7 | 8 | import com.horizon.task.lifecycle.LifecycleManager 9 | import com.horizon.taskdemo.application.DemoApplication 10 | 11 | abstract class BaseActivity : Activity() { 12 | protected val tag = this.javaClass.simpleName!! 13 | 14 | override fun onDestroy() { 15 | super.onDestroy() 16 | LifecycleManager.notify(this, LifeEvent.DESTROY) 17 | } 18 | 19 | override fun onPause() { 20 | super.onPause() 21 | LifecycleManager.notify(this, LifeEvent.HIDE) 22 | } 23 | 24 | override fun onResume() { 25 | super.onResume() 26 | LifecycleManager.notify(this, LifeEvent.SHOW) 27 | } 28 | 29 | fun startActivity(activityClazz: Class<*>) { 30 | val intent = Intent(this, activityClazz) 31 | startActivity(intent) 32 | } 33 | 34 | fun showTips(msg : String){ 35 | Toast.makeText( DemoApplication.context,msg, Toast.LENGTH_SHORT ).show() 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /app/src/main/java/com/horizon/taskdemo/base/BaseFragment.kt: -------------------------------------------------------------------------------- 1 | package com.horizon.taskdemo.base 2 | 3 | import android.app.Fragment 4 | import com.horizon.task.lifecycle.LifeEvent 5 | import com.horizon.task.lifecycle.LifecycleManager 6 | 7 | 8 | abstract class BaseFragment : Fragment() { 9 | override fun onDestroy() { 10 | super.onDestroy() 11 | LifecycleManager.notify(this, LifeEvent.DESTROY) 12 | } 13 | 14 | override fun setUserVisibleHint(isVisibleToUser: Boolean) { 15 | super.setUserVisibleHint(isVisibleToUser) 16 | LifecycleManager.notify(this, if (isVisibleToUser) LifeEvent.SHOW else LifeEvent.HIDE) 17 | } 18 | } -------------------------------------------------------------------------------- /app/src/main/java/com/horizon/taskdemo/base/HttpClient.kt: -------------------------------------------------------------------------------- 1 | package com.horizon.taskdemo.base 2 | 3 | import android.content.Context 4 | import okhttp3.Cache 5 | import okhttp3.OkHttpClient 6 | import okhttp3.Request 7 | import okhttp3.Response 8 | import java.io.File 9 | import java.io.IOException 10 | 11 | 12 | object HttpClient{ 13 | private var client: OkHttpClient? = null 14 | 15 | fun init(context: Context) { 16 | if (client == null) { 17 | val cacheDirPath = context.cacheDir.path + "/http/" 18 | client = OkHttpClient.Builder() 19 | .cache(Cache(File(cacheDirPath), (64 shl 20).toLong())) 20 | .build() 21 | } 22 | } 23 | 24 | @Throws(IOException::class) 25 | fun execute(request: Request): Response { 26 | return client!!.newCall(request).execute() 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /app/src/main/java/com/horizon/taskdemo/base/TaskSchedulers.kt: -------------------------------------------------------------------------------- 1 | package com.horizon.taskdemo.base 2 | 3 | import com.horizon.task.TaskCenter 4 | import com.horizon.task.executor.PipeExecutor 5 | import io.reactivex.Scheduler 6 | import io.reactivex.schedulers.Schedulers 7 | 8 | object TaskSchedulers { 9 | val io: Scheduler by lazy { Schedulers.from(TaskCenter.io) } 10 | val computation: Scheduler by lazy { Schedulers.from(TaskCenter.computation) } 11 | val single by lazy { Schedulers.from(PipeExecutor(1)) } 12 | } 13 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_chain_test.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 23 | 24 | 35 | 36 | 44 | 45 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_concurrent_test.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_concurrent_test2.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 18 | 19 | 20 | 28 | 29 | 30 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_counting_test.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_loading_test.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 |