-
Notifications
You must be signed in to change notification settings - Fork 67
RouterTask 详解
Wiki edited this page Sep 8, 2019
·
1 revision
RouterTask 是无需下沉Class的组件间通信组件,支持跨Project调用,支持支持Flutter、Hybrid H5。
-
自动生成启动构造器。
-
支持 URL 调用。
-
支持参数注入。
-
支持Flutter、Hybrid H5。
-
支持服务降级。
在Module中创建服务类,然后点击顶部菜单 Build
的 Make Module XXX
就在 GDelegateCenter 中生成构造器方法。
@RouterTask(path = "getUser")
public class GetUserTask extends GRouterTask {
@RouterField
public int uid;
@RouterField
public String name;
@Override
public Object process() {
// do something
return new User(uid, "Wiki");
}
}
// URL方式调用
val response = GRouter.getInstance().taskBuilder("grouter://task/getUser?uid=1").execute()
// 普通构造器调用
val response = GRouter.getInstance().taskBuilder("getUser").put("uid",1).execute()
// 自动构造器调用: 推荐
val response = GTaskCenter.GetUserTask().uid(1).execute()
直接获取返回的对象:
val user = response.value(User::class.java)
获取返回对象的某个字段:
val userName = response.map()["name"]
获取返回的json序列化String:
val text = response.string()
反序列化获取对象,当另外一个工程没有包含User.class,但是希望返回对象,可以创建一个数据结构和User一样的类,通过getDeserializeObject返回对象。
class UserB : Serializable {
var uid: Int? = null
var name: String? = null
}
val user = response.value(UserB::class.java)
// 反系列化 List
val users = response.list(UserB::class.java)
val exception = response.exception
如果是URL调用,RouterField参数支持类型:int、long、float、double、boolean、Integer、Long、Double、Float、Boolean、String、int[]、long[]、float[]、double[]、boolean[]、String[]、可序列化List、可序列化Object。如果是构造器调用,支持任意类型参数。
解析List和对象,必须在Application#onCreate设置GRouter.setSerialization(),根据自己项目的实际情况提供json序列化方法。
class WebViewActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_web_view)
web_view.settings.javaScriptEnabled = true
web_view.addJavascriptInterface(GRouterJavascriptInterface(this), "grouter")
web_view.webChromeClient = WebChromeClient()
web_view.loadUrl("file:///android_asset/grouter_example.html")
}
}
Javascript
<script>
function executeTask(){
var user = window.grouter.executeTask("grouter://task/getUser?name=Wiki&uid=1")
alert(user)
}
</script>
####支持Flutter
创建插件类
class GRouterFlutterPlugin(val activity: Activity) : MethodChannel.MethodCallHandler {
fun onMethodCall(methodCall: MethodCall, result: MethodChannel.Result) {
if (methodCall.method.equals("executeTask")) {
val url = methodCall.argument("url")
val response = GRouter.getInstance().getTask(url).execute()
if (response.isError){
result.error(response.exception.message,null,null)
}else{
result.success(response.string());
}
}
}
companion object {
fun registerWith(registry: PluginRegistry) {
val CHANNEL = "com.gourer/plugin"
val registrar = registry.registrarFor(CHANNEL)
val methodChannel = MethodChannel(registrar.messenger(), CHANNEL)
val plugin = GRouterFlutterPlugin(registrar.activity())
methodChannel.setMethodCallHandler(plugin)
}
}
}
在Activity中注册
class MainActivity : FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
GeneratedPluginRegistrant.registerWith(this)
GRouterFlutterPlugin.registerWith(this)
}
}
在Flutter中调用
static const grouterPlugin = const MethodChannel('com.gourer/plugin');
void getUser() async {
Map<String, Object> map = {"url": "grouter://task/getUser?uid=1"};
try {
String result = await grouterPlugin.invokeMethod("executeTask", map);
print(result);
} on PlatformException catch (e) {
print(e.message);
}
}
当我们需要单Module运行的时候,可以通过服务降级来模拟服务返回数据
class DebugMockIntercepter : GRouterInterceptor() {
override fun process(request: TaskRequest): Boolean {
if (request.taskClass == GetUserTask::class.java.name) {
val uid = request.params["uid"].toString().toInt()
request.onContinueResult(User(uid, "MockUser"))
return true
}
if (request.path == "getLoginUser") {
request.onContinueResult(User(123,"202cb962ac59075b964b07152d234b70"))
return true
}
return super.process(request)
}
}
当跳转发生了错误的时候处理,可用用于提高APP的可用性,也可以用于实现单Module运行调试。
class DebugMockIntercepter : GRouterInterceptor() {
override fun onError(request: TaskRequest, exception: Exception): Boolean {
if (request.path == "getLoginUser") {
request.onContinueResult(User(123,"202cb962ac59075b964b07152d234b70"))
return true
}
return super.onError(request, exception)
}
}
使用
// 手动注册拦截器
GRouter.getInstance().addInterceptor(DebugMockInterceptor())
val response = GTaskCenter.GetUserLoginTask().execute()
Log.e("GetUserLogin", response.string())
// GetUserLogin: {"name":"202cb962ac59075b964b07152d234b70","uid":123}