Android EventBus2.4 如何自动切换到EventBus3.0
EventBus想必许多android开发项目都会用到.但是如果项目比较早 EventBus使用的是2.4,或者更早的版本.现在github EventBus的版本已经升级到了3.0 使用方法已经变化很大.
2.4系列写法如下 https://github.com/greenrobot/EventBus/blob/v2/HOWTO.md
通过实现固定名称的函数来接受事件.
而3.0系列通过注解实现 http://greenrobot.org/eventbus/documentation/delivery-threads-threadmode/
通过@Subscribe 比如
想必老项目如果手动改实现方法就很困难了.以下我使用gradle脚步来实现自动切换.具体情况可以再自己改
task replaceEventBusCall {
dolast ->
FileTree tree = fileTree(dir: 'src/main/java')
tree.include '**/*.java'
tree.each {
File file ->
def text = file.getText("utf-8")
if (text.contains("de.greenrobot.event.EventBus")) {
if(text.contains(" onEventMainThread(")) {
println file.getName() + "1 used eventbus"
text = text.replace("de.greenrobot.event.EventBus", "org.greenrobot.eventbus.EventBus")
} else {
println file.getName() + "2 used eventbus"
text = text.replace("de.greenrobot.event.EventBus;", "org.greenrobot.eventbus.EventBus;\nimport org.greenrobot.eventbus.Subscribe;\n" +
"import org.greenrobot.eventbus.ThreadMode;")
}
file.write(text, "utf-8")
}
file.eachLine("utf-8") {
if (it.contains(" onEventMainThread(")) {
def eventName
def index = it.indexOf("onEventMainThread")
println "1" + it
eventName = it.substring(index + "onEventMainThread(".length(), it.length())
println "2" + eventName
index = eventName.indexOf(" ")
eventName = eventName.substring(0, index)
println "3" + eventName
def methodName = it.replace("onEventMainThread","handle"+eventName)
println "4" + methodName
def methodtext = file.getText("utf-8")
methodtext = methodtext.replace("public void onEventMainThread(" + eventName, "@Subscribe(threadMode = ThreadMode.MAIN)\n public void handle" +eventName + "(" + eventName)
file.write(methodtext, "utf-8")
}
}
}
}
gradle 脚步的用法传送门 http://blog.csdn.net/yanbober/article/details/49314255