Stop using a single framework, XUtils - you deserve it!

Details of XUtils

1, What are XUtils?

brief introduction

xUtils contains ORM, HTTP (s), image and view annotations, but it is still lightweight (251K), powerful and easy to expand

  1. orm: an efficient and stable orm tool, which makes it more convenient to support cookie s and caching when implementing the http interface
    Flexible, linq expression like interface. Consistent performance with greenDao
  2. http(s): Based on urlconnection, Android 4.4 is implemented by okHttp
    The request protocol supports 11 predicates: GET,POST,PUT,PATCH,HEAD,MOVE,COPY,DELETE,OPTIONS,TRACE,CONNECT
    Support large file (over 2G) upload
    Support breakpoint download (if the server supports the Range parameter, the client automatically handles breakpoint download)
    Cookie support (domain, path, expiry and other features are implemented)
    Support cache (realize cache control, last modified, Etag and other features, and use expiration time + LRU dual mechanism to clean up when there are too many cache contents)
    Supports asynchronous and synchronous (can be used in combination with RxJava) calls





  3. Image: with the support of http(s) and its download cache, the implementation of image module is quite simple
    It supports memory cache, disk cache (thumbnail and original image), and recycle pictures held by view but removed by MemCache, so as to reduce flicker during page fallback
    Support to automatically stop the download task corresponding to the recycled item when ListView slides (breakpoint renewal when downloading again)
    Support webp, GIF (some older systems only show static graphs)
    Support fillet, circle, square and other cutting, support automatic rotation



  4. View annotation: the view annotation module only supports more than 400 lines of code, but supports various view injection and event binding flexibly
    Event annotations are supported and not affected by obfuscation (refer to sample's obfuscation configuration)
    Supports binding listener s with multiple methods

Configuration before use

Required permissions

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><!-- Optional -->
initialization
// Initialize in onCreate of application
@Override
public void onCreate() {
    super.onCreate();
    x.Ext.init(this);
    x.Ext.setDebug(BuildConfig.DEBUG); // Whether to output debug log, enabling debug will affect performance
    ...
}
AndroidManifest.xml file application Add in node
android:requestLegacyExternalStorage="true"
android:usesCleartextTraffic="true"

Binding is required where annotations are used

x.view().inject(this);//Without view annotation, you can use it first

2, XUtils loading pictures

ImageOption

ImageOption is a class in xutils. If we do some processing for the loaded image when loading the image, such as setting the size and fillets, we can do it through ImageOption.

  private  ImageOptions getImageOptions(){
        ImageOptions imageOptions = new ImageOptions.Builder()
                .setSize(DensityUtil.dip2px(120), DensityUtil.dip2px(120))//Set size
                .setRadius(DensityUtil.dip2px(30))//Set fillet radius
                .setCrop(true)//If the size of ImageView is not defined as wrap_content, no cross
                .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
                .setLoadingDrawableId(R.drawable.ic_launcher_background)//Show in load
                .setFailureDrawableId(R.drawable.ic_launcher_foreground)//Show on failure
                .build();
                //Builder Design Mode
        return imageOptions;
    }

Load network picture

1. Simple loading

imageOptions = getImageOptions();
x.image().bind(imageView, "https://cdn.xiaoz.me/wp-content/uploads/2018/12/shibie_600.jpg");

2. Load with callback

imageOptions = getImageOptions();
                x.image().bind(imageView, "https://img0.utuku.china.com/640x0/news/20200517/734aa0ad-2843-4073-b370-f168fd56bc38.jpg", new Callback.CommonCallback<Drawable>() {
                    @Override
                    public void onSuccess(Drawable result) {
                        showToast("Picture loaded successfully");
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        showToast("Web address error");
                    }

                    @Override
                    public void onCancelled(CancelledException cex) {
                        showToast("Picture load cancel");
                    }

                    @Override
                    public void onFinished() {
                        showToast("End of image loading");
                    }
                });

3. Image loading with cache callback

   x.image().bind(imageView, "https://img0.utuku.china.com/640x0/news/20200517/734aa0ad-2843-4073-b370-f168fd56bc38.jpg", new Callback.CacheCallback<Drawable>() {
                    @Override
                    public boolean onCache(Drawable result) {
                        return true;
                    }

                    @Override
                    public void onSuccess(Drawable result) {
                        showToast("Picture loaded successfully");
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        showToast("Web address error");
                    }

                    @Override
                    public void onCancelled(CancelledException cex) {
                        showToast("Picture load cancel");
                    }

                    @Override
                    public void onFinished() {
                        showToast("End of image loading");
                    }
                });

Load Android resource pictures

1. Load the resource under the assert directory

x.image().bind(imageView, "assets://test.gif", imageOptions);

2. Load resources under res/drawable directory

x.image().bind(imageView, "res://"+R.drawable.test);

Load sd card picture

Load sd card picture

 x.image().bind(imageView, "file:///sdcard/Pictures/pic/photo.png");

3, XUtils request network

RequestParams

RequestParam is also a class in xutils. We can pass in the url in the constructor

  RequestParams params = new RequestParams("http://xxxx:8080/user/login");

If you need to carry parameters, you can add them in the following ways

   params.addBodyParameter("userAccount", "1001");
   params.addBodyParameter("userPwd", "123456");

get request

x.http().get(params, new Callback.CacheCallback<String>() {.....})

post request

Synchronization request (blocking main thread, not recommended)

   x.http().postSync(params, String.class);

Asynchronous request

 RequestParams params = new RequestParams("http://1xxxx:8080/user/login");
                params.addBodyParameter("userAccount", "1001");
                params.addBodyParameter("userPwd", "123456");
                x.http().post(params, new Callback.CommonCallback<String>() {

                    @Override
                    public void onSuccess(String result) {
                        Log.d("xutils", "success");
                        JSONObject json = JSON.parseObject(result);
                        if(json.getString("res").equals("success")){
                            showToast("Login successful");
                        }else{
                            showToast("Login failed");
                        }
                    }
                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        showToast("Wrong web address or network unavailable");
                    }

                    @Override
                    public void onCancelled(CancelledException cex) {
                        showToast("Login cancelled");
                    }

                    @Override
                    public void onFinished() {
                        Log.d("xutils", "finish");
                        showToast("OnFinish Last called back");
                    }
                });

4, Use summary

Finally, there is no mention of database operation. Please refer to this blog
Full use of Android xUtils framework

Personal experience: Xutils is easy to use and integrates several frameworks. At least it combines Okhttp + Glide + ButterKnife+GreenDAO. It's a very good framework and is strongly promoted. The source code of Xutils is also easy to read. It is recommended that you read it.

Finally, 30s recommend a great place for Xiaobai to get resources. Yes, you only need to pay for it!
Group No.: 705884058


Keywords: Android network JSON OkHttp

Added by u01jmg3 on Wed, 20 May 2020 13:51:48 +0300