Android10--Android之动态接口实现加载网页和图片

来源:互联网 发布:d3.js 折线图 编辑:程序博客网 时间:2024/06/06 00:18

承接上文:

今天我们使用动态接口去实现,更好的实现了封装性,通过接口,我们可以拿到NetWorkAsyncTask的一个类.

1.首先我们要有 一个注解,这个注解可以拿到我们的url..

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

2.然后我们要有一个接口,通过这个接口我们我可拿到我们想要的东西.
之后我们如果需要拿到不同的实体类,我们只需要重写一个接口传入不同的url即可.

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

然后实现我们的动态接口

public class Tools {    public static<T> T getInstance(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 {            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) entryType);                }            }            return null;        }    }}

测试类:

public class MainActivity extends AppCompatActivity implements NetworkTask.Callback<ShowEntry> {    private WebView web;    private ImageView image;    private static final String CSS = "<style>img{max-width:100%}</style>";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        web = (WebView) findViewById(R.id.main2_web);        image = (ImageView) findViewById(R.id.main2_image);        TopServer server = Tools.getInstance(TopServer.class);        NetworkTask<ShowEntry> show = server.getShow(3);        show.execute(this);    }    @Override    public void onSuccess(ShowEntry entry) {        setTitle(entry.getTitle());        new ImageLoader(image).execute("http://tnfs.tngou.net/img" + entry.getImg());        web.loadDataWithBaseURL("http://www.tngou.net", CSS + entry.getMessage(), "text/html; charset=utf-8", "UTF-8", null);    }    @Override    public void onFail(Exception e) {        e.printStackTrace();        Toast.makeText(MainActivity.this, "网络错误", Toast.LENGTH_SHORT).show();    }}

之后的使用.我们可以将加载图片,网页内容,和动态接口,注解,这几个类放到一起,之后当做一个Moudle直接道途使用即可..

结果实现:
和上篇的效果一样…

1 0