├── .gitignore ├── .idea ├── gradle.xml ├── misc.xml ├── modules.xml ├── runConfigurations.xml └── vcs.xml ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── cn │ │ └── leo │ │ └── magicthread │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── cn │ │ │ └── leo │ │ │ └── magicthread │ │ │ └── MainActivity.java │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── cn │ └── leo │ └── magicthread │ └── ExampleUnitTest.java ├── bintray.gradle ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── magic-lib ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ └── java │ └── cn │ └── leo │ └── magic │ ├── annotation │ ├── RunOnBackGround.java │ ├── RunOnCalcThread.java │ ├── RunOnIOThread.java │ └── RunOnUIThread.java │ ├── aspect │ └── ThreadAspect.java │ └── thread │ ├── CalcThreadPool.java │ ├── IOThreadPool.java │ ├── LifeCycleController.java │ ├── MagicRunnable.java │ └── ThreadController.java ├── magic-plugin ├── build.gradle └── src │ └── main │ ├── groovy │ └── cn │ │ └── leo │ │ └── magic_plugin │ │ └── MagicPlugin.groovy │ └── resources │ └── META-INF │ └── gradle-plugins │ ├── cn.leo.plugin.magic.properties │ └── magic.properties └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .externalNativeBuild 10 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 19 | 20 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 16 | 26 | 27 | 28 | 29 | 30 | 31 | 33 | 34 | 35 | 36 | 37 | 1.8 38 | 39 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MagicThread 2 | 安卓端、纯注解使用的线程切换框架 3 | 4 | ### how to use 5 | #### 一个注解搞定线程切换 6 | 7 | example: 8 | ``` 9 | @RunOnIOThread 10 | public void progress() { 11 |        for (int i = 0; i <= 100; i++) { 12 | showProgress(i); 13 | SystemClock.sleep(1000); 14 | } 15 | } 16 | 17 | @RunOnUIThread 18 | private void showProgress(int progress) { 19 | mTvTest.setText(progress + "%"); 20 | } 21 | ``` 22 | ### 框架提供4种线程注解: 23 | 24 | > @RunOnUIThread (被注解的方法在UI线程执行) 25 | 26 | > @RunOnIOThread (被注解的方法在子线程执行,适合IO密集型耗时操作(文件读写,网络请求)) 27 | 28 | > @RunOnCalcThread (被注解的方法在子线程执行,适合计算密集型耗时操作(大量消耗CPU的计算)) 29 | 30 | > @RunOnBackGround (被注解的方法在后台线程执行,所有被注解的方法都在同一个线程,队列执行,不适合耗时操作) 31 | 32 | > @RunOnUIThread(5000) 和 @RunOnBackGround(5000) 增加参数,为延时执行,单位毫秒值 33 | 34 | ### 依赖方法: 35 | #### To get a Git project into your build: 36 | #### Step 1. Add the JitPack repository to your build file 37 | 1.在全局build里面添加下面github仓库地址 38 | Add it in your root build.gradle at the end of repositories: 39 | ``` 40 | buildscript { 41 | ... 42 | dependencies { 43 | ... 44 | classpath 'cn.leo.plugin:magic-plugin:1.0.0' //java 用这个 45 | classpath 'com.hujiang.aspectjx:gradle-android-plugin-aspectjx:2.0.0' //kotlin 用这个 46 | } 47 | } 48 | allprojects { 49 | repositories { 50 | ... 51 | maven { url 'https://jitpack.io' } 52 | } 53 | } 54 | ``` 55 | google()和jcenter()这两个仓库一般是默认的,如果没有请加上 56 | 57 | #### Step 2. Add the dependency 58 | 2.在app的build里面添加插件和依赖 59 | ``` 60 | apply plugin: 'cn.leo.plugin.magic' //java 用这个 61 | apply plugin: 'android-aspectjx' //kotlin 用这个,编译速度会慢点 62 | ... 63 | dependencies { 64 | ... 65 | implementation 'com.github.jarryleo:MagicThread:v2.3' 66 | } 67 | ``` 68 | 69 | 70 | > 用于支持kotlin的插件用的是 [aspectjx](https://github.com/HujiangTechnology/gradle_plugin_android_aspectjx) 71 | > 感谢插件作者 72 | > 因为编织所有二进制文件的问题导致编译速度慢的问题,请查看原作者提供的解决方案 73 | 74 | ### 关于子线程在activity和fragment中进行耗时操作导致的内存泄漏,本框架提供解决办法: 75 | 76 | 在耗时操作的循环体中加入以下代码: 77 | ``` 78 | if (Thread.currentThread().isInterrupted()) return; 79 | ``` 80 | > 如果是采用休眠的耗时操作,请在捕获InterruptedException异常后跳出循环 81 | 82 | #### 注意: 83 | 只在注解 @RunOnIOThread 和 @RunOnCalcThread 的子线程中有效,利用了安卓新特性Lifecycle 84 | 85 | 其它2个注解不适合做耗时操作,不做处理 86 | 87 | ##### 请勿把注解打在有返回值的方法上,否则会失效!!!! 88 | 89 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | //AOP插件 3 | apply plugin: 'cn.leo.plugin.magic' 4 | 5 | android { 6 | compileSdkVersion 27 7 | defaultConfig { 8 | applicationId "cn.leo.magicthread" 9 | minSdkVersion 15 10 | targetSdkVersion 24 11 | versionCode 1 12 | versionName "1.0" 13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 14 | } 15 | buildTypes { 16 | release { 17 | minifyEnabled false 18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 19 | } 20 | } 21 | } 22 | 23 | dependencies { 24 | implementation fileTree(include: ['*.jar'], dir: 'libs') 25 | implementation 'com.android.support:appcompat-v7:27.1.1' 26 | implementation 'com.android.support.constraint:constraint-layout:1.1.2' 27 | testImplementation 'junit:junit:4.12' 28 | androidTestImplementation 'com.android.support.test:runner:1.0.2' 29 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' 30 | //implementation project(':magic-lib') 31 | //纯注解切换线程依赖 32 | implementation 'com.github.jarryleo:MagicThread:v2.3' 33 | } 34 | 35 | 36 | -------------------------------------------------------------------------------- /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/androidTest/java/cn/leo/magicthread/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magicthread; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumented test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("cn.leo.magicthread", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /app/src/main/java/cn/leo/magicthread/MainActivity.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magicthread; 2 | 3 | import android.os.Bundle; 4 | import android.os.SystemClock; 5 | import android.support.v7.app.AppCompatActivity; 6 | import android.util.Log; 7 | import android.view.View; 8 | import android.widget.TextView; 9 | import android.widget.Toast; 10 | 11 | import cn.leo.magic.annotation.RunOnCalcThread; 12 | import cn.leo.magic.annotation.RunOnUIThread; 13 | 14 | public class MainActivity extends AppCompatActivity { 15 | 16 | private TextView mTvTest; 17 | 18 | @Override 19 | protected void onCreate(Bundle savedInstanceState) { 20 | super.onCreate(savedInstanceState); 21 | setContentView(R.layout.activity_main); 22 | mTvTest = findViewById(R.id.tvTest); 23 | mTvTest.setOnClickListener(new View.OnClickListener() { 24 | @Override 25 | public void onClick(View v) { 26 | progress(); 27 | Log.e("-----", "跑完了"); 28 | testDelay(); 29 | } 30 | }); 31 | } 32 | 33 | @RunOnCalcThread 34 | public void progress() { 35 | for (int i = 0; i <= 10; i++) { 36 | //处理内存泄漏 37 | if (Thread.currentThread().isInterrupted()) { 38 | break; 39 | } 40 | Log.e("-----" + Thread.currentThread().getName(), "progress: " + i); 41 | showProgress(i); 42 | SystemClock.sleep(1000); 43 | } 44 | Log.e("-----", "跳出循环"); 45 | } 46 | 47 | @RunOnUIThread 48 | private void showProgress(int progress) { 49 | mTvTest.setText(progress + "%"); 50 | } 51 | 52 | @RunOnUIThread(5000) 53 | public void testDelay() { 54 | Toast.makeText(this, "延迟成功", Toast.LENGTH_SHORT).show(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 11 | 16 | 21 | 26 | 31 | 36 | 41 | 46 | 51 | 56 | 61 | 66 | 71 | 76 | 81 | 86 | 91 | 96 | 101 | 106 | 111 | 116 | 121 | 126 | 131 | 136 | 141 | 146 | 151 | 156 | 161 | 166 | 171 | 172 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarryleo/MagicThread/4f74c5ad261513d8ba0d08b3801afc1094cf2191/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarryleo/MagicThread/4f74c5ad261513d8ba0d08b3801afc1094cf2191/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarryleo/MagicThread/4f74c5ad261513d8ba0d08b3801afc1094cf2191/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarryleo/MagicThread/4f74c5ad261513d8ba0d08b3801afc1094cf2191/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarryleo/MagicThread/4f74c5ad261513d8ba0d08b3801afc1094cf2191/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarryleo/MagicThread/4f74c5ad261513d8ba0d08b3801afc1094cf2191/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarryleo/MagicThread/4f74c5ad261513d8ba0d08b3801afc1094cf2191/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarryleo/MagicThread/4f74c5ad261513d8ba0d08b3801afc1094cf2191/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarryleo/MagicThread/4f74c5ad261513d8ba0d08b3801afc1094cf2191/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarryleo/MagicThread/4f74c5ad261513d8ba0d08b3801afc1094cf2191/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | MagicThread 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/test/java/cn/leo/magicthread/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magicthread; 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 | } -------------------------------------------------------------------------------- /bintray.gradle: -------------------------------------------------------------------------------- 1 | // 应用插件 2 | apply plugin: 'com.jfrog.bintray' 3 | apply plugin: 'maven-publish' 4 | 5 | def baseUrl = 'https://github.com/jarryleo' 6 | def siteUrl = baseUrl 7 | def gitUrl = "${baseUrl}/MagicThread" 8 | def issueUrl = "${baseUrl}/issues" 9 | 10 | install { 11 | repositories { 12 | mavenInstaller { 13 | // This generates POM.xml with proper paramters 14 | pom.project { 15 | 16 | //添加项目描述 17 | name 'Magic Thread Gradle Plugin for Android' 18 | url siteUrl 19 | 20 | //设置开源证书信息 21 | licenses { 22 | license { 23 | name 'The Apache Software License, Version 2.0' 24 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt' 25 | } 26 | } 27 | //添加开发者信息 28 | developers { 29 | developer { 30 | name 'JarryLeo' 31 | email 'yjtx256@qq.com' 32 | } 33 | } 34 | 35 | scm { 36 | connection gitUrl 37 | developerConnection gitUrl 38 | url siteUrl 39 | } 40 | } 41 | } 42 | 43 | } 44 | } 45 | 46 | 47 | //配置上传Bintray相关信息 48 | bintray { 49 | user = 'xxxxxx' 50 | key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' 51 | 52 | configurations = ['archives'] 53 | pkg { 54 | repo = 'maven' // 上传到中央仓库的名称 55 | name = 'magic-plugin' // 上传到jcenter 的项目名称 56 | desc = 'magic thread gradle' // 项目描述 57 | websiteUrl = siteUrl 58 | issueTrackerUrl = issueUrl 59 | vcsUrl = gitUrl 60 | labels = ['gradle', 'plugin'] 61 | licenses = ['Apache-2.0'] 62 | publish = true 63 | } 64 | } -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | 5 | repositories { 6 | google() 7 | jcenter() 8 | } 9 | dependencies { 10 | classpath 'com.android.tools.build:gradle:3.0.1' 11 | // 将项目发布到JCenter 所需要的jar 添加依赖 12 | classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3' 13 | classpath 'com.github.dcendents:android-maven-plugin:1.2' 14 | classpath 'cn.leo.plugin:magic-plugin:1.0.0' 15 | } 16 | } 17 | 18 | allprojects { 19 | repositories { 20 | google() 21 | jcenter() 22 | maven { url 'https://jitpack.io' } 23 | } 24 | } 25 | 26 | task clean(type: Delete) { 27 | delete rootProject.buildDir 28 | } 29 | -------------------------------------------------------------------------------- /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/jarryleo/MagicThread/4f74c5ad261513d8ba0d08b3801afc1094cf2191/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue May 08 17:30:06 CST 2018 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-4.1-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 | -------------------------------------------------------------------------------- /magic-lib/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /magic-lib/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'cn.leo.plugin.magic' 3 | 4 | android { 5 | compileSdkVersion 27 6 | } 7 | 8 | dependencies { 9 | compileOnly 'com.android.support:appcompat-v7:27.1.1' 10 | } -------------------------------------------------------------------------------- /magic-lib/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 | -------------------------------------------------------------------------------- /magic-lib/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | -------------------------------------------------------------------------------- /magic-lib/src/main/java/cn/leo/magic/annotation/RunOnBackGround.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magic.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * Created by Leo on 2018/5/2. 10 | */ 11 | @Target(ElementType.METHOD) 12 | @Retention(RetentionPolicy.RUNTIME) 13 | public @interface RunOnBackGround { 14 | int value() default -1; 15 | } 16 | -------------------------------------------------------------------------------- /magic-lib/src/main/java/cn/leo/magic/annotation/RunOnCalcThread.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magic.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * Created by Leo on 2018/5/2. 10 | */ 11 | @Target(ElementType.METHOD) 12 | @Retention(RetentionPolicy.RUNTIME) 13 | public @interface RunOnCalcThread { 14 | 15 | } 16 | -------------------------------------------------------------------------------- /magic-lib/src/main/java/cn/leo/magic/annotation/RunOnIOThread.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magic.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * Created by Leo on 2018/5/2. 10 | */ 11 | @Target(ElementType.METHOD) 12 | @Retention(RetentionPolicy.RUNTIME) 13 | public @interface RunOnIOThread { 14 | 15 | } 16 | -------------------------------------------------------------------------------- /magic-lib/src/main/java/cn/leo/magic/annotation/RunOnUIThread.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magic.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * Created by Leo on 2018/5/2. 10 | */ 11 | @Target(ElementType.METHOD) 12 | @Retention(RetentionPolicy.RUNTIME) 13 | public @interface RunOnUIThread { 14 | int value() default -1; 15 | } 16 | -------------------------------------------------------------------------------- /magic-lib/src/main/java/cn/leo/magic/aspect/ThreadAspect.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magic.aspect; 2 | 3 | import android.arch.lifecycle.LifecycleOwner; 4 | import android.util.Log; 5 | 6 | import org.aspectj.lang.ProceedingJoinPoint; 7 | import org.aspectj.lang.annotation.AfterReturning; 8 | import org.aspectj.lang.annotation.Around; 9 | import org.aspectj.lang.annotation.Aspect; 10 | import org.aspectj.lang.annotation.Pointcut; 11 | import org.aspectj.lang.reflect.MethodSignature; 12 | 13 | import java.lang.reflect.Method; 14 | 15 | import cn.leo.magic.annotation.RunOnBackGround; 16 | import cn.leo.magic.annotation.RunOnUIThread; 17 | import cn.leo.magic.thread.LifeCycleController; 18 | import cn.leo.magic.thread.MagicRunnable; 19 | import cn.leo.magic.thread.ThreadController; 20 | 21 | /** 22 | * Created by Leo on 2018/5/2. 23 | */ 24 | @Aspect 25 | public class ThreadAspect { 26 | LifeCycleController mLifeCycleController = new LifeCycleController(); 27 | 28 | private static final String UI_THREAD = 29 | "execution(@cn.leo.magic.annotation.RunOnUIThread * *(..))"; 30 | private static final String IO_THREAD = 31 | "execution(@cn.leo.magic.annotation.RunOnIOThread * *(..))"; 32 | private static final String CALC_THREAD = 33 | "execution(@cn.leo.magic.annotation.RunOnCalcThread * *(..))"; 34 | private static final String BACK_THREAD = 35 | "execution(@cn.leo.magic.annotation.RunOnBackGround * *(..))"; 36 | 37 | @Pointcut(UI_THREAD) 38 | public void methodRunOnUIThread() { 39 | } 40 | 41 | @Pointcut(IO_THREAD) 42 | public void methodRunOnIOThread() { 43 | } 44 | 45 | @Pointcut(CALC_THREAD) 46 | public void methodRunOnCalcThread() { 47 | } 48 | 49 | @Pointcut(BACK_THREAD) 50 | public void methodRunOnBackGround() { 51 | } 52 | 53 | @Around("methodRunOnUIThread()") 54 | public void aroundJoinPointUI(final ProceedingJoinPoint joinPoint) { 55 | if (!Thread.currentThread().isInterrupted()) { 56 | MethodSignature signature = (MethodSignature) joinPoint.getSignature(); 57 | Method method = signature.getMethod(); 58 | RunOnUIThread annotation = method.getAnnotation(RunOnUIThread.class); 59 | int delayMillis = annotation.value(); 60 | ThreadController.runOnUIThread(getRunnable(joinPoint), delayMillis); 61 | } 62 | } 63 | 64 | @Around("methodRunOnIOThread()") 65 | public void aroundJoinPointIO(final ProceedingJoinPoint joinPoint) { 66 | ThreadController.runOnIOThread(getRunnable(joinPoint)); 67 | } 68 | 69 | @Around("methodRunOnCalcThread()") 70 | public void aroundJoinPointCalc(final ProceedingJoinPoint joinPoint) { 71 | ThreadController.runOnCalcThread(getRunnable(joinPoint)); 72 | } 73 | 74 | @Around("methodRunOnBackGround()") 75 | public void aroundJoinPointBack(final ProceedingJoinPoint joinPoint) { 76 | if (!Thread.currentThread().isInterrupted()) { 77 | MethodSignature signature = (MethodSignature) joinPoint.getSignature(); 78 | Method method = signature.getMethod(); 79 | RunOnBackGround annotation = method.getAnnotation(RunOnBackGround.class); 80 | int delayMillis = annotation.value(); 81 | ThreadController.runOnBackThread(getRunnable(joinPoint), delayMillis); 82 | } 83 | } 84 | 85 | @AfterReturning(pointcut = "methodRunOnIOThread()", 86 | returning = "retVal") 87 | public void afterJoinPointIO(Object retVal) { 88 | if (retVal != null) { 89 | Log.e("MagicThread:", "线程转换注解的方法不能有返回值"); 90 | } 91 | } 92 | 93 | public MagicRunnable getRunnable(final ProceedingJoinPoint joinPoint) { 94 | final Object target = joinPoint.getTarget(); 95 | MagicRunnable runnable = new MagicRunnable() { 96 | @Override 97 | public void run() { 98 | super.run(); 99 | try { 100 | joinPoint.proceed(); 101 | if (target instanceof LifecycleOwner) { 102 | mLifeCycleController.unSubscribe((LifecycleOwner) target, this); 103 | } 104 | } catch (Throwable throwable) { 105 | throwable.printStackTrace(); 106 | } 107 | } 108 | }; 109 | if (target instanceof LifecycleOwner) { 110 | mLifeCycleController.subscribe((LifecycleOwner) target, runnable); 111 | } 112 | return runnable; 113 | } 114 | 115 | } 116 | -------------------------------------------------------------------------------- /magic-lib/src/main/java/cn/leo/magic/thread/CalcThreadPool.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magic.thread; 2 | 3 | import java.util.concurrent.BlockingQueue; 4 | import java.util.concurrent.Executor; 5 | import java.util.concurrent.LinkedBlockingQueue; 6 | import java.util.concurrent.ThreadFactory; 7 | import java.util.concurrent.ThreadPoolExecutor; 8 | import java.util.concurrent.TimeUnit; 9 | import java.util.concurrent.atomic.AtomicInteger; 10 | 11 | /** 12 | * @author Leo 13 | */ 14 | public class CalcThreadPool { 15 | private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); 16 | private static final int CORE_POOL_SIZE = CPU_COUNT + 1; 17 | private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1; 18 | private static final int KEEP_ALIVE = 1; 19 | 20 | private static final ThreadFactory sThreadFactory = new ThreadFactory() { 21 | //线程安全的递加操作 22 | private final AtomicInteger mCount = new AtomicInteger(1); 23 | 24 | @Override 25 | public Thread newThread(Runnable r) { 26 | return new Thread(r, "CalcThread #" + mCount.getAndIncrement()); 27 | } 28 | }; 29 | 30 | /** 31 | * 超出线程池容量后的的排队队列,超出队列容量后将抛出异常 32 | */ 33 | private static final BlockingQueue sPoolWorkQueue = 34 | new LinkedBlockingQueue<>(128); 35 | /** 36 | * An {@link Executor} that can be used to execute tasks in parallel. 37 | */ 38 | public static ThreadPoolExecutor THREAD_POOL_EXECUTOR; 39 | 40 | 41 | /** 42 | * 执行任务,当线程池处于关闭,将会创建新的线程池 43 | */ 44 | public synchronized static void execute(Runnable run) { 45 | if (run == null) { 46 | return; 47 | } 48 | if (THREAD_POOL_EXECUTOR == null || THREAD_POOL_EXECUTOR.isShutdown()) { 49 | // 参数说明 50 | // 当线程池中的线程小于mCorePoolSize,直接创建新的线程加入线程池执行任务 51 | // 当线程池中的线程数目等于mCorePoolSize,将会把任务放入任务队列sPoolWorkQueue中 52 | // 当sPoolWorkQueue中的任务放满了,将会创建新的线程去执行, 53 | // 但是当总线程数大于mMaximumPoolSize时,将会抛出异常,交给RejectedExecutionHandler处理 54 | // mKeepAliveTime是线程执行完任务后,且队列中没有可以执行的任务,存活的时间,后面的参数是时间单位 55 | // ThreadFactory是每次创建新的线程工厂 56 | /**这是一个适合CPU密集型线程池*/ 57 | THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, 58 | TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory); 59 | } 60 | THREAD_POOL_EXECUTOR.execute(run); 61 | } 62 | 63 | /** 64 | * 取消线程池中某个还未执行的任务 65 | */ 66 | public synchronized static void cancel(Runnable run) { 67 | if (isThreadPoolAlive()) { 68 | THREAD_POOL_EXECUTOR.remove(run); 69 | } 70 | } 71 | 72 | /** 73 | * 线程池中是否包含某个任务 74 | */ 75 | public synchronized static boolean contains(Runnable run) { 76 | if (isThreadPoolAlive()) { 77 | return THREAD_POOL_EXECUTOR.getQueue().contains(run); 78 | } else { 79 | return false; 80 | } 81 | } 82 | 83 | /** 84 | * 立刻关闭线程池,停止所有任务,包括等待的任务。 85 | */ 86 | public synchronized static void stop() { 87 | if (isThreadPoolAlive()) { 88 | THREAD_POOL_EXECUTOR.shutdownNow(); 89 | } 90 | } 91 | 92 | /** 93 | * 关闭线程池,不再接受新的任务。但已经加入的任务都将会被执行完毕才关闭 94 | */ 95 | public synchronized static void shutdown() { 96 | if (isThreadPoolAlive()) { 97 | THREAD_POOL_EXECUTOR.shutdown(); 98 | } 99 | } 100 | 101 | private static boolean isThreadPoolAlive() { 102 | return THREAD_POOL_EXECUTOR != null && 103 | (!THREAD_POOL_EXECUTOR.isShutdown() || 104 | THREAD_POOL_EXECUTOR.isTerminating()); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /magic-lib/src/main/java/cn/leo/magic/thread/IOThreadPool.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magic.thread; 2 | 3 | import java.util.concurrent.BlockingQueue; 4 | import java.util.concurrent.Executor; 5 | import java.util.concurrent.Executors; 6 | import java.util.concurrent.SynchronousQueue; 7 | import java.util.concurrent.ThreadFactory; 8 | import java.util.concurrent.ThreadPoolExecutor; 9 | import java.util.concurrent.TimeUnit; 10 | import java.util.concurrent.atomic.AtomicInteger; 11 | 12 | /** 13 | * @author Leo 14 | */ 15 | public class IOThreadPool { 16 | private static final int CORE_POOL_SIZE = 0; 17 | private static final int MAXIMUM_POOL_SIZE = Integer.MAX_VALUE; 18 | private static final int KEEP_ALIVE = 30; 19 | 20 | private static final ThreadFactory sThreadFactory = new ThreadFactory() { 21 | //线程安全的递加操作 22 | private final AtomicInteger mCount = new AtomicInteger(1); 23 | 24 | @Override 25 | public Thread newThread(Runnable r) { 26 | return new Thread(r, "IOThread #" + mCount.getAndIncrement()); 27 | } 28 | }; 29 | 30 | /** 31 | * 无限队列 32 | */ 33 | private static final BlockingQueue sPoolWorkQueue = 34 | new SynchronousQueue<>(); 35 | /** 36 | * An {@link Executor} that can be used to execute tasks in parallel. 37 | */ 38 | public static ThreadPoolExecutor THREAD_POOL_EXECUTOR; 39 | 40 | 41 | /** 42 | * 执行任务,当线程池处于关闭,将会创建新的线程池 43 | */ 44 | public synchronized static void execute(Runnable run) { 45 | if (run == null) { 46 | return; 47 | } 48 | if (THREAD_POOL_EXECUTOR == null || THREAD_POOL_EXECUTOR.isShutdown()) { 49 | // 参数说明 50 | // 当线程池中的线程小于mCorePoolSize,直接创建新的线程加入线程池执行任务 51 | // 当线程池中的线程数目等于mCorePoolSize,将会把任务放入任务队列sPoolWorkQueue中 52 | // 当sPoolWorkQueue中的任务放满了,将会创建新的线程去执行, 53 | // 但是当总线程数大于mMaximumPoolSize时,将会抛出异常,交给RejectedExecutionHandler处理 54 | // mKeepAliveTime是线程执行完任务后,且队列中没有可以执行的任务,存活的时间,后面的参数是时间单位 55 | // ThreadFactory是每次创建新的线程工厂 56 | /**IO密集型线程池*/ 57 | THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, 58 | TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory); 59 | } 60 | THREAD_POOL_EXECUTOR.execute(run); 61 | 62 | } 63 | 64 | /** 65 | * 取消线程池中某个还未执行的任务 66 | */ 67 | public synchronized static void cancel(Runnable run) { 68 | if (isThreadPoolAlive()) { 69 | THREAD_POOL_EXECUTOR.remove(run); 70 | } 71 | } 72 | 73 | /** 74 | * 线程池中是否包含某个任务 75 | */ 76 | public synchronized static boolean contains(Runnable run) { 77 | if (isThreadPoolAlive()) { 78 | return THREAD_POOL_EXECUTOR.getQueue().contains(run); 79 | } else { 80 | return false; 81 | } 82 | } 83 | 84 | /** 85 | * 立刻关闭线程池,停止所有任务,包括等待的任务。 86 | */ 87 | public synchronized static void stop() { 88 | if (isThreadPoolAlive()) { 89 | THREAD_POOL_EXECUTOR.shutdownNow(); 90 | } 91 | } 92 | 93 | /** 94 | * 关闭线程池,不再接受新的任务。但已经加入的任务都将会被执行完毕才关闭 95 | */ 96 | public synchronized static void shutdown() { 97 | if (isThreadPoolAlive()) { 98 | THREAD_POOL_EXECUTOR.shutdown(); 99 | } 100 | } 101 | 102 | private static boolean isThreadPoolAlive() { 103 | return THREAD_POOL_EXECUTOR != null && 104 | (!THREAD_POOL_EXECUTOR.isShutdown() || 105 | THREAD_POOL_EXECUTOR.isTerminating()); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /magic-lib/src/main/java/cn/leo/magic/thread/LifeCycleController.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magic.thread; 2 | 3 | import android.arch.lifecycle.Lifecycle; 4 | import android.arch.lifecycle.LifecycleObserver; 5 | import android.arch.lifecycle.LifecycleOwner; 6 | import android.arch.lifecycle.OnLifecycleEvent; 7 | 8 | import java.util.ArrayList; 9 | import java.util.Collections; 10 | import java.util.List; 11 | import java.util.concurrent.ConcurrentHashMap; 12 | 13 | /** 14 | * @author Leo 15 | * @date 2018/5/9 16 | */ 17 | 18 | public class LifeCycleController implements LifecycleObserver { 19 | 20 | 21 | private static ConcurrentHashMap> mTasks = new ConcurrentHashMap<>(); 22 | 23 | public synchronized void subscribe(LifecycleOwner lifecycleOwner, MagicRunnable runnable) { 24 | lifecycleOwner.getLifecycle().addObserver(this); 25 | if (!mTasks.containsKey(lifecycleOwner)) { 26 | List runnableList = Collections.synchronizedList(new ArrayList()); 27 | runnableList.add(runnable); 28 | mTasks.put(lifecycleOwner, runnableList); 29 | } else { 30 | List runnableList = mTasks.get(lifecycleOwner); 31 | runnableList.add(runnable); 32 | } 33 | } 34 | 35 | public synchronized void unSubscribe(LifecycleOwner lifecycleOwner, MagicRunnable runnable) { 36 | if (mTasks.containsKey(lifecycleOwner)) { 37 | List runnableList = mTasks.get(lifecycleOwner); 38 | runnableList.remove(runnable); 39 | } 40 | } 41 | 42 | @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) 43 | public synchronized void onDestroy(LifecycleOwner source) { 44 | List runnableList = mTasks.get(source); 45 | for (MagicRunnable runnable : runnableList) { 46 | ThreadController.removeTask(runnable); 47 | } 48 | mTasks.remove(source); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /magic-lib/src/main/java/cn/leo/magic/thread/MagicRunnable.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magic.thread; 2 | 3 | import android.support.annotation.CallSuper; 4 | 5 | /** 6 | * 7 | * @author Leo 8 | * @date 2018/5/10 9 | */ 10 | 11 | public abstract class MagicRunnable implements Runnable { 12 | private Thread mThread; 13 | 14 | public void stop() { 15 | if (mThread != null && !mThread.isInterrupted()) { 16 | mThread.interrupt(); 17 | } 18 | } 19 | 20 | @CallSuper 21 | @Override 22 | public void run() { 23 | mThread = Thread.currentThread(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /magic-lib/src/main/java/cn/leo/magic/thread/ThreadController.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magic.thread; 2 | 3 | import android.os.Handler; 4 | import android.os.HandlerThread; 5 | import android.os.Looper; 6 | 7 | /** 8 | * @author Leo 9 | * @date 2018/5/9 10 | */ 11 | 12 | public class ThreadController { 13 | private static final HandlerThread mHandlerThread = new HandlerThread("Thread BackGround"); 14 | private static final Handler mBackHandler; 15 | private static final Handler mUIHandler; 16 | 17 | static { 18 | mHandlerThread.start(); 19 | mBackHandler = new Handler(mHandlerThread.getLooper()); 20 | mUIHandler = new Handler(Looper.getMainLooper()); 21 | } 22 | 23 | public static void runOnUIThread(MagicRunnable runnable, int delayMillis) { 24 | if (delayMillis > 0) { 25 | mUIHandler.postDelayed(runnable, delayMillis); 26 | } else { 27 | mUIHandler.post(runnable); 28 | } 29 | } 30 | 31 | public static void runOnIOThread(MagicRunnable runnable) { 32 | IOThreadPool.execute(runnable); 33 | } 34 | 35 | public static void runOnCalcThread(MagicRunnable runnable) { 36 | CalcThreadPool.execute(runnable); 37 | } 38 | 39 | public static void runOnBackThread(MagicRunnable runnable, int delayMillis) { 40 | if (delayMillis > 0) { 41 | mBackHandler.postDelayed(runnable, delayMillis); 42 | } else { 43 | mBackHandler.post(runnable); 44 | } 45 | } 46 | 47 | public static void removeTask(MagicRunnable runnable) { 48 | mUIHandler.removeCallbacks(runnable); 49 | mBackHandler.removeCallbacks(runnable); 50 | IOThreadPool.cancel(runnable); 51 | CalcThreadPool.cancel(runnable); 52 | runnable.stop(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /magic-plugin/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | apply plugin: 'groovy' 3 | apply plugin: "maven" 4 | 5 | sourceCompatibility = "1.7" 6 | targetCompatibility = "1.7" 7 | 8 | dependencies { 9 | compile gradleApi() 10 | compile localGroovy() 11 | compile 'com.android.tools.build:gradle:3.0.1' 12 | compile 'org.aspectj:aspectjtools:1.8.9' 13 | compile 'org.aspectj:aspectjrt:1.8.9' 14 | } 15 | 16 | // 代码仓库 17 | repositories { 18 | jcenter() 19 | } 20 | 21 | group = 'cn.leo.plugin' // 组名 22 | version = '1.0.0' // 版本 23 | 24 | //上传本地 25 | */ 26 | /*uploadArchives { 27 | repositories { 28 | mavenDeployer { 29 | repository(url: uri('../per_plug')) 30 | pom.groupId = 'cn.leo.plugin' // 组名 31 | pom.artifactId = 'permission' // 插件名 32 | pom.version = '1.0.0' // 版本号 33 | } 34 | } 35 | }*//* 36 | 37 | 38 | // 应用插件 39 | apply from: '../bintray.gradle' 40 | */ 41 | -------------------------------------------------------------------------------- /magic-plugin/src/main/groovy/cn/leo/magic_plugin/MagicPlugin.groovy: -------------------------------------------------------------------------------- 1 | package cn.leo.magic_plugin 2 | 3 | import com.android.build.gradle.AppPlugin 4 | import com.android.build.gradle.LibraryPlugin 5 | import org.aspectj.bridge.IMessage 6 | import org.aspectj.bridge.MessageHandler 7 | import org.aspectj.tools.ajc.Main 8 | import org.gradle.api.Plugin 9 | import org.gradle.api.Project 10 | import org.gradle.api.tasks.compile.JavaCompile 11 | 12 | class MagicPlugin implements Plugin { 13 | @Override 14 | void apply(Project project) { 15 | def hasApp = project.plugins.withType(AppPlugin) 16 | def hasLib = project.plugins.withType(LibraryPlugin) 17 | if (!hasApp && !hasLib) { 18 | throw new IllegalStateException("'android' or 'android-library' plugin required.") 19 | } 20 | 21 | final def log = project.logger 22 | final def variants 23 | if (hasApp) { 24 | variants = project.android.applicationVariants 25 | } else { 26 | variants = project.android.libraryVariants 27 | } 28 | 29 | project.dependencies { 30 | implementation 'org.aspectj:aspectjrt:1.8.9' 31 | } 32 | 33 | variants.all { variant -> 34 | 35 | JavaCompile javaCompile = variant.javaCompile 36 | javaCompile.doLast { 37 | String[] args = [ 38 | "-showWeaveInfo", 39 | "-1.8", 40 | "-inpath", javaCompile.destinationDir.toString(), 41 | "-aspectpath", javaCompile.classpath.asPath, 42 | "-d", javaCompile.destinationDir.toString(), 43 | "-classpath", javaCompile.classpath.asPath, 44 | "-bootclasspath", project.android.bootClasspath.join(File.pathSeparator) 45 | ] 46 | log.debug "ajc args: " + Arrays.toString(args) 47 | 48 | MessageHandler handler = new MessageHandler(true); 49 | new Main().run(args, handler) 50 | for (IMessage message : handler.getMessages(null, true)) { 51 | switch (message.getKind()) { 52 | case IMessage.ABORT: 53 | case IMessage.ERROR: 54 | case IMessage.FAIL: 55 | log.error message.message, message.thrown 56 | break 57 | case IMessage.WARNING: 58 | log.warn message.message, message.thrown 59 | break 60 | case IMessage.INFO: 61 | log.info message.message, message.thrown 62 | break 63 | case IMessage.DEBUG: 64 | log.debug message.message, message.thrown 65 | break 66 | } 67 | } 68 | } 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /magic-plugin/src/main/resources/META-INF/gradle-plugins/cn.leo.plugin.magic.properties: -------------------------------------------------------------------------------- 1 | implementation-class=cn.leo.magic_plugin.MagicPlugin -------------------------------------------------------------------------------- /magic-plugin/src/main/resources/META-INF/gradle-plugins/magic.properties: -------------------------------------------------------------------------------- 1 | implementation-class=cn.leo.magic_plugin.MagicPlugin -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':magic-lib', ':magic-plugin' 2 | --------------------------------------------------------------------------------