This hands-on tutorial shows you how to build a functioning Android application in 30 minutes that lets users chat with a support agent. It uses the Zendesk Chat SDK for Android, a shared code library that lets you easily incorporateZendesk Chatin Android applications.

Zendesk gives you other options for providing customer support in mobile apps:

  • You can use the Support SDK to incorporate other Zendesk customer support features in Android applications. To learn how, seeQuick start - Support SDK for Android.

  • You can use the Unified SDK to incorporate Answer Bot with Chat and Support to create aunified messaging experience. However, because Answer Bot is available only as an add-on with the Zendesk Suite Professional plan or above, the Unified SDK is not used in this tutorial.

You need Android Studio to build the small Android application in this tutorial. You can download Android Studio from theAndroid developer website.

You'll also need a Zendesk Chat account. A free trial account is available. See theZendesk Chat website.

Though this quick start guide provides step-by-step instructions to build a simple application, it's not an Android app tutorial, If you're new to Android development, I highly recommend working through the lessons inBuild Your First Appon the Android website.

The guide walks you through the following basic steps for adding chat functionality to an Android application:

  1. Creating a sample project
  2. Adding the Chat SDK to the project
  3. Initializing the framework
  4. Creating a button to start a chat
  5. Adding an event listener for the Chat button
  6. Testing that chat works
  7. Next steps

The tutorial uses version 3.3.6 of the Chat SDK. It was tested using Android Studio 2021.2.1 (Chipmunk).

Disclaimer:Zendesk provides this article for instructional purposes only. Zendesk can't provide support for third-party technologies such as Java, Android, and Android Studio. Please post any issue in the亚博Zendesk sdk社区, or search for a solution online.

Creating a sample project

This section shows you how to create a quick sample project in Android Studio. You'll use the project to try out the Chat SDK.

  1. In Android Studio, selectFile>New>New Project.

    If you're at the welcome window, chooseStart a new Android Studio project.

  2. In theSelect a Project Templatescreen, make sure thePhone and Tablettab is selected, clickEmpty Activity, and clickNext.

  3. Set the following options for the project:

    • Name- EnterMy Sample Chat Appor something similar
    • Package name- (required) Enter something likecom.sample.mysamplechatapp
    • Save location- (required) Choose where you want to save the project
    • Language- Java
    • Minimum SDK- API 21: Android 5.0 (Lollipop)
  4. ClickFinish.

Android Studio creates all the files and basic settings for your project. You can view the files in the Project navigator on the left side of the screen. If you don't see the files, click the first icon (the folder icon) on the upper side of the panel.

Adding the Chat SDK to the project

Note:messagingheredoes not referto the Messaging channel, but to the library used to send messages.

  1. 在左栏在您的项目文件,locateGradle Scripts>build.gradle (Module: My_Sample_App.app), then double-click the file to open it in the editor.

    Note: Make sure not to open the first gradle file,build.gradle (Project: My_Sample_App).

  2. Before thedependenciessection, add the followingrepositoriessection:

                   
    repositories{maven{url'https://zendesk.jfrog.io/zendesk/repo'}}
  3. In thedependenciessection, insert the following line (highlighted):

                   
    dependencies{implementation group:'com.zendesk',name:'chat',version:'3.3.6'implementation group:'com.zendesk',name:'messaging',version:'5.2.5'...}

    Thegradle.buildfile should look partially as follows:

                   
    repositories{maven{url'https://zendesk.jfrog.io/zendesk/repo'}}dependencies{implementation group:'com.zendesk',name:'chat',version:'3.3.6'implementation group:'com.zendesk',name:'messaging',version:'5.2.5'implementation'androidx.appcompat:appcompat:1.4.1'implementation'com.google.android.material:material:1.5.0'implementation'androidx.constraintlayout:constraintlayout:2.1.3'testImplementation'junit:junit:4.13.2'androidTestImplementation'androidx.test.ext:junit:1.1.3'androidTestImplementation'androidx.test.espresso:espresso-core:3.4.0'}
  4. Save the file, then integrate the Chat SDK in the project by selectingFile>Sync Project with Gradle Files.

If you see the following error, you'll need to update yoursettings.gradlefile as follows.

             
Buildwas configured to prefer settings repositories over projectrepositories but repository'maven'was added by buildfile'app/build.gradle'.
  1. 在左栏在您的项目文件,locateGradle Scripts>settings.gradle, then double-click the file to open it in the editor.

  2. ReplacerepositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)withrepositoriesMode.set(RepositoriesMode.PREFER_SETTINGS).

  3. In therepositoriessection, insert the following line (highlighted):

                   
    repositories{maven{url'https://zendesk.jfrog.io/zendesk/repo'}...}

    Thesettings.gradlefile should look partially as follows:

                   
    dependencyResolutionManagement{repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)repositories{maven{url'https://zendesk.jfrog.io/zendesk/repo'}google()mavenCentral()}}
  4. Save the file, then integrate the Support SDK in the project by selectingFile>Sync Project with Gradle Files.

    You can ignore the deprecated Gradle warning.

Running a test build

Before going any further, make sure you successfully added the Chat SDK to your project. One way is to run a test build in a phone emulator. The application doesn't do much yet, but if you don't get any build errors you know you're on the right path.

You can use the emulator that’s included in Android Studio. First, you'll need to create an Android Virtual Device (AVD) definition for the emulator. Your AVD definition will specify the characteristics of an Android phone. In this case, you'll define a Pixel phone.

  1. Click theDevice Managericon on the toolbar (or selectTools>Device Manager).

  2. In the Virtual Devices screen, clickCreate Virtual Device.

  3. In the Select Hardware screen, select the latest, regular-sized Pixel phone, and then clickNext.

  4. In the System Image screen, click theDownloadlink next to the latest recommended system image (Android API 32 with x86-64 ABI at the time of this writing).

    The components can take a few moments to download.

  5. After the download is complete, select the system image from the list and clickNext.

  6. On the next screen, change the AVD Name to something like "Pixel phone", then clickFinish.

  7. In the Your Virtual Devices screen that appears, click the green triangle on the right side to launch this phone in the emulator:

    Be patient. It can take a few moments for the OS to start up the first time the system image is used.

  8. Once the emulator is up and running, return to your Project window, click theRunicon (green triangle) on the toolbar (or selectRun>Run 'app'), and select your Pixel phone.

    Eventually your sample app should open in the phone emulator:

The test is a success if you don't get any errors.

Initializing the framework

Before a user can use chat on their device, the application has to create and prepare an instance of the Chat SDK.

在本节中,您将update the sample application to initialize the Chat SDK and make it ready for use. The task consists of the following steps:

  1. Getting the Zendesk Chat account key
  2. Adding the initialization code to your application

Getting the Zendesk Chat account key

You'll need access to the Zendesk Chat dashboard to get the account key. If you don't have access, ask somebody who does to perform the following steps.

  1. In the Chat dashboard, click the profile icon in the upper right, then selectCheck Connection.

  2. Copy and save the account key. It should be the second item in the list.

Adding the initialization code to your application

Android applications are event driven, so you need to initialize the framework in an event handler. By default, your application comes with anonCreate(Bundle)event handler that runs when an instance of yourMainActivitysubclass is created. You can add your own code to this event handler.

  1. Make sure theMainActivity.javafile is open in the Android Studio editor. It should be open by default. If not, you'll find the file in the java/com.sample.mysamplechatapp folder.

  2. Add the following initialization statement to theonCreate(Bundle)handler (highlighted):

                   
    protectedvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Chat.INSTANCE.init(applicationContext,"your account key");}

    Note:ChatandapplicationContextshould turn red, indicating there's something wrong. You'll fix this in the next steps.

  3. To fix the error indicated by the redChattext, click anywhere in the red text, then pressOption+Enter(Mac) orAlt+Enter(Windows). If prompted, selectImport Classfrom the menu. Android Studio automatically adds the missing import statement in the top portion of the file:

                   
    ...import亚博.chat.Chat;

    TheChattext color should return to normal.

    If you prefer, you can insert the import statement manually.

  4. ReplaceapplicationContextin theinit()method withthis(no quotes).

  5. Replace theyour account keyplaceholder value in theinit()method with the account key you retrieved earlier from the Chat dashboard.

    TheonCreate()method should look as follows:

                   
    protectedvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Chat.INSTANCE.init(this,"4PBQNia9qItVDD98qmCYEfVesWLR4IFC");}
  6. Run a build to make sure you don't get any error messages.

Creating a button to start a chat

The chat functionality provided by the SDK is designed to start in response to an event such as a button click.

Your default sample project consists of a ConstraintLayout containing a TextView that displays "Hello World!". The application's layout is defined in theactivity_main.xmlfile in the res/layout folder:

You'll change the layout to a vertical LinearLayout containing a single Chat button.

  1. In the Project window, make sure theactivity_main.xmlfile is open in the editor. If not, you'll find the file in the res/layout folder.

    Note: If you don't see the XML from the previous screenshot, make sure thatCodeon the upper right side of the window is selected.

  2. Replace all the contents of the file with the following layout code:

                   
    <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:orientation="vertical"><Buttonandroid:id="@+id/chat_button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/chat_button"/>LinearLayout>

    Notice that the button text is a reference to a string resource:"@string/chat_button". You'll add the string resource in the next step.

  3. Open thestrings.xmlfile in the res/values/ folder and add the followingchild tag to thetag:

                   
    <亚博电脑端>...<stringname="chat_button">Chatstring>亚博电脑端>
  4. Save the files, then run a build to make sure you don't get any error messages.

    The app should display a vertically centered Chat button:

Adding an event listener for the Chat button

You'd like your app to start a chat when the user taps the Chat button. To do so, you'll need an event listener that detects the tap's click event, then starts the chat.

  1. Switch to theMainActivity.javafile in the Android Studio editor.

  2. In theonCreate(Bundle)handler, and after the SDK initialization statement, declare a local Button variable and assign your layout button to it (highlighted):

                   
    protectedvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Chat.INSTANCE.init(this,"4PBQNia9qItVDD98qmCYEfVesWLR4IFC");ButtonmChatButton;mChatButton=(Button)findViewById(R.id.chat_button);}

    TheR.id.chat_buttonid is defined by the lineandroid:id="@+id/chat_button"in theactivity_main.xmllayout file. The"@+id/"expression creates the id.

    Note that you must cast the View to Button before assigning it to your Button-typed variable.

  3. The Button string is probably red, so click anywhere in the string and pressOption+Enter(Mac) orAlt+Enter(Windows). Android Studio should add the following import statement to your file:

                   
    importandroid.widget.Button;
  4. Add the following click event listener after the variable assignment (highlighted):

                   
    ...ButtonmChatButton;mChatButton=(Button)findViewById(R.id.chat_button);mChatButton.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(View v){// start chat}});

    The stringViewinView.OnClickListener()should turn red, indicating a missing import. Click anywhere in the red text and pressOption+Enter(Mac) orAlt+Enter(Windows). Android Studio should add the following import statement to your file:

                   
    importandroid.view.View;
  5. Replace the// start chatcomment in theonClick(View)method with the following statement:

                   
    MessagingActivity.builder().withEngines(ChatEngine.engine()).show(v.getContext());

    TheMessagingActivityandChatEngineobjects should turn red. Click anywhere in each string, pressOption+Enter(Mac) orAlt+Enter(Windows), and selectImport Classif prompted. Android Studio should add the following import statements to your file:

                   
    import亚博.chat.ChatEngine;import亚博.messaging.MessagingActivity;

That's it. The completedMainActivitysubclass should look as follows:

             
publicclassMainActivityextendsAppCompatActivity{@OverrideprotectedvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Chat.INSTANCE.init(this,"4PBQNia9qItVDD98qmCYEfVesWLR4IFC");ButtonmChatButton;mChatButton=(Button)findViewById(R.id.chat_button);mChatButton.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(View v){MessagingActivity.builder().withEngines(ChatEngine.engine()).show(v.getContext());}});}}

You should have the following import statements at the top of the file:

             
packagecom.sample.mysamplechatapp;importandroidx.appcompat.app.AppCompatActivity;importandroid.os.Bundle;importandroid.view.View;importandroid.widget.Button;import亚博.chat.Chat;import亚博.chat.ChatEngine;import亚博.messaging.MessagingActivity;

Testing that chat works

You can start a test chat if one or more chat agents are online. If nobody is online and you're a Zendesk Chat agent or administrator, you can chat with yourself by setting your status toOnlinein the Chat dashboard:

Build and run the application in your Android emulator. After tapping your custom Chat button, the chat interface should appear. Enter a message and tap right-arrow icon next to the message field to initiate the chat. Answer or skip the pre-chat questions.

Next steps

At this point you should have a working Android application that lets users chat with support agents. Use the sample application to experiment with the rest of the SDK. Here are some resources:

Put your project under git and create branches to try out different things. You can always reset if something goes wrong.