Quick Start Guide for Android APS SDK

Pro or Enterprise Subscription Required

Icon

This AMPLIFY Appcelerator Services feature requires a Pro or Enterprise Subscription. 

Introduction

This guide walks through the setup of the AMPLIFY Appcelerator Services for Android applications. The AMPLIFY Appcelerator Services SDK gives you access to the Appcelerator Analytics, Cloud, and CloudPush services.

Not developing a native Android application with Java?

See the following topics to use the AMPLIFY Appcelerator Services on other platforms:

For native iOS applications built with Objective-C, see Quick Start Guide for iOS APS SDK.

For Titanium Applications, see Quick Start.

Requirements

This document assumes you have an existing Android application and Android Studio already installed on your system.

Setup

Before you can use Appcelerator Services in your application you need to:

  • Create an application in Dashboard
  • Download the APS SDK
  • Get the Services key

Register an APS SDK application

Appcelerator Platform Services (APS) SDK for iOS and Android provides support for Appcelerator Analytics and Cloud services for your Android applications built with the native Android APIs and Java and iOS applications built with the native iOS APIs and Objective-C or Swift.

To register an APS SDK application for services:

  1. Sign in to the AMPLIFY Platform.
  2. Click the Add menu (+) and select Register App for Services to open the Register App for Services form.
  3. Enter the Name of the application.  
  4. Select APS SDK from the Type selection menu.
  5. Select a Platform (Andriod or iOS).
  6. Optionally, enter a unique Identifier for your application.
  7. Optionally, enter a Description for your application.
  8. Select Services for your application by selecting or deselecting the check-boxes for the following:
    • Analytics
    • Provision Cloud Services (Mobile Backend Services)
  9. Add teams to the application from your organization by clicking the add (+) button in the Assign Teams list.
  10. Click OK.

Appcelerator Dashboard displays the Services tab for your application. Follow the directions to add Platform Services to your application.

Register an API or Microservice application

To register an API or microservice application:

  1. Sign in to the AMPLIFY Platform.
  2. Click the Add menu (+) and select Register App for Services to open the Register App for Services form.
  3. Enter the Name of the application.  
  4. Select API/Microservice from the Type selection menu.
  5. Enter a Platform for your application.
  6. Optionally, enter a unique Identifier for your application.
  7. Optionally, enter a Description for your application.
  8. Select Services for your application by selecting or deselecting the check-boxes for the following:
    • Analytics
    • Provision Cloud Services (Mobile Backend Services)
  9. Add teams to the application from your organization by clicking the add (+) button in the Assign Teams list.
  10. Click OK.

Register a Website or Web application

To register a Website or Web application:

  1. Sign in to the AMPLIFY Platform.
  2. Click the Add menu (+) and select Register App for Services to open the Register App for Services form.
  3. Enter the Name of the application.  
  4. Select Website/Web App from the Type selection menu.
  5. Enter a Platform for your application.
  6. Optionally, enter a unique Identifier for your application.
  7. Optionally, enter a Description for your application.
  8. Select Services for your application by selecting or deselecting the check-boxes for the following:
    • Analytics
    • Provision Cloud Services (Mobile Backend Services)
  9. Add teams to the application from your organization by clicking the add (+) button in the Assign Teams list.
  10. Click OK.

Register a Custom application

To register a custom application (other than APS SDK, API/Microservice, or Website/Web applications):

  1. Sign in to the AMPLIFY Platform.
  2. Click the Add menu (+) and select Register App for Services to open the Register App for Services form.
  3. Enter the Name of the application.  
  4. Select Other from the Type selection menu.
  5. Enter a Platform for your application.
  6. Optionally, enter a unique Identifier for your application.
  7. Optionally, enter a Description for your application.
  8. Select Services for your application by selecting or deselecting the check-boxes for the following:
    • Analytics
    • Provision Cloud Services (Mobile Backend Services)
  9. Add teams to the application from your organization by clicking the add (+) button in the Assign Teams list.
  10. Click OK.

Dashboard displays the Platform Services tab for your application. In the tab, you can download the APS (Appcelerator Platform Services) SDK and get code snippets to copy and paste into your application.

For more information, refer to Managing Non-Titanium Client Applications in Dashboard.

Quick tutorial

The following tutorial demonstrates basic setup and usage of Analytics and Cloud libraries in a new Android app project. To complete the tutorial, you will need your application key for the Cloud and Analytics services.

To create a basic application using the APS SDK:

  1. In Android Studio, create a new Android app project using the "Empty Activity" template.
  2. Create a libs folder under your Android app project folder.
  3. Unzip the appcelerator-sdk-android-<VERSION>.zip file.
  4. From the unzipped SDK's libs folder, copy the following files to your app project's libs folder:
    • aps-analytics.aar
    • aps-cloud.aar
    • aps-services.aar
  5. If you want to add push notification support, then also copy the following file:

    • aps-cloudpush.aar
  6. Open the build.gradle file under your Android app project folder and add the following dependencies block. Uncomment the APS CloudPush part if you want to add push notification support.

    dependencies {
    	// Copy the APS libraries to the project's "libs" directory and reference them like this.
    	implementation fileTree(dir: 'libs', include: ['*.aar'])
    
    	// APS libraries depend on the following Google library.
    	implementation 'com.google.android.gms:play-services-base:17.1.0'
    
    	// APS CloudPush library also depends on the following Google libraries.
    	// Note: APS sends push notifications via Firebase and receives them via GCM library.
    //	implementation 'androidx.appcompat:appcompat:1.1.0'
    //	implementation 'com.google.android.gms:play-services-gcm:17.0.0'
    }
  7. Add the following import statement to the main Activity of the project: 

    import com.appcelerator.aps.APSServiceManager;
  8. In the main Activity's onCreate() method, add the following method call to enable the APS services.

    APSServiceManager.getInstance().enable(this, "YOUR_APP_KEY");

    The Android application is now ready to make method calls using the APS SDK APIs.

Modify the application

Customize the application's UI to display a spinner, text field and button, and add some logic to respond to user interaction. The spinner will display a list of available user accounts. The user can enter their password in the text field, then click the button to log in.

  1. Open the fragment layout XML file (res/layout/fragment_main.xml) in the Graphical Layout editor.
  2. Remove the "Hello World!" label.
  3. Drag a Spinner widget, EditText widget (password text field), and Button widget into the view.

  4. In the MainActivity.java file, modify the code to save an instance of the current activity, Spinner and EditText widgets. Modify the application to bind a doClick method to the Button's onClick listener and create an empty function called populateSpinner. You also need to import additional packages. In the following sections, you will add code to these handlers that call the Cloud and Analytics services. 

    // Import the following packages
    import android.app.Activity;
    import android.util.Log;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Spinner;
    import java.util.HashMap;
    import org.json.JSONArray;
    import com.appcelerator.aps.APSAnalytics;
    import com.appcelerator.aps.APSCloudException;
    import com.appcelerator.aps.APSResponse;
    import com.appcelerator.aps.APSResponseHandler;
    import com.appcelerator.aps.APSServiceManager;
    import com.appcelerator.aps.APSUsers;
    
    public class MainActivity extends ActionBarActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // Enable the Appcelerator Platform Services.
            APSServiceManager.getInstance().enable(this, "YOUR_APP_KEY");
    
            if (savedInstanceState == null) {
                getSupportFragmentManager()
                        .beginTransaction()
                        .add(R.id.container, new PlaceholderFragment())
                        .commit();
            }
        }
    
        private static class PlaceholderFragment extends Fragment {
            // Handle to Spinner and EditText widgets
            Spinner spinner;
            EditText textField;
    
            @Override
            public View onCreateView(
                    LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
                View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    
                // Bind the Button do the doClick method
                Button button = (Button)rootView.findViewById(R.id.button1);
                button.setOnClickListener(new Button.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        doClick();
                    }
                });
    
                // Save the Spinner and EditText instances
                spinner = (Spinner)rootView.findViewById(R.id.spinner1);
                textField = (EditText)rootView.findViewById(R.id.editText1);
    
                // Place holder for the next tutorial steps
                populateSpinner();
                return rootView;
            }
    
            // Placeholder for next tutorial steps
            public void doClick() {
            }
    
            public void populateSpinner() {
            }
        }
    }

Capture user session events

Unlike the iOS and Titanium platforms, you need to explicitly make analytic method calls to send user session events to the Analytics service to capture user activity. First, call the APSAnalytics' sendAppInstallEvent() in the main activity's onCreate() method. This must be called after enabling APSServiceManager.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Enable the Appcelerator Platform Services.
    APSServiceManager.getInstance().enable(this, "YOUR_APP_KEY");

    // Send the app install analytics event.
    APSAnalytics.getInstance().sendAppInstallEvent();

    // Your init code...
}

Use onPause() and onResume() to call the APSAnalytics' sendSessionStartEvent() and sendSessionEndEvent() respectively. These two APSAnalytics methods send user session events to the APS Analytics servers to track how long a user engages with your application. 

@Override
protected void onPause(){
    super.onPause();
    APSAnalytics.getInstance().sendSessionEndEvent();
}

@Override
protected void onResume(){
    super.onResume();
    APSAnalytics.getInstance().sendSessionStartEvent();
}

Send an Analytics custom event

Besides user session events, you can also send custom analytics events, as shown in this example. You can use feature events as one type of custom events.

In the doClick() function, add an APSAnalytics' sendCustomEvent() method call to send a feature event with the string "sample.feature.login". The optional second parameter is set to null for this example, but you can send additional data as a JSON object with the event.

public void doClick(View view){
   	APSAnalytics.getInstance().sendCustomEvent("sample.feature.login", null);
}; 

Query Cloud users

To use the APS Cloud component, most of the methods require a user to be logged in. This sample uses the Spinner widget to select a Cloud user account. To populate the Spinner values, the application needs to retrieve a list of users. Use the APSUsers.query() method to retrieve a list of user accounts.

Every APS Cloud method includes a handler parameter that specifies the callback to handle the server response. The callback is passed an APSResponse object that contains response metadata (such as success or failure) and the response payload.

public void populateSpinner() {
    try {
        APSUsers.query(null, new APSResponseHandler() {
            @Override
            public void onResponse(final APSResponse e) {
                if (e.getSuccess()) {
                    try {
	                    JSONArray payload = e.getResponse().getJSONArray("users");
	                    String[] items = new String[payload.length()];
	                    for (int i = 0; i < payload.length(); i++) {
	                        items[i] = payload.getJSONObject(i).getString("username");
	                    }
	                    ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(currentActivity,
	                        android.R.layout.simple_spinner_item, items);
	                    spinner.setAdapter(spinnerArrayAdapter); 
	                } catch (Exception ex) {
	                    Log.e("ACSUsers", "Error parsing JSON object: " + ex.toString());
	                }
                }                
                else {
                	Toast.makeText(currentActivity, "ERROR: Unable to get users.", Toast.LENGTH_SHORT).show();
                    Log.e("ACSUsers", e.getResponseString());
                }                   
            }
 
            @Override
            public void onException(APSCloudException e) {
                Log.e("ACSUsers", e.toString());
            }
        });
    } catch (APSCloudException e) {
        Log.e("ACSUsers", e.toString());
    }     
}

Log in to a Cloud account

To log in to a Cloud account, you need the username and password. Since the application was modified to get all available user accounts and populate the Spinner, the application needs to get the current value of the spinner and the text entered in the EditText widget. These values are passed to the APSUsers.login() method. Modify the doClick() method to login to a Cloud user account.

public void doClick(){
	APSAnalytics.getInstance().sendCustomEvent("sample.feature.login", null);
	
    // Get the current value of the Spinner and EditField widgets
	final String username = spinner.getSelectedItem().toString();
	String password = textField.getText().toString();
    
	// Use a HashMap to send the method parameters for the request
    HashMap<String, Object> data = new HashMap<String, Object>();
    data.put("login", username);
    data.put("password", password);
    
    try {
        APSUsers.login(data, new APSResponseHandler() {
            @Override
            public void onResponse(final APSResponse e) {
                if (e.getSuccess()) {
                	Log.i("ACSUsers", "Successfully logged in as " + username);
                }
                else {
                    Log.e("ACSUsers", e.getMessage());
                }                   
            }
 
            @Override
            public void onException(APSCloudException e) {
                Log.e("ACSUsers", e.toString());

            }
        });
    } catch (APSCloudException e) {
        Log.e("ACSUsers", e.toString());
    }          	
}

Testing the tutorial sample

Before testing the sample, you need to create user accounts for the application to query. To create Cloud user accounts:

  1. Login to the AMPLIFY Platform.
  2. On the Dashboard tile, select Go to Dashboard.
  3. Select your Mobile Backend Services app from the Projects menu.
  4. In the left navigation bar, click Manage Data.
  5. Click Users, then the Create User button.
  6. In the Username field, enter the user's username.
  7. In the Password field, enter the new user's password (four-character minimum).
  8. Click Save Changes.
Icon

To create a Cloud user account, you only need a username or e-mail address and a password.

For more information about managing Cloud user accounts, see Managing Organizations.

After you have created a few Cloud user accounts, build the sample and launch it on either a device or emulator.

Once the application launches:

  1. Click on the Picker/Spinner. You should see a list of all the Cloud user accounts you added.
  2. Select a user account from the Picker/Spinner and enter that user's password. Click the Button. In the log output, you should see an info log that login command was successful or not.
  3. Go back to the Dashboard.
  4. In Dashboard, select your application from the Apps menu in the upper-left corner.
  5. In the left navbar, click Search by User. Enter the username of the account that successfully logged in. Click the username. You should see a crash report for the user. 
  6. In the left navbar, select Analytics.
  7. In the Real-Time view, you should see at least one active session.
  8. In the left navbar, click Events. You should see the "sample.feature.login" feature event.

Next Steps for Appcelerator Analytics and Cloud

This tutorial only covers a small portion of what the Analytics and Cloud services can provide. For more in-depth information about these features, see the following topics:

Related Links