# Android

#### Pre-Requisites

Conscent.ai Android SDK supports **API 21 (Android 5.0)** and above. Please ensure the minSdkVersion is in the app's **build.gradle** file reflects the same.

{% hint style="info" %}
&#x20;*In case of an error for Kotlin not enabled - Enable Kotlin for Project.*

*In case of an error in Manifest merging - Merge Manifest as per Android Studio support or include the below line inside your application tag in the Android Manifest file.*

<pre class="language-xml" data-full-width="false"><code class="lang-xml"><strong>tools:replace="android:icon,android:roundIcon" 
</strong></code></pre>

{% endhint %}

#### Permissions

Add the following permissions to the `AndroidManifest.xml` file.

```xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
```

<details>

<summary>Installation</summary>

You can download and add AAR File from [here](https://github.com/tsbmediaventure/ConsCent-docs/tree/master/docs/plugins/android), which needs to be included in your **Module libs directory,** and tell gradle to install it like this:

```
Both files are required to be added.
```

```gradle
dependencies {
    implementation fileTree(include: [ '*.aar'], dir: 'libs')
}
```

</details>

<details>

<summary>Dependencies</summary>

In root level (project level) build.gradle, add classpath, and maven:

```gradle
dependencies {
    classpath 'com.google.gms:google-services:[latest-version]'
    // Add the Crashlytics Gradle plugin
    classpath 'com.google.firebase:firebase-crashlytics-gradle:[latest-version]'
}
```

In your application build.gradle file, include dependency as below with the latest versions:

```kotlin
dependencies{
// Retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.9'
// Coroutines    
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4'
// Browser   
     implementation 'androidx.browser:browser:1.5.0'
     implementation 'com.google.android.gms:play-services-base:[latest-version]'
     implementation (platform("com.google.firebase:firebase-bom:[latest-version]"))
     implementation ("com.google.firebase:firebase-analytics-ktx")
     implementation ("com.google.firebase:firebase-crashlytics-ktx")
     implementation 'com.squareup.picasso:picasso:[latest-version]'
     implementation "androidx.swiperefreshlayout:swiperefreshlayout:[latest-version]"
}
```

</details>

<details>

<summary>Initialize SDK</summary>

In your application or root activity class's method onCreate, pass these fields to be used in your app.

* applicationContext - Pass your application context.
* yourClientId - Pass your clientId received from Conscent.ai.
* yourAccentColor - Pass your accentColor for the app.
* Mode - configuration testing of different environments available. &#x20;
* APP\_MODE - used for checking the debug and production environment of the app.  &#x20;

```kotlin
Api Mode can be set as :
    ConscentConfiguration.MODE.SANDBOX
    ConscentConfiguration.MODE.PRODUCTION
```

&#x20;                                               &#x20;

```kotlin
APP_MODE can be set as : 
    ConsCentConfiguration.APP_MODE.DEBUG 
    ConsCentConfiguration.APP_MODE.PROD
```

*If APP\_MODE is DEBUG, all errors will be shown as Toast messages and Logs.*&#x20;

*If APP\_MODE is PROD, only logs will be available for critical errors like Network unavailability, wrong client\_id, and wrong content\_id.*

</details>

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
class TestingApplication : Application() {
    override fun onCreate() {
        super.onCreate()

        ConscentWrapper.configure(
            application = this,
            clientId = "5f92a62013332e0f667794dc",
            colorAccent = Color.parseColor("#000000"),
            appMode = ConscentConfiguration.APP_MODE.DEBUG,
            apiMode = ConscentConfiguration.MODE.SANDBOX,
        )
    }
}

```

{% hint style="info" %}
Pass the client ID received from Conscent.ai dashboard
{% endhint %}
{% endtab %}

{% tab title="Java" %}

```java
public class TestingApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        ConscentWrapper.Companion.configure(
                this,
                "5f92a62013332e0f667794dc",
                Color.parseColor("#000000"),
                ConscentConfiguration.APP_MODE.DEBUG,
                ConscentConfiguration.MODE.SANDBOX
        );
        
    }
}
```

{% hint style="info" %}
Pass the client Id received from Conscent.ai dashboard
{% endhint %}
{% endtab %}
{% endtabs %}

**Initialize the paywall**

In order to ensure that the Conscent.ai Paywall appears on the targeted pages and the deep insights and analytics are collected optimally you need to implement the following method on all the content/article pages.

To have more control over the content flow, create an instance of the Conscent class inside your activity onCreate method for each unique contentId(recommended).

Use the below-described method:

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
val instance = ConscentWrapper.getConscentInstance(
            callingActivity = yourCallingActivity,
            parentView = yourParentView,
            containerView = yourContainerView,
            popUpContainer = yourPopUpContainerView,
            onConscentListener = onConscentListener,
            contentId = contentId,
            title = contentTitle,
            categories= arrayListOf("categorie1","categorie2","categorie3"),
            sections = arrayListOf("section","section1","section3"),
            tags = arrayListOf("premium"),
            url = ContentUrl,
            authorName = authorName,
        )
//To display the registration paywall 
  RegistrationPaywall.initRegistrationPaywall()
 //To display the paywall       
RegularPaywall.initRegularPaywall()
//To display the metered banner
MeterBanner.initMeterBanner()
```

{% endtab %}

{% tab title="Java" %}

```java
Conscent instance = ConscentWrapper.Companion.getConscentInstance(
        yourCallingActivity,
        yourParentView,
        yourContainerView,
        yourPopUpContainerView,
        contentId,
        contentTitle,
        onConscentListener,
        Arrays.asList("categorie1", "categorie2", "categorie3"),
        Arrays.asList("section1", "sectio2", "section3"),
        Arrays.asList("premium"),
        contentUrl,
        authorName
);
 //To display the registration wall 
RegistrationPaywall.initRegistrationPaywall()
 //To display the paywall       
RegularPaywall.initRegularPaywall()
//To display the metered banner
MeterBanner.initMeterBanner()
```

{% endtab %}
{% endtabs %}

> #### Note: Include the AAR files of respective paywalls and banners before calling above functions.

#### To set the scroll depth on the content page:

```kotlin
instance.scrollDepth = scrollY
```

Call the below sample method on override **onActivityResult** in Activity Class.

```kotlin
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        Log.i(TAG, "RedirectionHandler.onActivityResult: ")
        if (resultCode == RESULT_OK) {
            if (data?.getStringExtra("TYPE") == "PLANS") {
                instance.checkSubscriptions(
                    TestingPreferences.getContentTitle(),
                    TestingPreferences.getSubscriptionUrl(),
                )
            } else
                instance.handledIntent()
        }
    }
```

In case of Fragment, call the below method inside onDestoyView()-

```
instance.onDestroy()
```

<table><thead><tr><th width="294.5">Parameters</th><th>Description</th></tr></thead><tbody><tr><td>yourCallingActivity(Activity)</td><td>This is your activity content which is calling the methods and where callback will be received.</td></tr><tr><td>yourParentView(ConstraintLayout)</td><td>This will be the parent of your layout. Please keep ConstraintLayout as your root view in your activity xml file. Pass the reference of your root view in checkContent function.  </td></tr><tr><td>yourContainerView(FrameLayout)</td><td><p>This will be a FrameLayout where the payment page will be inflated. Create a frameLayout in your XML and pass it here as a reference.</p><p>For eg:</p><pre class="language-xml"><code class="lang-xml">&#x3C;FrameLayout
        android:id="@+id/frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</code></pre></td></tr><tr><td>contentId (String)</td><td>This will be your article or content id for which detail needs to be checked.</td></tr><tr><td>yourContentTitle (<code>String</code> - Optional)</td><td>Title of the content for display purposes.</td></tr><tr><td>yourSubsUrl (<code>String</code> - Optional)</td><td>Url is to be used when subscribe button is clicked.</td></tr><tr><td>canSubscribe (<code>Boolean</code> - Optional)</td><td>Pass this as "true" to show subscribe layout else as "false".</td></tr><tr><td>showClose (<code>Boolean</code> - Optional)</td><td>Pass this as "true" to show the close button on the paywall/subscriptions, the default value is <code>"false"</code></td></tr><tr><td>OnConscentListener</td><td>You can pass a listener which will get called after success or failure in processing. If you pass a listener, after successful processing, the success reference will be called and for a failed event, the failure event will be called</td></tr></tbody></table>

You can implement OnConscentListener in your activity and then pass it as a reference.

| Methods                | Description                                                                                                                                                                                                                                                        |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| onSuccess              | This is the success callback that will get called for every successful processing. You can pass your method as a reference or a lambda expression which will get called in case of success.                                                                        |
| onError (optional)     | You can pass it as null. This is the failure callback which will get called for every failed processing. You can pass your method as a reference or a lambda expression and it'll get called for failed cases. You can implement your code in it for failed cases. |
| onSubscribe (optional) | If you want to inflate subscribe layout, pass a subscribe function which will be called when subscribe button will be clicked inside the payment flow. Passing null will not inflate subscribe layout.                                                             |
| onBuyPass (optional)   | It will be called when the buy-pass button will be clicked inside the payment flow.                                                                                                                                                                                |
| onSignIn               | This is the callback function that will be called when a user clicks on signIn button in the payment flow. This will be only visible if subscribe layout has been inflated.                                                                                        |
| onAdFree               | This is the callback function which will be called when a user clicks on adfree subscription.                                                                                                                                                                      |
| eventParams            | This callback function will be called when a user clicks on the Google login. This will send params paywallId,contentId, paywallType, clientId, and anonId.                                                                                                        |
| onShowPaywall          | This callback function will be called when a paywall is visible on the screen. This will send params - eventLocation, eventType, paywallDisplayType, paywallType.                                                                                                  |
| onGoogleLoginClick     | This will be used to trigger your Google sign. This callback function will be called when a user clicks on the Google login.                                                                                                                                       |
| onCustomLinkSlot       | This will be triggered when the Link Slot To on the Conscent Dashboard is linked to Custom URL                                                                                                                                                                     |

#### To check if an article/content is free/paid or payment needs to be done, in your class, use as below sample: Parameters detail can be checked below for more information.

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
instance.checkContentAccess(
        yourContentTitle,
        yourSubsUrl,
        canSubscribe,
        showClose
    )
```

{% endtab %}

{% tab title="Java" %}

```java
instance.checkContentAccess(
        yourContentTitle,
        yourSubsUrl,
        canSubscribe,
        showClose
    );
```

{% endtab %}
{% endtabs %}

> Call <mark style="color:orange;">**checkContentAccess**</mark> method on override <mark style="color:orange;">**onNewIntent**</mark> method in Activity Class.

**Call the below function and pass the userId, after the user has logged in:**

```kotlin
PluginPreferences.setClientUserId("Your_User_Id")
```

#### To use only the Subscription Landing Page, call the below method:

> Create a singleton instance as done during initialization of the paywall.

```kotlin
instance.onSoftSubscribeClick(<subsUrl>)
```

<details>

<summary>Login Functionality</summary>

Call this method to invoke our Login System

```kotlin
ConscentWrapper.INSTANCE?.onlyLoginFlow(yourCallingActivity)
```

</details>

#### Logout the User:

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
ConscentWrapper.INSTANCE?.logoutUser()
```

{% endtab %}

{% tab title="Java" %}

```java
ConscentWrapper.Companion.INSTANCE?.logoutUser();
```

{% endtab %}
{% endtabs %}

**Demo App:** [**Link**](https://github.com/RoshanSharma8245/Demo-Blog)
