├── .gitignore ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── silencedut │ │ └── asynctaskschedulertest │ │ └── ExampleInstrumentationTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── silencedut │ │ │ └── asynctaskschedulertest │ │ │ ├── App.java │ │ │ └── MainActivity.java │ └── res │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── silencedut │ └── asynctaskschedulertest │ └── ExampleUnitTest.java ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── library ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── silencedut │ │ └── asynctaskscheduler │ │ └── ExampleInstrumentationTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── silencedut │ │ │ └── asynctaskscheduler │ │ │ ├── AsyncTaskScheduler.java │ │ │ └── SingleAsyncTask.java │ └── res │ │ └── values │ │ └── strings.xml │ └── test │ └── java │ └── com │ └── silencedut │ └── asynctaskscheduler │ └── ExampleUnitTest.java └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea 5 | .DS_Store 6 | /build 7 | /captures 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Deprecated 2 | using [TaskScheduler](https://github.com/SilenceDut/TaskScheduler) highly recommend 3 | 4 | # AsyncTaskScheduler 5 | [![](https://jitpack.io/v/SilenceDut/AsyncTaskScheduler.svg)](https://jitpack.io/#SilenceDut/AsyncTaskScheduler) 6 | ## Background 7 | [详细解读AsyncTask的黑暗面以及一种替代方案](http://silencedut.coding.me/2016/07/08/%E5%9F%BA%E4%BA%8E%E6%9C%80%E6%96%B0%E7%89%88%E6%9C%AC%E7%9A%84AsyncTask%E6%BA%90%E7%A0%81%E8%A7%A3%E8%AF%BB%E5%8F%8AAsyncTask%E7%9A%84%E9%BB%91%E6%9A%97%E9%9D%A2/) 8 | ## Characters 9 | - execute tasks in parallel as default, rather than processing them sequentially 10 | - execute single task use a thread rather than an executor 11 | - you can set a default executor to execute tasks 12 | - a callback for task error 13 | - manage multiple tasks easily 14 | - you can you it on any thread ,anf it will have a callback on main thread。 15 | 16 | ## Methods Introduction 17 | methods like AsyncTask ,use easily 18 | 19 | - doInBackground : background thread 20 | - onProgressUpdate : main thread 21 | - onExecuteSucceed : main thread 22 | - onExecuteCancelled : main thread 23 | - onExecuteFailed : main thread,when unexpected happened 24 | 25 | ## Add to project 26 | **latest-version**: 27 | [![](https://jitpack.io/v/SilenceDut/AsyncTaskScheduler.svg)](https://jitpack.io/#SilenceDut/AsyncTaskScheduler) 28 | 29 | Step 1. Add the JitPack repository to your build file 30 | 31 | **gradle** 32 | ```groovy 33 | allprojects { 34 | repositories { 35 | ... 36 | maven { url "https://jitpack.io" } 37 | } 38 | } 39 | ``` 40 | **maven** 41 | ```xml 42 | 43 | 44 | jitpack.io 45 | https://jitpack.io 46 | 47 | 48 | ``` 49 | 50 | Step 2. Add the dependency 51 | 52 | **gradle** 53 | 54 | ```groovy 55 | compile 'com.github.SilenceDut:AsyncTaskScheduler:{latest-version}' 56 | ``` 57 | **maven** 58 | 59 | ```xml 60 | 61 | com.github.SilenceDut 62 | AsyncTaskScheduler 63 | {latest-version} 64 | 65 | ``` 66 | ##How to use 67 | **Single background task ,use a single thread rather than an Executor, save resource** 68 | 69 | ```java 70 | SingleAsyncTask singleTask = new SingleAsyncTask() { 71 | @Override 72 | public String doInBackground() { 73 | return null; 74 | } 75 | @Override 76 | public void onExecuteSucceed(String result) { 77 | super.onExecuteSucceed(result); 78 | } 79 | @Override 80 | public void onExecuteFailed(Exception exception) { 81 | super.onExecuteFailed(exception); 82 | Log.i(TAG,"onExecuteCancelled:"+exception.getMessage()+Thread.currentThread()); 83 | } 84 | }; 85 | singleTask.executeSingle(); 86 | 87 | //取消通过executeSingle执行的任务 88 | mSingleAsyncTask.cancel(true); 89 | ``` 90 | 91 | **multiple background tasks,create a task scheduler to manage them.** 92 | 93 | ```java 94 | //多个任务新建一个任务调度器 95 | AsyncTaskScheduler mAsyncTaskScheduler = new AsyncTaskScheduler(); 96 | 97 | SingleAsyncTask singleTask1 = new SingleTask() { ... }; 98 | SingleAsyncTask singleTask2 = new SingleTask() { ... }; 99 | SingleAsyncTask singleTask3 = new SingleTask() { ... }; 100 | ... 101 | 102 | //并行执行多个任务 103 | mAsyncTaskScheduler.execute(singleTask1) 104 | .execute(singleTask2).execute(singleTask3). 105 | 106 | //取消通过AsyncTaskScheduler任务 107 | mAsyncTaskScheduler.cancelAllTasks(true); 108 | ``` 109 | 110 | **you can set a default Executor to execute tasks** 111 | 112 | ```java 113 | //设置默认的线程池 114 | Executor defaultPoolExecutor = ... 115 | AsyncTaskScheduler mAsyncTaskScheduler = new AsyncTaskScheduler(Executor defaultPoolExecutor); 116 | ``` 117 | 118 | **make sure cancel task to avoid memory leak** 119 | 120 | ```java 121 | //取消通过executeSingle执行的任务 122 | mSingleAsyncTask.cancel(true); 123 | 124 | //取消通过AsyncTaskScheduler任务 125 | mAsyncTaskScheduler.cancelAllTasks(true); 126 | ``` 127 | License 128 | ------- 129 | 130 | Copyright 2015-2016 SilenceDut 131 | 132 | Licensed under the Apache License, Version 2.0 (the "License"); 133 | you may not use this file except in compliance with the License. 134 | You may obtain a copy of the License at 135 | 136 | http://www.apache.org/licenses/LICENSE-2.0 137 | 138 | Unless required by applicable law or agreed to in writing, software 139 | distributed under the License is distributed on an "AS IS" BASIS, 140 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 141 | See the License for the specific language governing permissions and 142 | limitations under the License. 143 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 23 5 | buildToolsVersion "23.0.3" 6 | defaultConfig { 7 | applicationId "com.silencedut.asynctaskschedulertest" 8 | minSdkVersion 9 9 | targetSdkVersion 23 10 | versionCode 1 11 | versionName "1.0" 12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(dir: 'libs', include: ['*.jar']) 24 | compile project(':library') 25 | 26 | compile 'com.android.support:appcompat-v7:23.4.0' 27 | compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha1' 28 | testCompile 'junit:junit:4.12' 29 | androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2' 30 | androidTestCompile 'com.android.support.test:runner:0.5' 31 | androidTestCompile 'com.android.support:support-annotations:23.4.0' 32 | 33 | debugCompile 'com.squareup.leakcanary:leakcanary-android:1.4-beta2' 34 | releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2' 35 | testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2' 36 | } 37 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/SilenceDut/Documents/developsoftware/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/silencedut/asynctaskschedulertest/ExampleInstrumentationTest.java: -------------------------------------------------------------------------------- 1 | package com.silencedut.asynctaskschedulertest; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.filters.MediumTest; 6 | import android.support.test.runner.AndroidJUnit4; 7 | 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | 11 | 12 | import static org.junit.Assert.*; 13 | 14 | /** 15 | * Instrumentation test, which will execute on an Android device. 16 | * 17 | * @see Testing documentation 18 | */ 19 | @MediumTest 20 | @RunWith(AndroidJUnit4.class) 21 | public class ExampleInstrumentationTest { 22 | @Test 23 | public void useAppContext() throws Exception { 24 | // Context of the app under test. 25 | Context appContext = InstrumentationRegistry.getTargetContext(); 26 | 27 | assertEquals("com.silencedut.asynctaskschedulertest", appContext.getPackageName()); 28 | } 29 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /app/src/main/java/com/silencedut/asynctaskschedulertest/App.java: -------------------------------------------------------------------------------- 1 | package com.silencedut.asynctaskschedulertest; 2 | 3 | import android.app.Application; 4 | 5 | import com.squareup.leakcanary.LeakCanary; 6 | 7 | /** 8 | * Created by SilenceDut on 16/7/22. 9 | */ 10 | 11 | public class App extends Application { 12 | @Override 13 | public void onCreate() { 14 | super.onCreate(); 15 | LeakCanary.install(this); 16 | } 17 | 18 | 19 | } 20 | -------------------------------------------------------------------------------- /app/src/main/java/com/silencedut/asynctaskschedulertest/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.silencedut.asynctaskschedulertest; 2 | 3 | import android.os.Bundle; 4 | import android.support.v7.app.AppCompatActivity; 5 | import android.util.Log; 6 | import android.widget.TextView; 7 | 8 | import com.silencedut.asynctaskscheduler.AsyncTaskScheduler; 9 | import com.silencedut.asynctaskscheduler.SingleAsyncTask; 10 | 11 | 12 | public class MainActivity extends AppCompatActivity { 13 | private static final String TAG = MainActivity.class.getSimpleName(); 14 | private SingleAsyncTask mSingleAsyncTask; 15 | private AsyncTaskScheduler mAsyncTaskScheduler; 16 | private TextView mLogMessageTv; 17 | @Override 18 | protected void onCreate(Bundle savedInstanceState) { 19 | super.onCreate(savedInstanceState); 20 | setContentView(R.layout.activity_main); 21 | mLogMessageTv = (TextView) findViewById(R.id.log_message_tv); 22 | mAsyncTaskScheduler = new AsyncTaskScheduler(); 23 | 24 | mSingleAsyncTask =new SingleAsyncTask() { 25 | @Override 26 | public String doInBackground() { 27 | try { 28 | Thread.sleep(2000); 29 | } catch (InterruptedException e) { 30 | e.printStackTrace(); 31 | } 32 | Log.i(TAG,"doInBackground: "+Thread.currentThread().getName()); 33 | return "singleTask"+Thread.currentThread().getName(); 34 | } 35 | 36 | @Override 37 | public void onExecuteSucceed(String s) { 38 | super.onExecuteSucceed(s); 39 | mLogMessageTv.setText("\n onExecuteSucceed:"+s+mLogMessageTv.getText()); 40 | Log.i(TAG,"onExecuteSucceed:"+s+Thread.currentThread()); 41 | } 42 | 43 | @Override 44 | public void onExecuteCancelled(String result) { 45 | super.onExecuteCancelled(result); 46 | Log.i(TAG,"onExecuteCancelled:"+result+Thread.currentThread()); 47 | } 48 | 49 | @Override 50 | public void onExecuteFailed(Exception exception) { 51 | super.onExecuteFailed(exception); 52 | Log.i(TAG,"onExecuteCancelled:"+exception.getMessage()+Thread.currentThread()); 53 | } 54 | }; 55 | SingleAsyncTask singleAsyncTask1 =new SingleAsyncTask() { 56 | @Override 57 | public String doInBackground() { 58 | try { 59 | Thread.sleep(1500); 60 | } catch (InterruptedException e) { 61 | onExecuteFailed(e); 62 | } 63 | Log.i(TAG,"doInBackground: "+Thread.currentThread().getName()); 64 | return "singleAsyncTask1"+Thread.currentThread().getName(); 65 | } 66 | @Override 67 | public void onExecuteSucceed(String s) { 68 | super.onExecuteSucceed(s); 69 | mLogMessageTv.setText("\n onExecuteSucceed:"+s+mLogMessageTv.getText()); 70 | } 71 | }; 72 | SingleAsyncTask singleAsyncTask2 =new SingleAsyncTask() { 73 | @Override 74 | public String doInBackground() { 75 | try { 76 | Thread.sleep(1500); 77 | } catch (InterruptedException e) { 78 | onExecuteFailed(e); 79 | } 80 | Log.i(TAG,"doInBackground: "+Thread.currentThread().getName()); 81 | return "singleAsyncTask1"+Thread.currentThread().getName(); 82 | } 83 | @Override 84 | public void onExecuteSucceed(String s) { 85 | super.onExecuteSucceed(s); 86 | mLogMessageTv.setText("\n onExecuteSucceed:"+s+mLogMessageTv.getText()); 87 | } 88 | }; 89 | 90 | mAsyncTaskScheduler.execute(singleAsyncTask1).execute(singleAsyncTask2); 91 | mSingleAsyncTask.executeSingle(); 92 | 93 | mLogMessageTv.setText("\n MainThread:"+Thread.currentThread()); 94 | Log.i(TAG, "Main"+Thread.currentThread()); 95 | } 96 | 97 | @Override 98 | protected void onDestroy() { 99 | super.onDestroy(); 100 | mAsyncTaskScheduler.cancelAllTasks(true); 101 | mSingleAsyncTask.cancel(true); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SilenceDut/AsyncTaskScheduler/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SilenceDut/AsyncTaskScheduler/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SilenceDut/AsyncTaskScheduler/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SilenceDut/AsyncTaskScheduler/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SilenceDut/AsyncTaskScheduler/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | AsyncTaskScheduler 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/test/java/com/silencedut/asynctaskschedulertest/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.silencedut.asynctaskschedulertest; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() throws Exception { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | org.gradle.jvmargs=-Xmx1536m 13 | 14 | # When configured, Gradle will run in incubating parallel mode. 15 | # This option should only be used with decoupled projects. More details, visit 16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 17 | # org.gradle.parallel=true 18 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SilenceDut/AsyncTaskScheduler/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Dec 28 10:00:20 PST 2015 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /library/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /library/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'com.github.dcendents.android-maven' 3 | group='com.github.SilenceDut' 4 | 5 | android { 6 | compileSdkVersion 23 7 | buildToolsVersion "23.0.3" 8 | 9 | defaultConfig { 10 | minSdkVersion 9 11 | targetSdkVersion 23 12 | versionCode 1 13 | versionName "1.0" 14 | 15 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 16 | } 17 | buildTypes { 18 | release { 19 | minifyEnabled false 20 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 21 | } 22 | } 23 | } 24 | 25 | dependencies { 26 | compile fileTree(dir: 'libs', include: ['*.jar']) 27 | compile 'com.android.support:appcompat-v7:23.4.0' 28 | testCompile 'junit:junit:4.12' 29 | androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2' 30 | androidTestCompile 'com.android.support.test:runner:0.5' 31 | androidTestCompile 'com.android.support:support-annotations:23.4.0' 32 | } 33 | -------------------------------------------------------------------------------- /library/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/SilenceDut/Documents/developsoftware/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /library/src/androidTest/java/com/silencedut/asynctaskscheduler/ExampleInstrumentationTest.java: -------------------------------------------------------------------------------- 1 | package com.silencedut.asynctaskscheduler; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.filters.MediumTest; 6 | import android.support.test.runner.AndroidJUnit4; 7 | 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | 11 | 12 | import static org.junit.Assert.*; 13 | 14 | /** 15 | * Instrumentation test, which will execute on an Android device. 16 | * 17 | * @see Testing documentation 18 | */ 19 | @MediumTest 20 | @RunWith(AndroidJUnit4.class) 21 | public class ExampleInstrumentationTest { 22 | @Test 23 | public void useAppContext() throws Exception { 24 | // Context of the app under test. 25 | Context appContext = InstrumentationRegistry.getTargetContext(); 26 | 27 | assertEquals("com.silencedut.asynctaskscheduler.test", appContext.getPackageName()); 28 | } 29 | } -------------------------------------------------------------------------------- /library/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /library/src/main/java/com/silencedut/asynctaskscheduler/AsyncTaskScheduler.java: -------------------------------------------------------------------------------- 1 | package com.silencedut.asynctaskscheduler; 2 | 3 | import android.support.annotation.NonNull; 4 | 5 | import java.util.concurrent.CopyOnWriteArrayList; 6 | import java.util.concurrent.Executor; 7 | import java.util.concurrent.ExecutorService; 8 | import java.util.concurrent.Executors; 9 | import java.util.concurrent.ThreadFactory; 10 | import java.util.concurrent.atomic.AtomicInteger; 11 | 12 | /** 13 | * Created by SilenceDut on 16/7/21. 14 | * 15 | *

AsyncTaskScheduler is a better substitute good of AsyncTask.It has a default 16 | * CachedThreadPool, and you can change the default {@link ExecutorService} .use 17 | * {@link #execute} to execute a new SingleAsyncTask,and it can be called when when you 18 | * what,not like {@link android.os.AsyncTask} you can only called the execute once. 19 | * {@link #cancelTask} to cancel a SingleAsyncTask. you can manage all tasks 20 | * {@link SingleAsyncTask} easy by the method{@link #cancelAllTasks}. 21 | *

22 | * 23 | *

Attention

24 | * 25 | * you should call {@link #cancelTask} or {@link #cancelAllTasks} when on some life cycle 26 | * such as {@link onDestroy} avoid memory leak 27 | * 28 | *

for more information 29 | * see {@link []!(https://github.com/SilenceDut/AsncSingleTaskSample)} 30 | *

31 | * 32 | */ 33 | public class AsyncTaskScheduler { 34 | 35 | private final CopyOnWriteArrayList mSingleAsyncTaskList = new CopyOnWriteArrayList(); 36 | 37 | private static final ThreadFactory sThreadFactory = new ThreadFactory() { 38 | private final AtomicInteger mCount = new AtomicInteger(1); 39 | 40 | public Thread newThread(Runnable r) { 41 | 42 | return new Thread(r, "AsyncTaskScheduler Thread#" + mCount.getAndIncrement()); 43 | } 44 | }; 45 | 46 | public static final Executor CACHED_THREAD_POOL = Executors.newCachedThreadPool(sThreadFactory); 47 | 48 | private Executor mDefaultPoolExecutor ; 49 | 50 | 51 | /** 52 | * set an {@link Executor} that can be used to execute tasks in parallel as default . 53 | */ 54 | public AsyncTaskScheduler() { 55 | this.mDefaultPoolExecutor = CACHED_THREAD_POOL; 56 | } 57 | 58 | /** 59 | * you set an {@link Executor} that you what as default . 60 | */ 61 | public AsyncTaskScheduler(Executor defaultPoolExecutor ) { 62 | this.mDefaultPoolExecutor = defaultPoolExecutor; 63 | } 64 | 65 | public AsyncTaskScheduler execute(@NonNull SingleAsyncTask singleAsyncTask){ 66 | mDefaultPoolExecutor.execute(singleAsyncTask.getFutureTask()); 67 | mSingleAsyncTaskList.add(singleAsyncTask); 68 | return this; 69 | } 70 | 71 | 72 | /** 73 | cancel a singleAsyncTask 74 | */ 75 | public boolean cancelTask(SingleAsyncTask singleAsyncTask, boolean mayInterruptIfRunning) { 76 | return singleAsyncTask.cancel(mayInterruptIfRunning); 77 | } 78 | 79 | /** 80 | cancel all singleTask in the scheduler 81 | */ 82 | public void cancelAllTasks(boolean mayInterruptIfRunning){ 83 | for(SingleAsyncTask singleAsyncTask : mSingleAsyncTaskList) { 84 | cancelTask(singleAsyncTask,mayInterruptIfRunning); 85 | } 86 | mSingleAsyncTaskList.clear(); 87 | } 88 | 89 | // public void shutDown() { 90 | // mDefaultPoolExecutor.shutdownNow(); 91 | // synchronized (this) { 92 | // cancelAllTasks(true); 93 | // } 94 | // } 95 | // 96 | // public boolean isShutDown() { 97 | // return mDefaultPoolExecutor.isShutdown(); 98 | // } 99 | } 100 | 101 | -------------------------------------------------------------------------------- /library/src/main/java/com/silencedut/asynctaskscheduler/SingleAsyncTask.java: -------------------------------------------------------------------------------- 1 | package com.silencedut.asynctaskscheduler; 2 | 3 | import android.os.Binder; 4 | import android.os.Handler; 5 | import android.os.Looper; 6 | import android.os.Message; 7 | import android.support.annotation.MainThread; 8 | import android.support.annotation.WorkerThread; 9 | 10 | import java.util.concurrent.Callable; 11 | import java.util.concurrent.FutureTask; 12 | import java.util.concurrent.atomic.AtomicBoolean; 13 | 14 | /** 15 | * 16 | * 17 | * Created by SilenceDut on 16/7/21. 18 | * 19 | * 20 | *

SingleTaskTask enables proper and easy use of the UI thread. This class allows to 21 | * perform background{@link #doInBackground} operations and publish results 22 | * {@link #onExecuteSucceed} on the UI thread without having to 23 | * manipulate threads and/or handlers.

24 | * 25 | *

Usage

26 | *

SingleTaskTask is a abstract class ,must be subclassed to be used. The subclass 27 | * will override at least one method ({@link #doInBackground}), and most often will 28 | * override a second one ({@link #onExecuteSucceed}.),use {@link #cancel} to cancel a 29 | * task ,but the task may be stop at once , however {@link #onExecuteSucceed} will not 30 | * be invoked,{@link #onExecuteCancelled(Object)} will be invoked. 31 | * 32 | * you should call {@link #cancel} when on some life cycle 33 | * such as {@link onDestroy} avoid memory leak 34 | * 35 | */ 36 | 37 | 38 | 39 | public abstract class SingleAsyncTask { 40 | 41 | private final AtomicBoolean mIsCancelled = new AtomicBoolean(); 42 | 43 | private final static Handler sUIHandler = new InternalHandler(); 44 | 45 | private static final int SINGLE_TASK_EXECUTED_RESULT = 0x1; 46 | private static final int SINGLE_TASK_EXECUTED_PROGRESS = 0x2; 47 | private FutureTask mFutureResult; 48 | 49 | protected SingleAsyncTask() { 50 | 51 | Callable taskCallable = new Callable() { 52 | @Override 53 | public Result call() throws Exception { 54 | Binder.flushPendingCommands(); 55 | return doInBackground(); 56 | } 57 | }; 58 | 59 | mFutureResult = new FutureTask(taskCallable) { 60 | @Override 61 | protected void done() { 62 | super.done(); 63 | try { 64 | postResult(get()); 65 | } catch (Exception e) { 66 | onExecuteFailed(e); 67 | } 68 | } 69 | }; 70 | } 71 | 72 | public void executeSingle() { 73 | Thread workThread= new Thread(mFutureResult); 74 | workThread.start(); 75 | } 76 | 77 | private void postResult(Result result) { 78 | if(mIsCancelled.get()) { 79 | return; 80 | } 81 | sUIHandler.obtainMessage(SINGLE_TASK_EXECUTED_RESULT,new AsyncTaskResult(this,result)).sendToTarget(); 82 | } 83 | 84 | 85 | FutureTask getFutureTask() { 86 | return mFutureResult; 87 | } 88 | 89 | @WorkerThread 90 | protected abstract Result doInBackground(); 91 | 92 | @MainThread 93 | protected void onProgressUpdate(Progress values) { 94 | } 95 | 96 | @MainThread 97 | protected void onExecuteSucceed(Result result){ 98 | 99 | } 100 | 101 | @WorkerThread 102 | protected void onExecuteFailed(Exception exception){ 103 | 104 | } 105 | 106 | @MainThread 107 | protected void onExecuteCancelled(Result result){ 108 | 109 | } 110 | 111 | @WorkerThread 112 | protected final void publishProgress(Progress values) { 113 | if (!isCancelled()) { 114 | sUIHandler.obtainMessage(SINGLE_TASK_EXECUTED_PROGRESS, 115 | new AsyncTaskResult(this, values)).sendToTarget(); 116 | } 117 | } 118 | 119 | private void finish(Result result) { 120 | 121 | if (isCancelled()) { 122 | onExecuteCancelled(result); 123 | } else { 124 | onExecuteSucceed(result); 125 | } 126 | } 127 | 128 | public final boolean cancel(boolean mayInterruptIfRunning) { 129 | mIsCancelled.set(true); 130 | return mFutureResult.cancel(mayInterruptIfRunning); 131 | } 132 | 133 | 134 | public boolean isCancelled() { 135 | return mIsCancelled.get(); 136 | } 137 | 138 | 139 | private static class AsyncTaskResult { 140 | final SingleAsyncTask mSingleAsyncTask; 141 | final Data mData; 142 | 143 | 144 | AsyncTaskResult(SingleAsyncTask singleAsyncTask, Data data) { 145 | mSingleAsyncTask = singleAsyncTask; 146 | mData = data; 147 | } 148 | } 149 | 150 | private static class InternalHandler extends Handler { 151 | InternalHandler() { 152 | super(Looper.getMainLooper()); 153 | } 154 | @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) 155 | @Override 156 | public void handleMessage(Message msg) { 157 | AsyncTaskResult asyncTaskResult = (AsyncTaskResult) msg.obj; 158 | switch (msg.what) { 159 | case SINGLE_TASK_EXECUTED_RESULT: 160 | asyncTaskResult.mSingleAsyncTask.finish(asyncTaskResult.mData); 161 | break; 162 | case SINGLE_TASK_EXECUTED_PROGRESS: 163 | asyncTaskResult.mSingleAsyncTask.onProgressUpdate(asyncTaskResult.mData); 164 | break; 165 | } 166 | } 167 | } 168 | 169 | 170 | } -------------------------------------------------------------------------------- /library/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | AsyncTaskScheduler 3 | 4 | -------------------------------------------------------------------------------- /library/src/test/java/com/silencedut/asynctaskscheduler/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.silencedut.asynctaskscheduler; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() throws Exception { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':library' 2 | --------------------------------------------------------------------------------