Skip to main content

Twitch API v3 for Android


Official website for Twitch API v3 https://dev.twitch.tv/docs

Twitch gives API to access some data with and without authentication :

Blocks Channels Channel Feed Chat Follows Games Ingests Search Streams Teams Users Videos


In this post we will work on how to get the channels basic data like status,name,language,banner,profile banner,videos,streams and other things.

There is a library for calling API callbacks called Java Twitch API Wrapper
https://github.com/urgrue/Java-Twitch-Api-Wrapper  this library is for Java projects not for Android.

So what we will do is first we will create a Android application called TwitchApp:



Next create a package named its as "twitchapis" and copy all the package from the "Java Twitch API Wrapper" project and paste it in "twitchapis" package.

Add these library in your build.gradle:

compile 'com.github.bumptech.glide:glide:3.6.1'
compile 'com.loopj.android:android-async-http:1.4.9'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.4'
compile 'com.fasterxml.jackson.core:jackson-databind:2.7.4'
 

1. Channel API: 

 

First we will get the Channel details by using "Channels API" 
--GET https://api.twitch.tv/kraken/channels/test_channel.
test_channel is the name of the channel or username. 
 
public void getChannelStatus() {
  List<Channel> channelList = new ArrayList<Channel>();
  TextView twitch_status = (TextView) findViewById(R.id.twitch_status);
 
    Twitch twitch = new Twitch();
    twitch.channels().get("test_channel", new ChannelResponseHandler() {
        @Override
        public void onSuccess(Channel channel) {
        /* Successful response from the Twitch API */
            channelList.add(channel);
            if (channelList.size() > 0) {
                twitch_status.setText(channel.getStatus());
                Glide.with(mContext)
                        .load(channel.getVideoBanner())
                        .placeholder(PlaceHolderDrawableHelper.getBackgroundDrawable(0))
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .crossFade()
                        .into(imageViewVideoBannerThumb);
            }
        }

        @Override
        public void onFailure(int statusCode, String statusMessage, String errorMessage) {
        /* Twitch API responded with an error message */
            Toast.makeText(getApplicationContext(), "" + errorMessage, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onFailure(Throwable e) {
        /* Unable to access Twitch, or error parsing the response */
            Toast.makeText(getApplicationContext(), "Unable to access Twitch", Toast.LENGTH_LONG).show();
        }
    });
}
 
 

2. Videos API:  

 

Get all the videos posted by the user.
--Get https://api.twitch.tv/kraken/channels/test_channel/videos?limit=10&offset=0

maximum limit is 100 by setting offset you can get all the videos more than 200.
For example in first hit:
 https://api.twitch.tv/kraken/channels/test_channel/videos?limit=100&offset=0
In second hit:
https://api.twitch.tv/kraken/channels/test_channel/videos?limit=100&offset=100
so total 200 videos.

public void getChannelVideos(final String offset) {
    Twitch twitch = new Twitch();
    RequestParams params = new RequestParams();
    params.put("limit", "100");
    params.put("offset", offset);
    twitch.channels().getVideos("test_channel", params, new VideosResponseHandler() {

        @Override
        public void onSuccess(int total, List<Video> videos, Links links) {
        /* Successful response from the Twitch API */
            int totalChannelVideos = total;

            List<Video> videoList= new ArrayList<Video>();
            videoList.addAll(videos);
 
        }

        @Override
        public void onFailure(int statusCode, String statusMessage, String errorMessage) {
        /* Twitch API responded with an error message */
            Toast.makeText(getApplicationContext(), "" + errorMessage, 
                          Toast.LENGTH_LONG).show();
        }

        @Override
        public void onFailure(Throwable e) {
        /* Unable to access Twitch, or error parsing the response */
            Toast.makeText(getApplicationContext(), "Unable to access Twitch", 
                             Toast.LENGTH_LONG).show();
        }
    });
}
 
 

 3. Streams API:


Get the live stream status.
--GET https://api.twitch.tv/kraken/streams/test_channel

Returns a stream object if live.

Example Response:

If offline

{
  "stream": null,
  "_links": {
    "self": "https://api.twitch.tv/kraken/streams/test_channel",
    "channel": "https://api.twitch.tv/kraken/channels/test_channel"
  }
}
 

If online

{
  "_links": {
    "channel": "https://api.twitch.tv/kraken/channels/test_channel",
    "self": "https://api.twitch.tv/kraken/streams/test_channel"
  },
  "stream": {
    "game": "StarCraft II: Heart of the Swarm",
    "viewers": 2123,
    "average_fps": 29.9880749574,
    "delay": 0,
    "video_height": 720,
    "is_playlist": false,
    "created_at": "2015-02-12T04:42:31Z",
    "_id": 4989654544,
    "channel": {
      "mature": false,
      "status": "test status",
      "broadcaster_language": "en",
      "display_name": "test_channel",
      "game": "StarCraft II: Heart of the Swarm",
      "delay": null,
      "language": "en",
      ...
      "partner": true,
      "url": "http://www.twitch.tv/test_channel",
      "views": 49144894,
      "followers": 215780,
      "_links": {
        "self": "https://api.twitch.tv/kraken/channels/test_channel",
        "follows": "https://api.twitch.tv/kraken/channels/test_channel/follows",
        ...
        "teams": "https://api.twitch.tv/kraken/channels/test_channel/teams",
        "videos": "https://api.twitch.tv/kraken/channels/test_channel/videos"
      }
    },
    "preview": {
      "small": "http://static-cdn.jtvnw.net/previews-ttv/
                    live_user_test_channel-80x45.jpg",...
    },
    "_links": {
      "self": "https://api.twitch.tv/kraken/streams/test_channel"
    }
  }
}
 
 public void getStream() {

    Twitch twitch = new Twitch();
    twitch.streams().get("test_channel", new StreamResponseHandler() {
        @Override
        public void onSuccess(Stream stream) {
        /* Successful response from the Twitch API */
            if (stream != null) {
                if (stream.isOnline()) {
                    Glide.with(mContext)
                            .load(stream.getPreview().getLarge())
                            .placeholder(PlaceHolderDrawableHelper.
                                                  getBackgroundDrawable(0))
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .crossFade()
                            .into(imageViewVideoThumb);
                    title.setText(stream.getGame());
                    genre.setText(stream.getChannel().getStatus());
                    year.setText(stream.getCreatedAt().toString());
                    year.setTag("" + stream.getId());
                
                }
            }
        }

        @Override
        public void onFailure(int statusCode, String statusMessage, 
                                                       String errorMessage) {
        /* Twitch API responded with an error message */
            Toast.makeText(getApplicationContext(), "" + errorMessage, 
                    Toast.LENGTH_LONG).show();
        }

        @Override
        public void onFailure(Throwable e) {
        /* Unable to access Twitch, or error parsing the response */
            Toast.makeText(getApplicationContext(), "Unable to access Twitch", 
                             Toast.LENGTH_LONG).show();
        }
    });
}
 
 
We have to do same with other API's, if there is authentication you have to
pass the credential with API.
 

Comments

  1. I use getStream but my app crashed
    Logcat shows Twitch twitch = new Twitch(); line

    ReplyDelete

Post a Comment

Popular posts from this blog

Vertical AutoScrolling TextView in Android

In android by default we can scroll the text in horizontal using marquee in layout, but if we want to scroll the text in vertical its not possible by default. So here we will learn to create a custom TextView which will auto-scroll in vertical direction. Source Code:  VerticalScrollingTextView-Android Create a AutoScrollingTextView.class which extends TextView: @SuppressLint ( "AppCompatCustomView" ) public class AutoScrollingTextView extends TextView { private static final float DEFAULT_SPEED = 65.0f ; public Scroller scroller ; public float speed = DEFAULT_SPEED ; public boolean continuousScrolling = true; public AutoScrollingTextView (Context context) { super (context) ; init( null, 0 ) ; scrollerInstance(context) ; } public AutoScrollingTextView (Context context , AttributeSet attrs) { super (context , attrs) ; init(attrs , 0 ) ; scr...

Flexbox inside the RecyclerView as a LayoutManager (FlexboxLayoutManager).

Currently google has release the Flexbox which can be used for building flexible layouts using FlexboxLayout, it can be interpreted as an advanced LinearLayout because both layouts align their child views sequentially. For more detail on this flexbox-layout But here we are gonna work on Flexbox with RecyclerView. Flexbox with a large number of items in a scrollable container! Let's first see what are the Supported attributes / features comparison Due to some characteristics of the RecyclerView, some Flexbox attributes are not available/not implemented to the FlexboxLayoutManager. Here is a quick overview of the attributes/features comparison between the two containers. Attribute / Feature FlexboxLayout                FlexboxLayoutManager (RecyclerView) flexDirection flexWrap (except wrap_reverse ) justifyContent alignItems alignContent - layout_order - layout_fle...

Android RecyclerView and StaggeredGridLayoutManager with Picasso/Glide

This project is there in GitHub https://github.com/yuvaraj119/Picasso-RecyclerView-StaggeredGridLayoutManager You can download and start customizing it for your project also. How to use with Picasso Picasso + RecyclerView + StaggeredGridLayoutManager Its the enhanced version of this project https://github.com/pohh/slotmachinepicasso were there was a problem with Picasso + RecyclerView + StaggeredGridLayoutManager shuffles resizable recycler views infinitely issue posted on github https://github.com/square/picasso/issues/918 I have made some changes now it works with Picasso and Glide without any shuffles and position change Currently this project is done with Picasso If you want to use it with Glide How to use with Glide Glide + RecyclerView + StaggeredGridLayoutManager Add dependencies for Glide https://github.com/bumptech/glide Remove Picasso library from dependency and remove all the codes of Picasso from MyGridAdapter.java and also from other p...