編輯:關於 Android 程式設計
先把原理說清楚
在 Eclipse 時代,AspectJ 有 AJDT 插件現成可用,編譯器與關鍵字提示都已經集成完畢。但到了 Android Studio,官方並沒有提供同等地位的插件支持,於是很多人就直接放棄了 AOP 這條路。其實只要理解 AspectJ 的工作方式,就會發現 IDE 只是外殼,真正的關鍵從來只有一個:編譯器。
AspectJ 做的事情非常單純——在編譯期把切面代碼織入(weave)到目標程序裡,運行時它和普通程序別無二致。完成這件事的工具就是 ajc。它負責在編譯階段建立目標類與切面代碼之間的聯繫,把切點(PointCut)命中的地方插入增強邏輯,AOP 的效果由此產生。
所以問題被簡化成一句話:無論你用哪個 IDE,只要想辦法讓它調用 ajc 去編譯代碼就行。命令行下直接執行 ajc 即可,IDE 下則需要一點配置功夫。
路線一:現成插件。GitHub 上有人封裝了 gradle-android-aspectj-plugin,裝上就能用。但實測下來它與 DataBinding 無法共存,而這個問題作者至今沒有修復。如果你的工程裡用了 DataBinding,這條路基本可以放棄。
路線二:手寫 Gradle 腳本。另一位國外開發者把織入邏輯直接寫進 build 腳本,同樣能在 Android Studio 裡跑起來。缺點是腳本裡定義的自定義任務對 Gradle 不熟的人不太友好,優點是可控、穩定,而且確實能繞開 DataBinding 之類的兼容問題。下面重點講這條路。
先照平常的方式建一個 Android 工程,再額外新建一個 Android Library 模塊用來放切面代碼。

依賴必須加在 module 裡,加到 app 工程上是沒有效果的——ajc 不會去織入那樣的目標代碼。這一點很多人第一次都踩過。
compile 'org.aspectj:aspectjrt:1.8.9'
主工程與 module 都要改腳本,目的是建立兩者的通信鏈路,並在 Java 編譯完成後追加一次織入。
build.gradle(app):
import org.aspectj.bridge.IMessage
import org.aspectj.bridge.MessageHandler
import org.aspectj.tools.ajc.Main
buildscript {
repositories { mavenCentral() }
dependencies { classpath 'org.aspectj:aspectjtools:1.8.9' }
}
apply plugin: 'com.android.application'
repositories { mavenCentral() }
dependencies { compile project(':aspectjlibrary') }
android {
compileSdkVersion 21
buildToolsVersion '22.0.1'
buildTypes {
debug { minifyEnabled false } // debug 下應關閉混淆
}
defaultConfig {
applicationId "com.example.lingyimly.try2"
minSdkVersion 15
targetSdkVersion 21
}
lintOptions { abortOnError true }
}
final def log = project.logger
final def variants = project.android.applicationVariants
variants.all { variant ->
if (!variant.buildType.isDebuggable()) {
log.debug("Skipping non-debuggable build type '${variant.buildType.name}'.")
return
}
JavaCompile javaCompile = variant.javaCompile
javaCompile.doLast {
String[] args = ["-showWeaveInfo", "-1.5",
"-inpath", javaCompile.destinationDir.toString(),
"-aspectpath", javaCompile.classpath.asPath,
"-d", javaCompile.destinationDir.toString(),
"-classpath", javaCompile.classpath.asPath,
"-bootclasspath", project.android.bootClasspath.join(File.pathSeparator)]
log.debug "ajc args: " + Arrays.toString(args)
MessageHandler handler = new MessageHandler(true)
new Main().run(args, handler)
for (IMessage message : handler.getMessages(null, true)) {
switch (message.getKind()) {
case IMessage.ABORT:
case IMessage.ERROR:
case IMessage.FAIL:
log.error message.message, message.thrown; break
case IMessage.WARNING:
log.warn message.message, message.thrown; break
case IMessage.INFO:
log.info message.message, message.thrown; break
case IMessage.DEBUG:
log.debug message.message, message.thrown; break
}
}
}
}
build.gradle(module):
import com.android.build.gradle.LibraryPlugin
import org.aspectj.bridge.IMessage
import org.aspectj.bridge.MessageHandler
import org.aspectj.tools.ajc.Main
apply plugin: 'com.android.library'
buildscript {
repositories { mavenCentral() }
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0'
classpath 'org.aspectj:aspectjtools:1.8.9'
classpath 'org.aspectj:aspectjweaver:1.8.9'
}
}
repositories { mavenCentral() }
dependencies {
compile 'org.aspectj:aspectjrt:1.8.9'
compile 'com.android.support:appcompat-v7:22.2.1'
}
android {
compileSdkVersion 22
buildToolsVersion '23.0.1'
lintOptions { abortOnError false }
}
android.libraryVariants.all { variant ->
LibraryPlugin plugin = project.plugins.getPlugin(LibraryPlugin)
JavaCompile javaCompile = variant.javaCompile
javaCompile.doLast {
String[] args = ["-showWeaveInfo", "-1.5",
"-inpath", javaCompile.destinationDir.toString(),
"-aspectpath", javaCompile.classpath.asPath,
"-d", javaCompile.destinationDir.toString(),
"-classpath", javaCompile.classpath.asPath,
"-bootclasspath", plugin.project.android.bootClasspath.join(File.pathSeparator)]
MessageHandler handler = new MessageHandler(true)
new Main().run(args, handler)
def log = project.logger
for (IMessage message : handler.getMessages(null, true)) {
switch (message.getKind()) {
case IMessage.ABORT:
case IMessage.ERROR:
case IMessage.FAIL:
log.error message.message, message.thrown; break
case IMessage.WARNING:
case IMessage.INFO:
log.info message.message, message.thrown; break
case IMessage.DEBUG:
log.debug message.message, message.thrown; break
}
}
}
}
切面類本體就是最普通的 AspectJ 寫法,用 @Aspect 標記,用 @Pointcut 定義切點,再用 @Around、@Before 等註解聲明增強。下面的例子同時演示了 execution 與 call 兩種切點的區別。
package com.example.lingyimly.aspectj;
import android.util.Log;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class TraceAspect {
private String TAG = "TAG ";
private static final String POINT_METHOD =
"execution(* com.example.lingyimly.try3.MainActivity.*(..))";
private static final String POINT_CALLMETHOD =
"call(* com.example.lingyimly.try3.MainActivity.*(..))";
@Pointcut(POINT_METHOD)
public void methodAnnotated() {}
@Pointcut(POINT_CALLMETHOD)
public void methodCallAnnotated() {}
@Around("methodAnnotated()")
public Object aroundWeaverPoint(ProceedingJoinPoint joinPoint) throws Throwable {
joinPoint.proceed();
String result = "----------------------------->aroundWeaverPoint";
Log.e(TAG, "----------------------------->aroundWeaverPoint");
return result; // 替換原方法的返回值
}
@Before("methodCallAnnotated()")
public void beforecall(JoinPoint joinPoint) {
Log.e(TAG, "beforecall");
}
}
編譯通過後,如果日志裡出現了切面中定義的輸出,說明織入已經成功生效:
05-27 21:01:30.618 E/TAG: beforecall
05-27 21:01:30.678 E/TAG: beforecall
05-27 21:01:30.678 E/TAG: ----------------------------->aroundWeaverPoint
05-27 21:01:30.678 E/TAG: MainActivity ----------------------------->aroundWeaverPoint
05-27 21:39:20.108 E/TAG: MainActivity From MainActivity
值得注意的是 @Around 增強可以修改返回值,這在沒有源代碼的第三方 SDK 上做埋點、性能監控、方法替換時非常有用,也是 AOP 在 Android 上最實際的價值所在。
DEMO 地址:AndroidAOP
Android 上的制表符(Tab)——一個能讓程式崩潰的神奇字符(cocos2dx crash)
今天測試時發現了遊戲裡的一個怪問題:系統郵件如果內含 tab 字符,在 Android 上一打開郵件內容就會 crash,而且同事很確定就是 tab 造成的。 憑我這幾個
android——App Widget 桌面小工具的完整實作
一、效果展示 在 Android 手機的桌面上,我們常能看到這樣的小元件: 在這些元件上,可以顯示 App 的一些重要交互資訊。以我最近開發的手機衛士為例,widget
怎麼用QQ號註冊微信?手機註冊後綁定QQ再解綁的做法
微信無法直接以QQ號註冊,必須先用手機號完成註冊。不過有一個繞道的方式:先用手機註冊,接著綁定QQ號,最後解除手機綁定——這樣一來,就能用QQ號登入微信了。QQ號註冊微信
Android 中利用 TextView 打造可點擊超鏈接的完整方案
前陣子在開發交流群裡,看到有人請教 Android 的 TextView 該如何實現自定義的超鏈接跳轉。舉個常見的例子:界面上有一串文字「使用本軟件,即表示您同意本軟件的