您的位置:首页 > 其它

异步任务-AsyncTack进阶-结合动态接口

2016-09-01 01:16 330 查看

使用动态接口实现异步任务下载

1, 这里我们使用到了上一篇博客中的NetWorkTask工具类, 这里不再赘述, 链接如下

github

CSDN

2, 需要我们写一个注解, 用于标示接口需要传入的数据

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UrlString {
String value();
}


3, 写一个工具类Tools, 生成接口的实例

/**
* Created by Lulu on 2016/8/31.
*/
public class Tools {
public static <T> T getInsances(Class<T> type) {
Object o = Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, new MyHandler());
return (T) o;
}
private static class MyHandler implements InvocationHandler {

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
method.setAccessible(true);
//得到方法的注解
UrlString annotation = method.getAnnotation(UrlString.class);
if (annotation != null) {
String url = String.format(Locale.CHINA, annotation.value(), args);
Class<?> returnType = method.getReturnType();
if (returnType.equals(NetWorkTask.class)) {
//得到泛型
ParameterizedType type = (ParameterizedType) method.getGenericReturnType();
//得到实体类的类型
Type entryType = type.getActualTypeArguments()[0];

return new NetWorkTask<>(url, (Class<Object>) entryType);
}
}
return null;
}
}

}


4, 测试使用:

1) 新建一个获取数据的接口

public interface TopServer {
@UrlString("http://www.tngou.net/api/top/show?id=%d")
NetWorkTask<ShowEntry> getShow(int id);
}


2)创建Activity测试

public class Main4Activity extends AppCompatActivity implements NetWorkTask.Callback<ShowEntry>{
private TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
TopServer server = Tools.getInsances(TopServer.class);
server.getShow(13122).execute(this);
text = (TextView) findViewById(R.id.main4_text);
}
@Override
public void onSuccess(ShowEntry t) {
text.setText(t.getMessage());
}

@Override
public void onFailed(Exception e) {
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  博客