Filter results by

Your first Android app

Browse source for this tutorial.

Let's build an Android application that communicates to ARTIK Cloud using ARTIK Cloud's Java/Android SDK. You will learn:

Prerequisites

Initial setup

Create an application

Follow these instructions to create an application using the Developer Dashboard. For this tutorial, select the following:

  • Set "Redirect URL" for your application to cloud.artik.example.hellocloud://oauth2callback.
  • Under Authentication, only check "Authorization Code with PKCE" as AUTH METHODS.
  • Under "PERMISSIONS", click the "Add Device Type" button. Choose "Example Activity Tracker" (device type ID: cloud.artik.example.activitytracker) as the device type. Check both "Read" and "Write" permissions for this device type.

Make a note of your client ID. This is your application ID, which you will need later.

Connect a device

Follow these instructions to create and connect a device with My ARTIK Cloud. For this tutorial, select the following:

  • "Example Activity Tracker" (device type unique name: cloud.artik.example.activitytracker).

Now as an ARTIK Cloud user, you have a device. The sample app will access your data on this device.

Get the device ID

In My ARTIK Cloud, click the name of the device you just connected. A window like the following will appear.

device info screen

Make a note of the device ID on the above screen. You will use it in the sample app.

The end goal of the above steps is to create an application with the redirect URL that works with this sample app, and get the client ID (application ID) and device ID to set up the Android project below.

Set up your Android project

  • Get the sample application Android project at GitHub
  • Change CLIENT_ID and DEVICE_ID to your own IDs in the following lines in Config.java of the sample application:
1
2
static final String CLIENT_ID = "YOUR_CLIENT_ID";// AKA application id
static final String DEVICE_ID = "YOUR_DEVICE_ID";
  • Build the Android project of the sample application.

This sample application uses ARTIK Cloud Java/Android SDK library downloaded from Maven Central Repository. The version of the library is specified in app/build.gradleof the Android project. You may also build ARTIK Cloud Java/Android SDK library using the source code at GitHub.

The sample application uses Android SDK with API level 24.

Demo

Before we dig in, let's preview how our simple Android application will work.

  • Launch the app on your Android phone. Click the login button.
    ARTIK Cloud first Android app
  • Sign in using your account in the browser.
    ARTIK Cloud first Android app
  • If this is your first time using this app, you will see the following permission screen. Click "Allow".
    ARTIK Cloud first Android app
  • You are redirected to a new page where you can play with ARTIK Cloud as follows:
    ARTIK Cloud first Android app
  • Click "Send a message" to send a message to ARTIK Cloud on behalf of your device.
  • Click "Get a message" to get the latest message from your device on ARTIK Cloud. Note that it may take up to a few seconds for your message to appear since the called API is not intended for real-time data streaming.
  • After sending and receiving messages, your screen should look like this:
    ARTIK Cloud first Android app

Implementation Details

The following two Java files implement the major logics.

  • LoginActivity.java handles OAuth2 authentication to get the user token (one of the three types of access tokens).
  • MessageActivity.java gets your name, sends a message on behalf of the device, and gets the device's latest message from ARTIK Cloud.

Login to obtain access token

LoginActivity.java implements Authorization Code with PKCE method. Thanks to AppAuth for Android, the implementation is very easy. LoginActivity.java makes two calls to the ARTIK Cloud accounts server.

The first call is to get the authorization code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private void doAuth() {
    AuthorizationRequest authorizationRequest = AuthHelper.createAuthorizationRequest();

    PendingIntent authorizationIntent = PendingIntent.getActivity(
            this,
            authorizationRequest.hashCode(),
            new Intent(INTENT_ARTIKCLOUD_AUTHORIZATION_RESPONSE, null, this, LoginActivity.class),
            0);

    /* request sample with custom tabs */
    CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
    CustomTabsIntent customTabsIntent = builder.build();

    mAuthorizationService.performAuthorizationRequest(authorizationRequest, authorizationIntent, customTabsIntent);
}

After receiving the code, make the second call to get the access token:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private void handleAuthorizationResponse(@NonNull Intent intent) {
    AuthorizationResponse response = AuthorizationResponse.fromIntent(intent);
    final AuthState authState = new AuthState(response, error);

    mAuthorizationService.performTokenRequest(response.createTokenExchangeRequest(), new AuthorizationService.TokenResponseCallback() {
        @Override
        public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse, @Nullable AuthorizationException exception) {
            if (tokenResponse != null) {
                authState.update(tokenResponse, exception);
                mAuthStateDAL.writeAuthState(authState); //store into persistent storage for use later
                startMessageActivity();
            } else { /* code exchange failed*/}
        }
    });
}

After obtaining the access token, LoginActivity.java stores the token info into the persistent storage and starts MessageActivity.java.

Call ARTIK Cloud APIs

MessageActivity.java retrieves the access token from the persistent storage and uses it to communicate to ARTIK Cloud to:

  • Get the user's information.
  • Send a message on behalf of the device.
  • Get the latest message sent by the device.

It performs the above operations by calling API methods of ARTIK Cloud's SDK library.

To facilitate using API methods of the SDK later, MessageActivity.java first performs the following setup:

1
2
3
4
5
6
7
private void setupArtikCloudApi() {
  mApiClient = new ApiClient();
  mApiClient.setAccessToken(mAccessToken);

  mUsersApi = new UsersApi(mApiClient);
  mMessagesApi = new MessagesApi(mApiClient);
}

Note that the access token is added to the authorization header above. This ensures that every request sent to ARTIK Cloud contains the correct authorization header.

Get the user's name from ARTIK Cloud

Call REST API Get the user's profile. With the SDK, MessageActivity.java calls mUsersApi.getSelfAsync as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
mUsersApi.getSelfAsync(new ApiCallback<UserEnvelope>() {
    @Override
    public void onFailure(ApiException exc, int statusCode, Map<String, List<String>> map) {
        processFailure(tag, exc);
    }

    @Override
    public void onSuccess(UserEnvelope result, int statusCode, Map<String, List<String>> map) {
        updateWelcomeViewOnUIThread("Welcome " + result.getData().getFullName());
    }

    @Override
    public void onUploadProgress(long bytes, long contentLen, boolean done) {
    }

    @Override
    public void onDownloadProgress(long bytes, long contentLen, boolean done) {
    }
}

Method onSuccess() extracts the user's name and shows it on the UI.

Send a message to ARTIK Cloud

Let's send a message to ARTIK Cloud on behalf of the demo device by making a POST call. Set up a button in MessageActivity.java to initiate sending upon clicking.

1
2
3
4
5
6
7
8
9
sendMsgBtn.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Log.v(TAG, ": send button is clicked.");

        // Reset UI
        mSendResponse.setText("Response:");

        postMsg();
    }

Method postMsg() uses mMessagesApi.sendMessageAsync to send a POST request as following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
private void postMsg() {
    final String tag = TAG + " sendMessageAsync";

    Message msg = new Message();
    msg.setSdid(DEVICE_ID);
    msg.getData().put("stepCount", 4393);
    msg.getData().put("heartRate", 110);
    msg.getData().put("description", "Run");
    msg.getData().put("activity", 2);

    try {
        mMessagesApi.sendMessageAsync(msg, new ApiCallback<MessageIDEnvelope>() {
            @Override
            public void onFailure(ApiException exc, int i, Map<String, List<String>> stringListMap) {
                processFailure(tag, exc);
            }

            @Override
            public void onSuccess(MessageIDEnvelope result, int i, Map<String, List<String>> stringListMap) {
                updateSendResponseOnUIThread(result.getData().toString());
            }

            @Override
            public void onUploadProgress(long bytes, long contentLen, boolean done) {
            }

            @Override
            public void onDownloadProgress(long bytes, long contentLen, boolean done) {
            }
        });
    } catch (ApiException exc) {
        processFailure(tag, exc);
    }
}

To make a POST /message call, you need to set the source device ID and data fields in the Message object. The SDK library constructs the payload of a POST request based on the object.

The data format depends entirely on the device type you're using to send data to ARTIK Cloud. The provided data is for the device with type "Example Activity Tracker".

As a result of sending a message, you'll get a message ID (or errors) that you could use to query that message later.

Get a message from ARTIK Cloud

Now get the latest message on ARTIK Cloud that was sent by the demo device. The sample app calls the REST API Get a message.

MessageActivity.java sets up a button to initiate getting a message upon clicking.

1
2
3
4
5
6
7
8
9
10
getLatestMsgBtn.setOnClickListener(new View.OnClickListener() {
  public void onClick(View v) {
    // Reset UI
    mGetLatestResponseId.setText("id:");
    mGetLatestResponseData.setText("data:");
    
    // Now get the message
    getLatestMsg();
  }
});

Again, MessageActivity.java calls mMessagesApi.getLastNormalizedMessagesAsync() to send a GET request to ARTIK Cloud.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
private void getLatestMsg() {
    final String tag = TAG + " getLastNormalizedMessagesAsync";
    try {
        int messageCount = 1;
        mMessagesApi.getLastNormalizedMessagesAsync(messageCount, DEVICE_ID, null,
          new ApiCallback<NormalizedMessagesEnvelope>() {
              @Override
              public void onFailure(ApiException exc, int i, Map<String, List<String>> stringListMap) {
                  processFailure(tag, exc);
              }

              @Override
              public void onSuccess(NormalizedMessagesEnvelope result, int i, Map<String, List<String>> stringListMap) {
                  updateGetResponseOnUIThread(result.getData().get(0).getMid(), result.getData().get(0).getData().toString());
              }

              @Override
              public void onUploadProgress(long bytes, long contentLen, boolean done) {
              }

              @Override
              public void onDownloadProgress(long bytes, long contentLen, boolean done) {
              }
          });
    } catch (ApiException exc) {
        processFailure(tag, exc);
    }
}

As shown above, to make the call to get the latest messages, pass the message count and the source device ID. The source device ID is the device ID of the demo device. If the call succeeds, the information of the latest message from ARTIK Cloud will be shown on the screen.

Customization

The sample app uses a specific redirect URL. You can change it, but make sure the following four spots are consistent to each other. Let's use cloud.artik.example.hellocloud://oauth2callback as a URL example.

  • Set "Redirect URL" for your application to cloud.artik.example.hellocloud://oauth2callback at the Developer Dashboard.
  • REDIRECT_URI in the following line in Config.java is consistent with the Developer Dashboard setup:
1
public static final String REDIRECT_URI = "cloud.artik.example.hellocloud://oauth2callback";
  • The intent-filter field for RedirectUriReceiverActivity in AndroidManifest.xml respects your URL setup at the Developer Dashboard:
1
<data android:scheme="cloud.artik.example.hellocloud" android:host="auth2callback"/>
  • The appAuthRedirectScheme at the following line in build.gradle (Module: app) respects your URL setup at the Developer Dashboard:
1
manifestPlaceholders = [appAuthRedirectScheme: "cloud.artik.example.hellocloud://oauth2callback"]