

# Use the Android producer library
<a name="producer-sdk-android"></a>

You can use the Amazon Kinesis Video Streams provided Android producer library to write application code, with minimal configuration, to send media data from an Android device to a Kinesis video stream. 

Perform the following steps to integrate your code with Kinesis Video Streams so that your application can start streaming data to your Kinesis video stream:

1. Create an instance of the `KinesisVideoClient` object. 

1. Create a `MediaSource` object by providing media source information. For example, when creating a camera media source, you provide information such as identifying the camera and specifying the encoding the camera uses.

   When you want to start streaming, you must create a custom media source. 

## Procedure: Use the Android producer SDK
<a name="producer-sdk-android-using"></a>

This procedure demonstrates how to use the Kinesis Video Streams Android producer client in your Android application to send data to your Kinesis video stream. 

The procedure includes the following steps:
+ [Prerequisites](producersdk-android-prerequisites.md)
+ [Download and configure the Android producer library code](producersdk-android-downloadcode.md)
+ [Examine the code](producersdk-android-writecode.md)
+ [Run and verify the code](producersdk-android-reviewcode.md)

# Prerequisites
<a name="producersdk-android-prerequisites"></a>

We recommend [Android Studio](https://developer.android.com/studio/index.html) for examining, editing, and running the application code. We recommend using the latest stable version.

In the sample code, you provide Amazon Cognito credentials.

**Topics**
+ [Set up a user pool](#set-up-user-pool)
+ [Set up an identity pool](#set-up-identity-pool)

## Set up a user pool
<a name="set-up-user-pool"></a>

**To set up a user pool**

1. Sign in to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home) and verify the region is correct.

1. In the navigation on the left choose **User pools**.

1. In the **User pools** section, choose **Create user pool**.

1. Complete the following sections:

   1. **Step 1: Configure sign-in experience** - In the **Cognito user pool sign-in options** section, select the appropriate options.

      Select **Next**.

   1. **Step 2: Configure security requirements** - Select the appropriate options.

      Select **Next**.

   1. **Step 3: Configure sign-up experience** - Select the appropriate options.

      Select **Next**.

   1. **Step 4: Configure message delivery** - Select the appropriate options.

      In the **IAM role selection** field, select an existing role or create a new role.

      Select **Next**.

   1. **Step 5: Integrate your app** - Select the appropriate options.

      In the **Initial app client** field, choose **Confidential client**.

      Select **Next**.

   1. **Step 6: Review and create** - Review your selections from the previous sections, then choose **Create user pool**.

1. On the **User pools** page, select the pool that you just created.

   Copy the **User pool ID** and make note of this for later. In the `awsconfiguration.json` file, this is `CognitoUserPool.Default.PoolId`.

1. Select the **App integration** tab and go to the bottom of the page.

1. In the **App client list** section, choose the **App client name** you just created.

   Copy the **Client ID** and make note of this for later. In the `awsconfiguration.json` file, this is `CognitoUserPool.Default.AppClientId`.

1. Show the **Client secret** and make note of this for later. In the `awsconfiguration.json` file, this is `CognitoUserPool.Default.AppClientSecret`.

## Set up an identity pool
<a name="set-up-identity-pool"></a>

**To set up an identity pool**

1. Sign in to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home) and verify the region is correct.

1. In the navigation on the left choose **Identity pools**.

1. Choose **Create identity pool**.

1. Configure the identity pool.

   1. **Step 1: Configure identity pool trust** - Complete the following sections:
      + **User access** - Select **Authenticated access**
      + **Authenticated identity sources** - Select **Amazon Cognito user pool**

      Select **Next**.

   1. **Step 2: Configure permissions** - In the **Authenticated role** section, complete the following fields:
      + **IAM role** - Select **Create a new IAM role**
      + **IAM role name** - Enter a name and make note of it for a later step.

      Select **Next**.

   1. **Step 3: Connect identity providers** - In the **User pool details** section complete the following fields: 
      + **User pool ID** - Select the user pool you created earlier.
      + **App client ID** - Select the app client ID you created earlier.

      Select **Next**.

   1. **Step 4: Configure properties** - Type a name in the **Identity pool name** field.

      Select **Next**.

   1. **Step 5: Review and create** - Review your selections in each of the sections, then select **Create identity pool**.

1. On the **Identity pools** page, select your new identity pool.

   Copy the **Identity pool ID** and make note of this for later. In the `awsconfiguration.json` file, this is `CredentialsProvider.CognitoIdentity.Default.PoolId`.

1. Update the permissions for the IAM role.

   1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

   1. In the navigation on the left, choose **Roles**.

   1. Find and select the role you created above.
**Note**  
Use the search bar, if needed.

   1. Select the attached permissions policy.

      Select **Edit**.

   1. Select the **JSON** tab and replace the policy with the following:

------
#### [ JSON ]

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
              {
                  "Effect": "Allow",
                  "Action": [
                      "cognito-identity:*",
                      "kinesisvideo:*"
                  ],
                  "Resource": [
                      "*"
                  ]
              }
          ]
      }
      ```

------

      Select **Next**.

   1. Select the box next to **Set this new version as the default** if it isn't already selected.

      Select **Save changes**.

# Download and configure the Android producer library code
<a name="producersdk-android-downloadcode"></a>

In this section of the Android producer library procedure, you download the Android example code and open the project in Android Studio. 

For prerequisites and other details about this example, see [Using the Android producer library](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/producer-sdk-android.html).



1. Create a directory, and then clone the AWS Mobile SDK for Android from the GitHub repository. 

   ```
   git clone https://github.com/awslabs/aws-sdk-android-samples
   ```

1. Open [Android Studio](https://developer.android.com/studio/index.html).

1. In the opening screen, choose **Open an existing Android Studio project**.

1. Navigate to the `aws-sdk-android-samples/AmazonKinesisVideoDemoApp` directory, and choose **OK**.

1. Open the `AmazonKinesisVideoDemoApp/src/main/res/raw/awsconfiguration.json` file.

   In the `CredentialsProvider` node, provide the identity pool ID from the **To set up an identity pool** procedure in the [Prerequisites](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/producer-sdk-android.html#producersdk-android-prerequisites) section, and provide your AWS Region (for example, **us-west-2**).

   In the `CognitoUserPool` node, provide the App client secret, App client ID, and Pool ID from the **To set up a user pool** procedure in the [Prerequisites](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/producer-sdk-android.html#producersdk-android-prerequisites) section, and provide your AWS Region (for example, **us-west-2**).

1. Your `awsconfiguration.json` file will look similar to the following:

   ```
   {
     "Version": "1.0",
     "CredentialsProvider": {
       "CognitoIdentity": {
         "Default": {
           "PoolId": "us-west-2:01234567-89ab-cdef-0123-456789abcdef",
           "Region": "us-west-2"
         }
       }
     },
     "IdentityManager": {
       "Default": {}
     },
     "CognitoUserPool": {
       "Default": {
         "AppClientSecret": "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmno",
         "AppClientId": "0123456789abcdefghijklmnop",
         "PoolId": "us-west-2_qRsTuVwXy",
         "Region": "us-west-2"
       }
     }
   }
   ```

1. Update the `AmazonKinesisVideoDemoApp/src/main/java/com/amazonaws/kinesisvideo/demoapp/KinesisVideoDemoApp.java` with your Region (in the following sample, it’s set to **US\$1WEST\$12**): 

   ```
   public class KinesisVideoDemoApp extends Application {
       public static final String TAG = KinesisVideoDemoApp.class.getSimpleName();
       public static Regions KINESIS_VIDEO_REGION = Regions.US_WEST_2;
   ```

   For information about AWS Region constants, see [Regions](https://aws-amplify.github.io/aws-sdk-android/docs/reference/com/amazonaws/regions/Regions.html).

# Examine the code
<a name="producersdk-android-writecode"></a>

In this section of the [Android producer library procedure](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/producer-sdk-android.html), you examine the example code. 

The Android test application (`AmazonKinesisVideoDemoApp`) shows the following coding pattern:
+ Create an instance of `KinesisVideoClient`.
+ Create an instance of `MediaSource`.
+ Start streaming. Start the `MediaSource`, and it starts sending data to the client.

The following sections provide details.



## Create an instance of KinesisVideoClient
<a name="producersdk-android-review-code-create-client"></a>

You create the `[KinesisVideoClient](https://github.com/aws-amplify/aws-sdk-android/blob/main/aws-android-sdk-kinesisvideo/src/main/java/com/amazonaws/kinesisvideo/client/KinesisVideoClient.java)` object by calling the `[createKinesisVideoClient](https://github.com/aws-amplify/aws-sdk-android/blob/main/aws-android-sdk-kinesisvideo/src/main/java/com/amazonaws/mobileconnectors/kinesisvideo/client/KinesisVideoAndroidClientFactory.java)` operation.

```
mKinesisVideoClient = KinesisVideoAndroidClientFactory.createKinesisVideoClient(
                    getActivity(),
                    KinesisVideoDemoApp.KINESIS_VIDEO_REGION,
                    KinesisVideoDemoApp.getCredentialsProvider());
```

For `KinesisVideoClient` to make network calls, it needs credentials to authenticate. You pass in an instance of `AWSCredentialsProvider`, which reads your Amazon Cognito credentials from the `awsconfiguration.json` file that you modified in the previous section.

## Create an instance of MediaSource
<a name="producersdk-android-review-code-create-mediasource"></a>

To send bytes to your Kinesis video stream, you must produce the data. Amazon Kinesis Video Streams provides the `[MediaSource](https://github.com/aws-amplify/aws-sdk-android/blob/main/aws-android-sdk-kinesisvideo/src/main/java/com/amazonaws/kinesisvideo/internal/client/mediasource/MediaSource.java)` interface, which represents the data source.

For example, the Kinesis Video Streams Android library provides the `[AndroidCameraMediaSource](https://github.com/aws-amplify/aws-sdk-android/blob/main/aws-android-sdk-kinesisvideo/src/main/java/com/amazonaws/mobileconnectors/kinesisvideo/mediasource/android/AndroidCameraMediaSource.java)` implementation of the `MediaSource` interface. This class reads data from one of the device's cameras.

In the following code example (from the `[fragment/StreamConfigurationFragment.java](https://github.com/awslabs/aws-sdk-android-samples/blob/main/AmazonKinesisVideoDemoApp/src/main/java/com/amazonaws/kinesisvideo/demoapp/fragment/StreamConfigurationFragment.java)` file), the configuration for the media source is created:

```
private AndroidCameraMediaSourceConfiguration getCurrentConfiguration() {
return new AndroidCameraMediaSourceConfiguration(
        AndroidCameraMediaSourceConfiguration.builder()
                .withCameraId(mCamerasDropdown.getSelectedItem().getCameraId())
                .withEncodingMimeType(mMimeTypeDropdown.getSelectedItem().getMimeType())
                .withHorizontalResolution(mResolutionDropdown.getSelectedItem().getWidth())
                .withVerticalResolution(mResolutionDropdown.getSelectedItem().getHeight())
                .withCameraFacing(mCamerasDropdown.getSelectedItem().getCameraFacing())
                .withIsEncoderHardwareAccelerated(
                        mCamerasDropdown.getSelectedItem().isEndcoderHardwareAccelerated())
                .withFrameRate(FRAMERATE_20)
                .withRetentionPeriodInHours(RETENTION_PERIOD_48_HOURS)
                .withEncodingBitRate(BITRATE_384_KBPS)
                .withCameraOrientation(-mCamerasDropdown.getSelectedItem().getCameraOrientation())
                .withNalAdaptationFlags(StreamInfo.NalAdaptationFlags.NAL_ADAPTATION_ANNEXB_CPD_AND_FRAME_NALS)
                .withIsAbsoluteTimecode(false));
}
```

In the following code example (from the `[fragment/StreamingFragment.java](https://github.com/awslabs/aws-sdk-android-samples/blob/main/AmazonKinesisVideoDemoApp/src/main/java/com/amazonaws/kinesisvideo/demoapp/fragment/StreamingFragment.java)` file), the media source is created:

```
mCameraMediaSource = (AndroidCameraMediaSource) mKinesisVideoClient
    .createMediaSource(mStreamName, mConfiguration);
```

## Start the media source
<a name="producersdk-android-review-code-start-mediasource"></a>

Start the media source so that it can begin generating data and sending it to the client. The following code example is from the `[fragment/StreamingFragment.java](https://github.com/awslabs/aws-sdk-android-samples/blob/main/AmazonKinesisVideoDemoApp/src/main/java/com/amazonaws/kinesisvideo/demoapp/fragment/StreamingFragment.java)` file:

```
mCameraMediaSource.start();
```



# Run and verify the code
<a name="producersdk-android-reviewcode"></a>

To run the Android example application for the [Android producer library](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/producer-sdk-android.html), do the following.

1. Connect to an Android device.

1. Choose **Run**, **Run...**, and choose **Edit configurations...**.

1. Choose the plus icon (**\$1**), **Android App**. In the **Name** field, enter **AmazonKinesisVideoDemoApp**. In the **Module** pulldown, choose **AmazonKinesisVideoDemoApp**. Choose **OK**.

1. Choose **Run**, **Run**.

1. In the **Select Deployment Target** screen, choose your connected device, and choose **OK**.

1. In the **AWSKinesisVideoDemoApp** application on the device, choose **Create new account**.

1. Enter values for **USERNAME**, **Password**, **Given name**, **Email address**, and **Phone number**, and then choose **Sign up**.
**Note**  
These values have the following constraints:  
**Password:** Must contain uppercase and lowercase letters, numbers, and special characters. You can change these constraints in your User pool page on the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). 
**Email address:** Must be a valid address so that you can receive a confirmation code.
**Phone number:** Must be in the following format: **\$1*<Country code>**<Number>***, for example, **\$112065551212**.

1. Enter the code that you receive by email, and choose **Confirm**. Choose **Ok**.

1. On the next page, keep the default values, and choose **Stream**.

1. Sign in to the AWS Management Console and open the [Kinesis Video Streams console](https://console.aws.amazon.com//kinesisvideo/home/) in the US West (Oregon) Region. 

   On the **Manage Streams** page, choose **demo-stream**. 

1. The streaming video plays in the embedded player. You might need to wait a short time (up to ten seconds under typical bandwidth and processor conditions) while the frames accumulate before the video appears.
**Note**  
If the device's screen rotates (for example, from portrait to landscape), the application stops streaming video.

The code example creates a stream. As the `MediaSource` in the code starts, it begins sending frames from the camera to the `KinesisVideoClient`. The client then sends the data to a Kinesis video stream named **demo-stream**. 