Skip to content

Instantly share code, notes, and snippets.

@Trogious
Last active April 25, 2020 15:03
Show Gist options
  • Save Trogious/9b3579de76ba7ee6f28d09bbba2485b2 to your computer and use it in GitHub Desktop.
Save Trogious/9b3579de76ba7ee6f28d09bbba2485b2 to your computer and use it in GitHub Desktop.
Get latest release version of a GitHub repo's release (Android Java)

Gets the latest release version (based on tag name) for a given GitHub repo. (requires Guava due to usage of CharStreams).

    private static class VersionTask extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... strings) {
            String result = null;
            URL url;
            HttpURLConnection connection = null;
            try {
                url = new URL("https://api.github.com/repos/user_name/repo_name/releases/latest");
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                result = CharStreams.toString(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8));
            } catch (IOException e) {
                Log.d("VersionTask", Log.getStackTraceString(e));
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result != null) {
                String version = "";
                try {
                    version = new JSONObject(result).optString("tag_name").trim();
                } catch (JSONException e) {
                    Log.e("VersionTask", Log.getStackTraceString(e));
                }
                if (version.startsWith("v")) {
                    //process version
                }
            }
        }
    }

PS: some further discussions here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment