Set up Android SDK

This document will introduce how to configure the Android SDK for QWeather API.

OS requirement:

Android 8.0+, minSDK 26

Step 1: Create project and credential

Make sure you have created a Project and Credential, see Project and KEY and JWT authentication.

Step 2: Install SDK

Download the latest SDK: QWeather Android SDK 5.0.1 (MD5:ab2c14983ab8a59c9ab4eed014faa952)

Copy the JAR file to the app/libs/

YOUR-PROJECT/
├── app/
│   ├── libs/
│   │   └── QWeather_Public_Android_V5.0.1.jar
│   ├── src/
│   └── build.gradle

Update the Gradle configuration app/build.gradle

dependencies {
    // add QWeather jar
    implementation files('libs/QWeather_Public_Android_V5.0.1.jar')
    
    // or add all jar
    implementation fileTree(dir: 'libs', include: ['*.jar'])
}

Reference library

implementation libs.gson
implementation libs.okhttp

Add the following code to the obfuscation file proguard-rules.pro

-keep public class com.qweather.sdk.QWeather {
    public *;
}

-keep public class com.qweather.sdk.basic.**{ *; }
-keepclassmembers class com.qweather.sdk.basic** { *; }

-keep public class com.qweather.sdk.parameter.**{ *; }
-keepclassmembers class com.qweather.sdk.parameter** { *; }

-keep public class com.qweather.sdk.response.**{ *; }
-keepclassmembers class com.qweather.sdk.response** { *; }

-keep interface com.qweather.sdk.Callback{  *; }
-keep interface com.qweather.sdk.TokenGenerator{  *; }

Step 3: Add API Host and token

Hint: iOS SDK only support JWT for authentication.

QWeather.getInstance(MainActivity.this, "{YOUR_HOST}") // Initialize api host
        .setTokenGenerator(new TokenGenerator() {
                        @Override
                        public String generator() {
                             // Update jwt token should be implemented here in production environments
                            return "{YOUR_TOKEN}"; 
                        }
                    });

Sample code

Get real-time weather for Beijing.

WeatherParameter parameter = new WeatherParameter("101010100")
                .lang(Lang.ZH_HANS)
                .unit(Unit.METRIC);

QWeather.instance.weatherNow(parameter, new Callback<WeatherNowResponse>() {
    @Override
    public void onSuccess(WeatherNowResponse response) {
        Log.i(TAG, response.toString());
    }

    @Override
    public void onFailure(ErrorResponse errorResponse) {
        Log.i(TAG,errorResponse.toString());
    }

    @Override
    public void onException(Throwable e) {
        e.printStackTrace();
    }
});