Legacy — v1.0

How to install and configure the Sophonz Android SDK v1.0.

TIP — Obtain your app key

Sign in to the Sophonz console, add an app to a project with Add App, and use the app key issued on the app's App Management page.

Sophonz Android SDK Requirements

ItemRequirement
Java version1.8 or higher
min SDK24 or higher
compile SDK (= target SDK)34 or higher
Support LanguageJava, Kotlin
Gradle8.10.2 or higher
Gradle Plugin (AGP)8.8.0 or higher

Installing the Sophonz Android SDK

The Sophonz SDK is designed to collect runtime data from your application. Follow the steps below to install it.

1. Gradle Configuration

The Sophonz Android SDK is distributed via a Maven repository. Add the SDK in your project's Gradle configuration files.

1-1. Project-level build.gradle or settings.gradle

Add the Maven repository using either Groovy or Kotlin DSL.

Groovy DSL

allprojects {
  repositories {
    maven {
      url 'https://nexus.sophonz.com/repository/sophonz-maven-releases/'
    }
  }
}

Kotlin DSL

repositories {
  maven {
    url = uri("https://nexus.sophonz.com/repository/sophonz-maven-releases/")
  }
}

1-2. Module (app) level build.gradle

Add the Sophonz SDK to the dependencies section of your application.

Groovy DSL

dependencies {
  implementation 'com.sophonz:sophonz-android-sdk:1.0.32'
}

Kotlin DSL

dependencies {
  implementation("com.sophonz:sophonz-android-sdk:1.0.32")
}

TIP

Always use the latest SDK version.

1-3. Direct AAR installation

Create a libs directory under your application directory, copy the sophonz-android-sdk-version-release.aar file into it, then add the Sophonz SDK to the dependencies section.

Groovy DSL

dependencies {
  implementation files('libs/sophonz-android-sdk-1.0.32-release.aar')
}

Kotlin DSL

dependencies {
  implementation(files("libs/sophonz-android-sdk-1.0.32-release.aar"))
}

1-4. Desugaring

If minSdkVersion is below 26, you must enable core library desugaring.

Groovy DSL

compileOptions {
  ...
  coreLibraryDesugaringEnabled true
}
dependencies {
    // For AGP 7.4+
    coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.0.3'
    // For AGP 7.3
    // coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.2.3'
    // For AGP 4.0 to 7.2
    // coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.9'
}

Kotlin DSL

compileOptions {
  ...
  isCoreLibraryDesugaringEnabled = true
}
dependencies {
    // For AGP 7.4+
    coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.0.3")
    // For AGP 7.3
    // coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:1.2.3")
    // For AGP 4.0 to 7.2
    // coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:1.1.9")
}

2. Application Class Setup

The Sophonz SDK is initialized inside the Application class. Add the initialization code to the onCreate() method of your Application class.

  1. Register the Application class Set the android:name attribute in your AndroidManifest.xml to point to your Application class. Skip this step if an Application class already exists.
<application
    android:name=".Application"
    ...
>
</application>
  1. Write the SDK initialization code Add the following code to the onCreate() method of your Application class.

Kotlin

import com.sophonz.sdk.core.Sophonz
import com.sophonz.sdk.core.SophonzOption
 
class Application : android.app.Application() {
    override fun onCreate() {
        super.onCreate()
 
        val options = SophonzOption()
        options.setDefault()
        options.setCollectorURL("Enter the collector URL here.")
        options.setAppKey("Enter the app key here.")
        options.setSampleRate("Enter a sampling rate (0.0–1.0).") // default=0.5
        // Enter the namespace set when adding the dashboard service
        options.setProject("Namespace")
        // Deployment environment (optional, default: .PRODUCTION)
        //options.setEnvironment(Environment.DEVELOPMENT)
        // Auto click event collection (default=false)
        //options.setUserEventEnable(true)
 
        Sophonz.setup(options)
        Sophonz.initialize(this.applicationContext, this)
    }
}

Java

import com.sophonz.sdk.core.Sophonz;
import com.sophonz.sdk.core.SophonzOption;
 
public class Application extends android.app.Application {
    @Override
    public void onCreate() {
        super.onCreate();
 
        SophonzOption options = new SophonzOption();
        options.setDefault();
        options.setCollectorURL("Enter the collector URL here.");
        options.setAppKey("Enter the app key here.");
        options.setSampleRate("Enter a sampling rate (0.0–1.0)."); // default=0.5
        // Enter the namespace set when adding the dashboard service
        options.setProject("Namespace");
        // Deployment environment (optional, default: .PRODUCTION)
        //options.setEnvironment(Environment.DEVELOPMENT);
        // Auto click event collection (default=false)
        //options.setUserEventEnable(true)
 
        Sophonz.setup(options);
        Sophonz.initialize(this.getApplicationContext(), this);
    }
}
  • setCollectorURL: URL of the server that collects data.
  • setAppKey: The app key issued from the Sophonz console.
  • (optional) setSampleRate: Sampling rate. Default is 0.5 (50%).
    • Accepts a value between 0.0 and 1.0. (0.0: no collection, 1.0: 100% collection)

3. HTTPS Configuration

  1. Retrofit / OkHttp

To collect XHR data from Retrofit or OkHttp network requests, add HttpInterceptor as shown below.

Kotlin

val client = OkHttpClient.Builder()
    .addInterceptor(HttpInterceptor())
    .build()
 
val retrofit = Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .client(client)
    .addConverterFactory(GsonConverterFactory.create())
    .build()

Java

OkHttpClient client = new OkHttpClient.Builder()
    .addInterceptor(new HttpInterceptor())
    .build();
 
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .client(client)
    .addConverterFactory(GsonConverterFactory.create())
    .build();
  1. HttpURLConnection

To collect XHR data from HttpURLConnection-based network requests, wrap the connection as shown below.

Kotlin

// Wrap the HttpURLConnection(HttpsURLConnection) object with ConnectionWrapper
var url : URL = URL("https://some.host.com")
var conn = ConnectionWrapper.wrap(url.openConnection() as HttpURLConnection)

Java

// Wrap the HttpsURLConnection object with ConnectionWrapper
URL url = new URL("https://some.host.com");
HttpURLConnection conn = 
    ConnectionWrapper.wrap((HttpURLConnection) url.openConnection());
  1. Ktor (OkHttp engine)

When using the OkHttp engine with Ktor, add the interceptor as shown below.

Kotlin

val client = HttpClient(OkHttp) {
    engine {
        config {
            // Existing settings (timeouts, etc.)
            connectTimeout(2, TimeUnit.SECONDS)
            readTimeout(2, TimeUnit.SECONDS)
            writeTimeout(2, TimeUnit.SECONDS)
 
            // Add the interceptor
            addInterceptor(HttpInterceptor())
        }
    }
    install(Logging)
 
    install(ContentNegotiation) {
        json(Json { ignoreUnknownKeys = true })
    }
}

Verification

To confirm that Sophonz is working correctly, trigger a sample error and verify that the log is transmitted.

Sample Code

Add the following code to an appropriate location in your application to run a test.

Kotlin

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import java.lang.Exception
import com.sophonz.sdk.log.SophonzLog
 
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
 
        try {
            throw Exception("Test error")
        } catch (e: Exception) {
            SophonzLog.error("TestTag", "This is a test error", e)
        }
    }
}

Java

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.lang.Exception;
import com.sophonz.sdk.log.SophonzLog;
 
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        try {
            throw new Exception("Test error");
        } catch (Exception e) {
            SophonzLog.error("TestTag", "This is a test error", e);
        }
    }
}

Sophonz Android SDK Configuration

Custom User ID

Set a custom user ID to identify individual users during session analysis. Typically, set it to the user's ID (or employee number) on successful login, and clear it with an empty string ("") on logout. Must be called after Sophonz.initialize.

Kotlin

Sophonz.custom.setupUserId("customer-user-id")

Java

Sophonz.getCustomAttributes().setupUserId("customer-user-id");

Custom Event Tracking

Send an event notification when a specific button or tab is clicked.

Sophonz.sendClickEvent(view: View, isNetworkRequest: Boolean = false)

  • view: the clicked target, isNetworkRequest: whether a data request follows

For a simple screen navigation button click:

Kotlin

val intent = Intent(this, HelloActivity::class.java)
binding.button.setOnClickListener { startActivity(intent) }
 
Sophonz.sendClickEvent(binding.button, false)

Java

Intent intent = new Intent(this, HelloActivity.class);
binding.button.setOnClickListener(v -> {
    startActivity(intent);
});
Sophonz.sendClickEvent(binding.button, false);

When the button click triggers a server data request:

Kotlin

binding.button.setOnClickListener {
    Sophonz.sendClickEvent(it, true)
    service.getHello().enqueue(object : retrofit2.Callback<Data> {
        override fun onFailure(call: Call<Data>, t: Throwable) {
            t.printStackTrace()
        }
 
        override fun onResponse(call: Call<Data>, response: Response<Data>) {
            response.body()?.let { data ->
                SophonzLog.debug("MainActivity", "Data: $data")
            }
        }
    })
}

Java

binding.button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Sophonz.sendClickEvent(v, true);
        service.getHello().enqueue(new Callback<Data>() {
            @Override
            public void onResponse(Call<Data> call, Response<Data> response) {
                Data data = response.body();
                if (data != null) {
                    SophonzLog.debug("MainActivity", "Data: " + data.toString());
                }
            }
 
            @Override
            public void onFailure(Call<Data> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }
});

WebView Session Bridging

To combine a native app session with a WebView page session, call JavaScriptInjector.injectSession(view) before calling webView.loadUrl(serverUrl).

TIP — Sophonz configuration in hybrid apps (WebView)

The Sophonz Android SDK, iOS SDK, and Browser SDK each collect data suited to their respective environments.

Kotlin

// ... omitted ...
JavaScriptInjector.injectSession(webView)
webView.loadUrl(serverUrl)
// ... omitted ...

Java

// ... omitted ...
JavaScriptInjector.injectSession(webView);
webView.loadUrl(serverUrl);
// ... omitted ...

Cordova Library WebView Setup

When using the Cordova library, configure the WebView as follows.

Cordova Library build.gradle

    compileOnly(files("libs/sophonz-android-sdk-1.0.32-release.aar"))

WebView Interface Setup

Use JavaScriptInjector.injectSession(view) to connect the sessions.

protected void init() {
   appView = makeWebView();
   createViews();
   if (!appView.isInitialized()) {
       appView.init(cordovaInterface, pluginEntries, preferences);
   }
   cordovaInterface.onCordovaInit(appView.getPluginManager());
 
   // Inject WebView Interface
   WebView realWebView = (WebView) ((SystemWebViewEngine) appView.getEngine()).getView();
   JavaScriptInjector.injectSession(realWebView);
 
   String volumePref = preferences.getString("DefaultVolumeStream", "");
   if ("media".equals(volumePref.toLowerCase(Locale.ENGLISH))) {
       setVolumeControlStream(AudioManager.STREAM_MUSIC);
   }
}

Fragment Lifecycle

Fragment lifecycle events (onCreate, onStart, onResume, etc.) are automatically instrumented to track screen entry and exit. If obfuscation tools rename classes based on f.javaClass.simpleName, add the following ProGuard/R8 rule to preserve Fragment class names.

ProGuard

-keepnames class * extends androidx.fragment.app.Fragment 

To disable Fragment-level instrumentation, set the option during initialization:

options.setFragmentLifecycleEnabled(false) 

Custom Logging

Use the SophonzLog API to collect custom user logs when needed. Log levels are debug, info, warn, and error.

WARNING — Custom logging caution

Use custom logging only when necessary. Excessive logging can degrade app performance and increase storage usage due to additional collected data.

TIP — Trace critical logic and transactions

Leave custom messages to identify problem patterns and exceptions in your service.

Kotlin

SophonzLog.debug("TAG", "message")
SophonzLog.info("TAG", "message")
SophonzLog.warn("TAG", "message")
SophonzLog.error("TAG", "message", RuntimeException("exception"))

Java

SophonzLog.debug("TAG", "message");
SophonzLog.info("TAG", "message");
SophonzLog.warn("TAG", "message");
SophonzLog.error("TAG", "message", new RuntimeException("exception"));

TIP — This is just the beginning

Now ship your app. Sophonz surfaces the problems real users hit — so your app evolves on its own.