本文主要是介绍异步任务-AsyncTack进阶-结合动态接口,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
使用动态接口实现异步任务下载
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 {@Overridepublic 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;@Overrideprotected 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);}@Overridepublic void onSuccess(ShowEntry t) {text.setText(t.getMessage());}@Overridepublic void onFailed(Exception e) {}
}
这篇关于异步任务-AsyncTack进阶-结合动态接口的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!