### Complete Configuration Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/configuration.md
This example demonstrates how to build and start the mParticle SDK with a comprehensive set of configuration options.
```java
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// Build initial identify request
IdentityApiRequest identifyRequest = IdentityApiRequest.withEmptyUser()
.email("user@example.com")
.customerId("CUST-12345")
.build();
// Set location tracking parameters
MParticleOptions.LocationTracking locationTracking = new MParticleOptions.LocationTracking();
locationTracking.enabled = true;
locationTracking.provider = LocationManager.NETWORK_PROVIDER;
locationTracking.minTime = 120000; // 2 minutes
locationTracking.minDistance = 50; // 50 meters
// Build SDK options
MParticleOptions options = MParticleOptions.builder(this)
// Required
.credentials("YOUR_API_KEY", "YOUR_API_SECRET")
// Environment
.environment(MParticle.Environment.Production)
.installType(MParticle.InstallType.AutoDetect)
// Logging
.logLevel(MParticle.LogLevel.WARNING)
// Timing
.uploadInterval(600) // 10 minutes
.sessionTimeout(120) // 2 minutes
.configMaxAge(3600) // 1 hour
.persistenceMaxAgeSeconds(2592000) // 30 days
.identityConnectionTimeout(15)
// Features
.uncaughtExceptionLogging(true)
.devicePerformanceMetricsDisabled(false)
.androidIdEnabled(true)
// User Management
.identify(identifyRequest)
.identifyTask(new BaseIdentityTask()
.addSuccessListener(result -> {
Log.d("APP", "Initial identify: " + result.getUser().getId());
})
.addFailureListener(result -> {
Log.e("APP", "Initial identify failed: " + result.getHttpCode());
}))
// Tracking
.locationTracking(locationTracking)
.pushRegistration(fcmToken, "123456789")
// Analytics
.attributionListener((kitId, results) -> {
Log.d("APP", "Attribution from kit " + kitId);
})
// Network
.networkOptions(new NetworkOptions()
.connectionTimeout(15)
.socketTimeout(30))
.build();
// Start SDK
MParticle.start(options);
}
}
```
--------------------------------
### Upload and Sync
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/quick-reference.md
Examples for forcing an immediate upload of data and changing the upload interval.
```java
// Force upload now
MParticle.getInstance().upload();
// Change upload interval
MParticle.getInstance().setUpdateInterval(120); // 2 minutes
```
--------------------------------
### Listen for Push Broadcasts
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/quick-reference.md
Example of how to listen for push notification broadcasts from mParticle.
```java
IntentFilter filter = new IntentFilter();
filter.addAction("com.mparticle.push.RECEIVE");
filter.addAction("com.mparticle.push.TAP");
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
ProviderCloudMessage message = intent.getParcelableExtra("mp-push-message");
Log.d("TAG", "Push message: " + message.getBody());
}
};
LocalBroadcastManager.getInstance(context).registerReceiver(receiver, filter);
```
--------------------------------
### Include only the current Kit in settings-kits.gradle
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/ONBOARDING.md
Example of how to comment out unnecessary kits in the settings-kits.gradle file to speed up build times and simplify troubleshooting.
```groovy
include(
':kits:adjust-kit',
':kits:adobe-kit'
/* ':kits:adobemedia-kit',
':kits:appboy-kit',
... */
)
```
--------------------------------
### Basic Push Setup Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-messaging.md
Example of initializing mParticle and enabling push notifications with a given FCM Sender ID, and suppressing auto-display.
```java
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// Initialize mParticle
MParticleOptions options = MParticleOptions.builder(this)
.credentials("YOUR_API_KEY", "YOUR_API_SECRET")
.build();
MParticle.start(options);
// Enable push notifications
// Get your FCM Sender ID from Firebase Console
MParticle.getInstance().Messaging().enablePushNotifications("123456789");
// Suppress auto-display to handle notifications manually
MParticle.getInstance().Messaging().displayPushNotificationByDefault(false);
}
}
```
--------------------------------
### Android Manifest Setup
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/quick-reference.md
Required permissions and service declarations for the mParticle SDK in the Android Manifest.
```xml
```
--------------------------------
### Handling Multiple Users Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-identity.md
Example demonstrating how to switch between multiple users.
```java
private void switchUser(long mpid) {
MParticleUser targetUser = MParticle.getInstance().Identity().getUser(mpid);
if (targetUser != null) {
// Already exists, just log them in again
MParticleUser currentUser = MParticle.getInstance().Identity().getCurrentUser();
IdentityApiRequest request = IdentityApiRequest.withUser(targetUser)
.build();
MParticle.getInstance().Identity().login(request)
.addSuccessListener(result -> {
Log.d("APP", "Switched to user: " + result.getUser().getId());
});
}
}
```
--------------------------------
### Install Type Configuration
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/configuration.md
Set the installation source detection mode.
```java
.installType(MParticle.InstallType.KnownInstaller)
```
--------------------------------
### Custom Push Handler
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/quick-reference.md
Example of how to create a custom push receiver to handle incoming push notifications and taps.
```java
public class MyPushReceiver extends PushAnalyticsReceiver {
@Override
public boolean onNotificationReceived(ProviderCloudMessage message) {
Log.d("TAG", "Push: " + message.getBody());
return false; // Let mParticle display
}
@Override
public boolean onNotificationTapped(ProviderCloudMessage message) {
String url = message.getRedirectUrl();
// Handle tap
return true;
}
}
MParticle.getInstance().Messaging()
.registerPushAnalyticsReceiver(new MyPushReceiver());
```
--------------------------------
### Queue Requests
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/quick-reference.md
Example of how to queue Identity API requests to handle rate limiting (HTTP 429 errors).
```java
private Queue queue = new LinkedList<>();
private void processQueue() {
if (queue.isEmpty()) return;
IdentityApiRequest request = queue.poll();
MParticle.getInstance().Identity().identify(request)
.addSuccessListener(result -> processQueue())
.addFailureListener(result -> {
if (result.getHttpCode() == 429) {
queue.addFirst(request); // Re-queue
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(this::processQueue, 2000);
} else {
processQueue();
}
});
}
```
--------------------------------
### Product Builder Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-events.md
Example of building a Product object.
```java
Product product = new Product.Builder("Blue Widget", "WIDGET-BLU", 19.99, 2)
.category("Widgets")
.brand("ACME")
.couponCode("SAVE10")
.position(1)
.variant("Large")
.customAttributes(Collections.singletonMap("color", "blue"))
.build();
```
--------------------------------
### Session Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/types.md
Example of how to retrieve and use Session information.
```java
Session session = MParticle.getInstance().getCurrentSession();
if (session != null) {
String uuid = session.getSessionUUID(); // "550E8400-E29B-41D4-A716-446655440000"
long startTime = session.getSessionStartTime(); // 1622505600000
long id = session.getSessionID(); // -3453425435345344234
}
```
--------------------------------
### Add the Example Kit as a submodule
Source: https://github.com/mparticle/mparticle-android-sdk/wiki/Kit-Development
Integrates the example kit repository as a submodule into the Core SDK repository.
```bash
git submodule add git@github.com:MYORGANIZATION/mparticle-android-integration-example.git kits/COMPANYNAME-kit
```
--------------------------------
### getUsers() Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-identity.md
Get all users seen on this device, ordered by most recently seen.
```java
List users = MParticle.getInstance().Identity().getUsers();
for (MParticleUser user : users) {
Log.d("TAG", "User: " + user.getId());
}
```
--------------------------------
### Complete Login Flow Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-identity.md
Example demonstrating a complete login flow, including setting user attributes.
```java
private void handleLogin(String email, String customerId) {
IdentityApiRequest request = IdentityApiRequest.withEmptyUser()
.email(email)
.customerId(customerId)
.build();
MParticle.getInstance().Identity().login(request)
.addSuccessListener(result -> {
MParticleUser user = result.getUser();
Log.d("APP", "Login successful: " + user.getId());
// Set user attributes
Map attrs = new HashMap<>();
attrs.put("plan", "premium");
attrs.put("onboarded", true);
user.setUserAttributes(attrs);
})
.addFailureListener(result -> {
Log.e("APP", "Login failed with code: " + result.getHttpCode());
});
}
```
--------------------------------
### SDK Initialization Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/README.md
Example of how to initialize the mParticle SDK in the Application class.
```java
package com.example.myapp;
import android.app.Application;
import com.mparticle.MParticle;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
MParticleOptions options = MParticleOptions.builder(this)
.credentials("REPLACE ME WITH KEY","REPLACE ME WITH SECRET")
.logLevel(MParticle.LogLevel.VERBOSE)
.identify(identifyRequest)
.identifyTask(
new BaseIdentityTask()
.addFailureListener(this)
.addSuccessListener(this)
)
.build();
MParticle.start(options);
}
}
```
--------------------------------
### GDPRConsent Builder Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/consent.md
Example of creating a GDPRConsent object using its builder.
```java
GDPRConsent consent = GDPRConsent.builder(true)
.consentDocument("privacy_policy_v2")
.location("San Francisco, CA")
.hardwareId("device_abc123")
.build();
```
--------------------------------
### Quick Start Commands
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/AGENTS.md
Common Gradle commands for building, testing, and validating the Android SDK.
```bash
./gradlew build
./gradlew test
./gradlew connectedAndroidTest
```
```bash
cd kits/urbanairship-kit && ./gradlew testRelease
```
--------------------------------
### Verifying all kits
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/ONBOARDING.md
Commands to verify both main and isolated kits after publishing to mavenLocal.
```bash
./gradlew -PisRelease=true publishReleaseLocal
./gradlew -PisRelease=true testRelease publishReleaseLocal -c settings-kits.gradle
cd kits/urbanairship-kit && ./gradlew -PisRelease=true testRelease
```
--------------------------------
### Get User Identities
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-identity.md
Example of retrieving all identities associated with the current user.
```java
MParticleUser user = MParticle.getInstance().Identity().getCurrentUser();
Map identities = user.getUserIdentities();
String email = identities.get(MParticle.IdentityType.Email);
```
--------------------------------
### Publishing Kits to Maven Local
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/ONBOARDING.md
Command to publish the selected kit to the local Maven repository.
```bash
./gradlew -PisRelease=true clean testRelease publishReleaseLocal -c settings-kits.gradle
```
--------------------------------
### getInstallReferrer
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-mparticle.md
Retrieves the current install referrer string.
```java
@Nullable
public String getInstallReferrer()
```
--------------------------------
### Install mParticle CLI tool
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/README.md
Installs the mParticle CLI tool using Gradle.
```bash
./gradlew mpInstall
```
--------------------------------
### MPEvent Constructor Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-events.md
Example of creating an MPEvent using the Builder pattern for a purchase.
```java
MPEvent event = new MPEvent.Builder("Purchase Complete")
.eventType(MParticle.EventType.Transaction)
.addCustomAttribute("orderId", "ORD-12345")
.addCustomAttribute("amount", "99.99")
.addCustomAttribute("currency", "USD")
.build();
MParticle.getInstance().logEvent(event);
```
--------------------------------
### toString() Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/consent.md
Get the JSON serialization of the consent state for storage or transmission.
```java
String serialized = consent.toString();
userPreferences.edit()
.putString("consent_state", serialized)
.apply();
```
--------------------------------
### getGDPRConsentState() Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/consent.md
Get all GDPR consent states by purpose and log the consent status for each purpose.
```java
ConsentState consent = user.getConsentState();
Map gdprConsents = consent.getGDPRConsentState();
for (String purpose : gdprConsents.keySet()) {
GDPRConsent consentInfo = gdprConsents.get(purpose);
boolean isConsented = consentInfo.isConsented();
Log.d("TAG", "Purpose: " + purpose + " - Consented: " + isConsented);
}
```
--------------------------------
### Initialization
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/quick-reference.md
Initializes the mParticle SDK with provided credentials and log level.
```java
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
MParticleOptions options = MParticleOptions.builder(this)
.credentials("YOUR_API_KEY", "YOUR_API_SECRET")
.logLevel(MParticle.LogLevel.DEBUG)
.build();
MParticle.start(options);
}
}
```
--------------------------------
### Error Handling
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/quick-reference.md
Example of how to handle potential errors during identity identification, including specific HTTP status codes.
```java
MParticle.getInstance().Identity().identify(request)
.addFailureListener(result -> {
int code = result.getHttpCode();
switch (code) {
case IdentityApi.BAD_REQUEST:
Log.e("TAG", "Invalid request");
break;
case IdentityApi.THROTTLE_ERROR:
Log.e("TAG", "Rate limited - retry later");
break;
case IdentityApi.SERVER_ERROR:
Log.e("TAG", "Server error - retry");
break;
case IdentityApi.UNKNOWN_ERROR:
Log.e("TAG", "Network error");
break;
}
});
```
--------------------------------
### setGDPRConsentState Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/consent.md
Example of how to set the GDPR consent state with a map of consents.
```java
Map allConsents = new HashMap<>();
allConsents.put("marketing", GDPRConsent.builder(true).build());
allConsents.put("analytics", GDPRConsent.builder(true).build());
allConsents.put("profiling", GDPRConsent.builder(false).build());
ConsentState consent = ConsentState.builder()
.setGDPRConsentState(allConsents)
.build();
```
--------------------------------
### CCPAConsent Builder Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/consent.md
Example of creating a CCPAConsent object using its builder.
```java
CCPAConsent ccpa = CCPAConsent.builder(true) // Opted out
.consentDocument("ccpa_notice_v1")
.location("California")
.build();
```
--------------------------------
### MParticle Get Instance
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-mparticle.md
Retrieve a reference to the current MParticle SDK instance. Must be called after `start()`.
```java
@Nullable
public static MParticle getInstance()
```
```java
MParticle mp = MParticle.getInstance();
if (mp != null) {
mp.logEvent(event);
}
```
--------------------------------
### MPEvent Builder with Duration Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-events.md
Example of setting the duration for an event in milliseconds.
```java
event = new MPEvent.Builder("VideoPlay")
.duration(120000) // 2 minutes
.build();
```
--------------------------------
### Login
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/quick-reference.md
Logs a user in with provided identity request, including success and failure listeners.
```java
MParticle.getInstance().Identity().login(request)
.addSuccessListener(result -> {
Log.d("TAG", "Login successful");
})
.addFailureListener(result -> {
Log.e("TAG", "Login failed");
});
```
--------------------------------
### MPEvent Builder with Custom Flags Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-events.md
Example of setting custom flags for third-party service integration.
```java
Map> flags = new HashMap<>();
flags.put("firebase_event_name", Arrays.asList("checkout_complete"));
flags.put("amplitude_event_type", Arrays.asList("revenue"));
event = new MPEvent.Builder("Checkout")
.customFlags(flags)
.build();
```
--------------------------------
### Play Install Referrer Library Dependency
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/README.md
Dependency for the Play Install Referrer Library to collect the Google Play Install referrer string.
```groovy
implementation 'com.android.installreferrer:installreferrer:1+'
```
--------------------------------
### Logout
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/quick-reference.md
Logs a user out, with callbacks for success and failure.
```java
MParticle.getInstance().Identity().logout()
.addSuccessListener(result -> {
Log.d("TAG", "Logout successful");
})
.addFailureListener(result -> {
Log.e("TAG", "Logout failed");
});
```
--------------------------------
### MPEvent Copy Constructor Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-events.md
Example of cloning an existing MPEvent using the copy constructor.
```java
MPEvent event1 = new MPEvent.Builder("ViewProduct").build();
MPEvent event2 = new MPEvent(event1); // Clone
```
--------------------------------
### Consent Activity Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/consent.md
An example of an Android Activity that collects user consent choices via checkboxes and sets the corresponding GDPR consent state using the mParticle SDK.
```java
public class ConsentActivity extends AppCompatActivity {
private CheckBox marketingCheckbox;
private CheckBox analyticsCheckbox;
private CheckBox profilingCheckbox;
private void handleConsentSubmit() {
MParticleUser user = MParticle.getInstance().Identity().getCurrentUser();
if (user == null) return;
ConsentState.Builder builder = ConsentState.builder();
// Build consent based on user selections
if (marketingCheckbox.isChecked()) {
builder.addGDPRConsentState("marketing",
GDPRConsent.builder(true)
.consentDocument("privacy_policy.pdf")
.build());
}
if (analyticsCheckbox.isChecked()) {
builder.addGDPRConsentState("analytics",
GDPRConsent.builder(true)
.consentDocument("privacy_policy.pdf")
.build());
}
if (profilingCheckbox.isChecked()) {
builder.addGDPRConsentState("profiling",
GDPRConsent.builder(true)
.consentDocument("privacy_policy.pdf")
.build());
}
ConsentState consent = builder.build();
user.setConsentState(consent);
// Navigate to next screen
finish();
}
}
```
--------------------------------
### Debug Logging
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/quick-reference.md
How to enable verbose debug logging for the mParticle SDK during development.
```java
// Enable verbose logging
MParticleOptions options = MParticleOptions.builder(this)
.credentials("key", "secret")
.logLevel(MParticle.LogLevel.DEBUG)
.build();
MParticle.start(options);
// View logs with: adb logcat | grep "mParticle"
```
--------------------------------
### setCCPAConsentState Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/consent.md
Example of how to set the CCPA consent state.
```java
CCPAConsent ccpaConsent = CCPAConsent.builder(false)
.build();
ConsentState consent = ConsentState.builder()
.setCCPAConsentState(ccpaConsent)
.build();
```
--------------------------------
### setInstallReferrer
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-mparticle.md
Manually sets the install referrer, overriding any automatically retrieved referrer from Google Play.
```java
public void setInstallReferrer(@Nullable String referrer)
```
--------------------------------
### MParticle.InstallType (Enum)
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/types.md
Installation source detection modes.
```java
public enum InstallType {
AutoDetect, // Auto-detect installation source
KnownInstaller, // App Store installation
Unknown // Side-loaded or other installation
}
```
--------------------------------
### Location Tracking
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/quick-reference.md
Configuration options for enabling and customizing location tracking.
```java
MParticleOptions.LocationTracking tracking = new MParticleOptions.LocationTracking();
tracking.enabled = true;
tracking.provider = LocationManager.NETWORK_PROVIDER;
tracking.minTime = 60000; // 1 minute
tracking.minDistance = 100; // 100 meters
MParticleOptions options = MParticleOptions.builder(this)
.credentials("key", "secret")
.locationTracking(tracking)
.build();
// Or enable at runtime
MParticle.getInstance().enableLocationTracking("gps", 60000, 100);
```
--------------------------------
### getImage() Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-messaging.md
Example of retrieving the image URL for a notification.
```java
String imageUrl = message.getImage();
// "https://cdn.example.com/promo.png"
```
--------------------------------
### Gradle Dependencies
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/quick-reference.md
Required Gradle dependencies for integrating the mParticle SDK and related services.
```gradle
dependencies {
// mParticle Core SDK
implementation "com.mparticle:android-core:5.79.0+"
// Firebase Cloud Messaging
implementation(platform("com.google.firebase:firebase-bom:29.1.0"))
implementation("com.google.firebase:firebase-messaging")
// Google Play Services Ads (for AAID)
implementation "com.google.android.gms:play-services-ads-identifier:18.0.1+"
// Play Install Referrer
implementation "com.android.installreferrer:installreferrer:1.+"
}
```
--------------------------------
### Bad Request (BAD_REQUEST - 400) Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/errors.md
Example of handling a bad request error (BAD_REQUEST).
```java
// Bad: Invalid email
IdentityApiRequest request = IdentityApiRequest.withEmptyUser()
.email("notanemail") // Invalid format
.build();
MParticle.getInstance().Identity().identify(request)
.addFailureListener(result -> {
if (result.getHttpCode() == IdentityApi.BAD_REQUEST) {
Log.e("TAG", "Invalid request: " + result.getResponseBody());
// e.g., "Invalid email address"
}
});
```
--------------------------------
### Network Error (UNKNOWN_ERROR) Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/errors.md
Example of handling a network or parsing error (UNKNOWN_ERROR).
```java
IdentityApiRequest request = IdentityApiRequest.withEmptyUser()
.email("user@example.com")
.build();
MParticle.getInstance().Identity().identify(request)
.addFailureListener(result -> {
if (result.getHttpCode() == IdentityApi.UNKNOWN_ERROR) {
Log.e("TAG", "Network/parsing error occurred");
Log.e("TAG", "Response: " + result.getResponseBody());
// Retry logic
scheduleRetry();
}
});
```
--------------------------------
### getCurrentUser() Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-identity.md
Get the current user profile.
```java
MParticleUser user = MParticle.getInstance().Identity().getCurrentUser();
if (user != null) {
long mpid = user.getId();
Map attrs = user.getUserAttributes();
}
```
--------------------------------
### Enable Push
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/quick-reference.md
Enables push notifications by providing the FCM sender ID.
```java
MParticle.getInstance().Messaging().enablePushNotifications("YOUR_FCM_SENDER_ID");
```
--------------------------------
### getCampaignId() Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-messaging.md
Example of retrieving the campaign ID associated with a push notification.
```java
String campaignId = message.getCampaignId();
// "camp_987654321"
```
--------------------------------
### Screen View
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/quick-reference.md
Logs a screen view event, optionally with associated data.
```java
MParticle.getInstance().logScreen("HomeScreen");
MParticle.getInstance().logScreen("ProductDetail",
Collections.singletonMap("product_id", "SKU-123"));
```
--------------------------------
### ConsentState.builder() Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/consent.md
Create a new ConsentState builder and set GDPR and CCPA consent states, then apply it to the current user.
```java
ConsentState consent = ConsentState.builder()
.addGDPRConsentState("marketing",
GDPRConsent.builder(true).build())
.setCCPAConsentState(
CCPAConsent.builder(true).build())
.build();
MParticleUser user = MParticle.getInstance().Identity().getCurrentUser();
user.setConsentState(consent);
```
--------------------------------
### MPEvent Builder with Custom Attributes Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-events.md
Example of setting custom attributes for an event using a Map.
```java
Map attrs = new HashMap<>();
attrs.put("product_id", "SKU-123");
attrs.put("price", 29.99);
attrs.put("quantity", 2);
event = new MPEvent.Builder("AddToCart")
.eventType(MParticle.EventType.Commerce)
.customAttributes(attrs)
.build();
```
--------------------------------
### Product Getters - getSku()
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-events.md
Get product SKU.
```java
public String getSku()
```
--------------------------------
### Simple Event
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/quick-reference.md
Logs a simple event with a type and custom attributes.
```java
MParticle.getInstance().logEvent(
new MPEvent.Builder("UserClicked")
.eventType(MParticle.EventType.Navigation)
.addCustomAttribute("button_name", "submit")
.build()
);
```
--------------------------------
### getUser(Long mpid) Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-identity.md
Get a user by their mParticle ID (MPID).
```java
MParticleUser user = MParticle.getInstance().Identity().getUser(123456789L);
```
--------------------------------
### Set User Attributes
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-identity.md
Example of setting multiple user attributes at once.
```java
Map attrs = new HashMap<>();
attrs.put("age", 25);
attrs.put("premium_member", true);
attrs.put("tags", Arrays.asList("vip", "early_adopter"));
MParticleUser user = MParticle.getInstance().Identity().getCurrentUser();
user.setUserAttributes(attrs);
```
--------------------------------
### SERVER_ERROR (5xx) Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/errors.md
Shows how to detect and handle server errors (5xx) by logging the error and scheduling a retry.
```java
Error: SERVER_ERROR (500+)
Trigger: mParticle server-side issue
```
```java
MParticle.getInstance().Identity().identify(request)
.addFailureListener(result -> {
int code = result.getHttpCode();
if (code >= 500 && code < 600) {
Log.e("TAG", "Server error (" + code + ") - temporary issue");
Log.e("TAG", "Response: " + result.getResponseBody());
// Retry with longer delay
scheduleRetryAfterDelay(5000); // 5 seconds
}
});
```
```java
private void identifyWithRetry(IdentityApiRequest request) {
MParticle.getInstance().Identity().identify(request)
.addFailureListener(result -> {
int code = result.getHttpCode();
if (code == IdentityApi.THROTTLE_ERROR || (code >= 500 && code < 600)) {
// Retryable error - schedule retry
scheduleRetry();
} else if (code == IdentityApi.BAD_REQUEST) {
// Non-retryable - validate request and fail
Log.e("TAG", "Bad request - check data: " + result.getResponseBody());
showErrorToUser("Invalid input data");
} else {
// Unknown error
Log.e("TAG", "Unknown error: " + code);
}
});
}
```
--------------------------------
### Publishing Core Modules to Local Maven Repository
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/ONBOARDING.md
Gradle commands to build and publish core modules to the local Maven repository.
```bash
./gradlew buildLocal
```
```bash
./gradlew -PisRelease=true clean publishReleaseLocal
```
--------------------------------
### Retry with Backoff
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/quick-reference.md
Implementation of a retry mechanism with exponential backoff for identity identification requests.
```java
private void identifyWithRetry(IdentityApiRequest request, int attempt) {
MParticle.getInstance().Identity().identify(request)
.addFailureListener(result -> {
if (result.getHttpCode() == 429 && attempt < 3) {
long delay = (long) Math.pow(2, attempt) * 1000;
new Handler(Looper.getMainLooper())
.postDelayed(() -> identifyWithRetry(request, attempt + 1), delay);
}
});
}
```
--------------------------------
### Get User Attributes (Asynchronous)
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-identity.md
Example of retrieving user attributes asynchronously with a callback.
```java
MParticleUser user = MParticle.getInstance().Identity().getCurrentUser();
user.getUserAttributes((attributes) -> {
String tier = (String) attributes.get("user_tier");
Log.d("TAG", "User tier: " + tier);
});
```
--------------------------------
### SDK Initialization
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/mparticle-android-sdk-reference.md
Example of how to initialize the mParticle SDK in your Application class.
```java
import com.mparticle.MParticle;
import com.mparticle.MParticleOptions;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
MParticleOptions options = MParticleOptions.builder(this)
.credentials("YOUR_API_KEY", "YOUR_API_SECRET")
.logLevel(MParticle.LogLevel.VERBOSE)
.build();
MParticle.start(options);
}
}
```
--------------------------------
### Product Getters - getQuantity()
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-events.md
Get quantity.
```java
public double getQuantity()
```
--------------------------------
### Deploy Kits
Source: https://github.com/mparticle/mparticle-android-sdk/wiki/Building
Uploads the SDK kits to the local Maven repository using a specific settings file.
```sh
./gradlew uploadArchives -c settings-kits.gradle
```
--------------------------------
### CommerceEvent getPromotionAction()
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-events.md
Get the promotion action.
```java
@Nullable
public String getPromotionAction()
```
--------------------------------
### Manifest Configuration: Application Class
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/README.md
Example of configuring the application class in the Android manifest to include MParticle initialization.
```xml
...
```
--------------------------------
### Commerce Event - Purchase
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/quick-reference.md
Logs a commerce purchase event with product details, transaction information, and currency.
```java
List products = Arrays.asList(
new Product.Builder("Widget", "SKU-123", 29.99, 1).build(),
new Product.Builder("Case", "SKU-456", 14.99, 2).build()
);
CommerceEvent purchase = new CommerceEvent.Builder(products, Product.PURCHASE)
.transactionAttributes(new TransactionAttributes()
.setId("ORDER-789")
.setRevenue(59.97)
.setTax(4.50)
.setShipping(5.00))
.currency("USD")
.build();
MParticle.getInstance().logEvent(purchase);
```
--------------------------------
### Get Current User
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/quick-reference.md
Retrieves the current mParticle user object and its associated data.
```java
MParticleUser user = MParticle.getInstance().Identity().getCurrentUser();
if (user != null) {
long mpid = user.getId();
Map attrs = user.getUserAttributes();
Map identities = user.getUserIdentities();
}
```
--------------------------------
### Building an isolated kit (urbanairship-kit)
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/ONBOARDING.md
Steps to build an isolated kit like urbanairship-kit from its own directory after publishing the core SDK to mavenLocal.
```bash
cd kits/urbanairship-kit
./gradlew testRelease publishReleaseLocal
```
--------------------------------
### getCCPAConsentState() Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/consent.md
Get the CCPA consent state and check if the user has explicitly opted out of sale.
```java
CCPAConsent ccpaConsent = consent.getCCPAConsentState();
if (ccpaConsent != null) {
boolean isSaleOptedOut = ccpaConsent.isExplicitlyOptedOut();
}
```
--------------------------------
### Product Getters - getCouponCode()
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-events.md
Get coupon code.
```java
public String getCouponCode()
```
--------------------------------
### THROTTLE_ERROR (429) Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/errors.md
Demonstrates how to handle a THROTTLE_ERROR by implementing exponential backoff.
```java
Error: THROTTLE_ERROR (429)
Trigger: Too many requests in short time
```
```java
// Bad: Rapid-fire requests
for (User user : users) {
IdentityApiRequest request = IdentityApiRequest.withEmptyUser()
.email(user.email)
.build();
MParticle.getInstance().Identity().identify(request)
.addFailureListener(result -> {
if (result.getHttpCode() == IdentityApi.THROTTLE_ERROR) {
Log.e("TAG", "Rate limited - backoff required");
}
});
}
```
```java
private int retryCount = 0;
private static final int MAX_RETRIES = 3;
private void identifyWithBackoff(String email) {
IdentityApiRequest request = IdentityApiRequest.withEmptyUser()
.email(email)
.build();
MParticle.getInstance().Identity().identify(request)
.addFailureListener(result -> {
if (result.getHttpCode() == IdentityApi.THROTTLE_ERROR && retryCount < MAX_RETRIES) {
retryCount++;
long delayMs = (long) Math.pow(2, retryCount) * 1000; // 2s, 4s, 8s
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(() -> identifyWithBackoff(email), delayMs);
}
});
}
```
--------------------------------
### login(IdentityApiRequest request) Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-identity.md
Send a login request. Establishes a new or existing user as the current user.
```java
IdentityApiRequest request = IdentityApiRequest.withEmptyUser()
.email("user@example.com")
.customerId("customer_123")
.build();
MParticle.getInstance().Identity().login(request)
.addSuccessListener((result) -> {
MParticleUser user = result.getUser();
Log.d("TAG", "Login successful for user: " + user.getId());
})
.addFailureListener((result) -> {
Log.e("TAG", "Login failed: " + result.getHttpCode());
});
```
--------------------------------
### Logging an Event
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/mparticle-android-sdk-reference.md
Example of how to access the SDK instance and log a standard event.
```java
MParticle mp = MParticle.getInstance();
mp.logEvent(new MPEvent.Builder("Purchase Complete")
.eventType(MParticle.EventType.Transaction)
.addCustomAttribute("value", "99.99")
.build());
```
--------------------------------
### Deploy the Core SDK
Source: https://github.com/mparticle/mparticle-android-sdk/wiki/Building
Uploads the core SDK to the local Maven repository.
```sh
./gradlew uploadArchives
```
--------------------------------
### Session Management
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/quick-reference.md
Retrieves the current session object and its properties like UUID, start time, and ID.
```java
Session session = MParticle.getInstance().getCurrentSession();
if (session != null) {
String uuid = session.getSessionUUID();
long startTime = session.getSessionStartTime();
long sessionId = session.getSessionID();
}
```
--------------------------------
### ConsentState.withConsentState(ConsentState source) Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/consent.md
Create a builder from an existing ConsentState, update a GDPR consent state, and build the new ConsentState.
```java
ConsentState currentConsent = user.getConsentState();
ConsentState updatedConsent = ConsentState.withConsentState(currentConsent)
.addGDPRConsentState("analytics",
GDPRConsent.builder(false).build())
.build();
user.setConsentState(updatedConsent);
```
--------------------------------
### Get User Attributes (Background Thread)
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-identity.md
Example of retrieving user attributes by querying the database on a background thread.
```java
new Thread(() -> {
MParticleUser user = MParticle.getInstance().Identity().getCurrentUser();
if (user != null) {
Map attrs = user.getUserAttributes();
String plan = (String) attrs.get("subscription_plan");
}
}).start();
```
--------------------------------
### Combined GDPR + CCPA
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/consent.md
Example demonstrating how to set both GDPR and CCPA consent states for a user simultaneously.
```java
private void updateAllConsent() {
MParticleUser user = MParticle.getInstance().Identity().getCurrentUser();
if (user == null) return;
long now = System.currentTimeMillis();
ConsentState consent = ConsentState.builder()
// GDPR purposes
.addGDPRConsentState("marketing",
GDPRConsent.builder(true)
.consentDocument("gdpr_v2")
.timestamp(now)
.build())
.addGDPRConsentState("analytics",
GDPRConsent.builder(true)
.consentDocument("gdpr_v2")
.timestamp(now)
.build())
// CCPA
.setCCPAConsentState(
CCPAConsent.builder(false) // Did NOT opt out
.consentDocument("ccpa_2024")
.location("California")
.timestamp(now)
.build())
.build();
user.setConsentState(consent);
}
```
--------------------------------
### addGDPRConsentState() Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/consent.md
Add or update GDPR consent for multiple purposes, including setting consent document and hardware ID for one purpose.
```java
GDPRConsent marketingConsent = GDPRConsent.builder(true)
.consentDocument("privacy_v2")
.location("New York")
.build();
ConsentState consent = ConsentState.builder()
.addGDPRConsentState("marketing", marketingConsent)
.addGDPRConsentState("analytics",
GDPRConsent.builder(false).build())
.addGDPRConsentState("profiling",
GDPRConsent.builder(true)
.consentDocument("terms_v3")
.hardwareId("device123")
.build())
.build();
```
--------------------------------
### Error Logging
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/quick-reference.md
Logs errors with optional context or logs exceptions.
```java
MParticle.getInstance().logError("Payment failed",
Collections.singletonMap("error_code", "timeout"));
MParticle.getInstance().logException(exception);
```
--------------------------------
### Core SDK Testing Commands
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/ONBOARDING.md
Gradle wrapper commands for running lint checks, unit tests, and instrumented tests for the mParticle Android SDK.
```bash
./gradlew lint
```
```bash
./gradlew test
```
```bash
./gradlew :android-core:cAT :android-kit-base:cAT --stacktrace
```
--------------------------------
### Identify User
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/quick-reference.md
Identifies a user with email and customer ID, providing success and failure listeners.
```java
IdentityApiRequest request = IdentityApiRequest.withEmptyUser()
.email("user@example.com")
.customerId("cust_123")
.build();
MParticle.getInstance().Identity().identify(request)
.addSuccessListener(result -> {
MParticleUser user = result.getUser();
Log.d("TAG", "Identified: " + user.getId());
})
.addFailureListener(result -> {
Log.e("TAG", "Identify failed: " + result.getHttpCode());
});
```
--------------------------------
### Check Current User
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/quick-reference.md
Utility function to retrieve the current mParticle user and log a warning if no user is found.
```java
private MParticleUser getOrWarnUser() {
MParticleUser user = MParticle.getInstance().Identity().getCurrentUser();
if (user == null) {
Log.w("TAG", "No current user");
return null;
}
return user;
}
```
--------------------------------
### Development Build Settings
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/configuration.md
Recommended mParticle SDK settings for development builds.
```java
.environment(MParticle.Environment.Development)
.logLevel(MParticle.LogLevel.DEBUG)
.uploadInterval(60)
.sessionTimeout(30)
```
--------------------------------
### Production Build Settings
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/configuration.md
Recommended mParticle SDK settings for production builds.
```java
.environment(MParticle.Environment.Production)
.logLevel(MParticle.LogLevel.ERROR)
.uploadInterval(600)
.sessionTimeout(120)
.uncaughtExceptionLogging(true)
.androidIdEnabled(true)
```
--------------------------------
### Manifest Configuration: Push Notification Service
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/README.md
Example of configuring the push notification service in the Android manifest.
```xml
```
--------------------------------
### Identify User
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/configuration.md
Set initial user identity for app startup.
```java
public Builder identify(@Nullable IdentityApiRequest request)
IdentityApiRequest identifyRequest = IdentityApiRequest.withEmptyUser()
.email("user@example.com")
.customerId("user_123")
.build();
.identify(identifyRequest)
```
--------------------------------
### Product Builder build()
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-events.md
Build and return the Product.
```java
public Product build()
```
--------------------------------
### MParticleOptions Builder
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/configuration.md
All SDK configuration is provided via MParticleOptions.Builder. Create an instance with MParticleOptions.builder(context).
```java
MParticleOptions options = MParticleOptions.builder(context)
.credentials("YOUR_API_KEY", "YOUR_API_SECRET")
.build();
```
--------------------------------
### Deploy Core and Kits to local Maven repository
Source: https://github.com/mparticle/mparticle-android-sdk/wiki/Kit-Development
Commands to upload the core SDK and the kits to a local Maven repository for testing.
```bash
./gradlew uploadArchives # deploy the core
./gradlew uploadArchives -c settings-kits.gradle # deploy the kits
```
--------------------------------
### getAllExtras() Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-messaging.md
Example of retrieving all custom extra fields from a ProviderCloudMessage.
```java
Map extras = message.getAllExtras();
for (String key : extras.keySet()) {
String value = extras.get(key);
}
```
--------------------------------
### MParticle Initialization
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-mparticle.md
Start the mParticle SDK and begin tracking a user session. This method must be called prior to `getInstance()`, typically in your Application class's `onCreate()` method.
```java
public static void start(@NonNull MParticleOptions options)
```
```java
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
MParticleOptions options = MParticleOptions.builder(this)
.credentials("YOUR_API_KEY", "YOUR_API_SECRET")
.environment(MParticle.Environment.Production)
.logLevel(MParticle.LogLevel.DEBUG)
.build();
MParticle.start(options);
}
}
```
--------------------------------
### getRedirectUrl() Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-messaging.md
Example of retrieving the redirect URL from a ProviderCloudMessage object.
```java
String deepLink = message.getRedirectUrl();
// "https://myapp.com/orders/ORD-123"
// or "myapp://orders/ORD-123"
```
--------------------------------
### MPEvent Builder to Exclude Upload Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-events.md
Example of creating an event that is logged to kits but not uploaded to mParticle.
```java
// Log to kits only, not to mParticle
event = new MPEvent.Builder("InternalDebugEvent")
.shouldUploadEvent(false)
.build();
```
--------------------------------
### Product Builder couponCode()
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-events.md
Set coupon/promotion code.
```java
public Builder couponCode(@Nullable String coupon)
```
--------------------------------
### MPEvent Builder with Single Custom Attribute Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-events.md
Example of adding a single custom attribute to an event.
```java
event = new MPEvent.Builder("Search")
.eventType(MParticle.EventType.Search)
.addCustomAttribute("query", "blue widgets")
.addCustomAttribute("result_count", 42)
.build();
```
--------------------------------
### Clone SDK and Kit Submodules
Source: https://github.com/mparticle/mparticle-android-sdk/wiki/Building
Clones the mParticle Android SDK repository and its submodules. It also provides instructions to switch to a specific branch, SHA, or tag.
```sh
git clone --recursive git@github.com:mParticle/mparticle-android-sdk.git
cd mparticle-android-sdk
# if there's a particular branch, SHA, or tag that you'd like to test, switch to it now
```
--------------------------------
### getExtra(String key) Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-messaging.md
Example of retrieving custom extra fields from a ProviderCloudMessage by key.
```java
String productId = message.getExtra("product_id");
String promo = message.getExtra("promotion_code");
```
--------------------------------
### Environment Configuration
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/configuration.md
Set whether app is in Development or Production environment.
```java
.environment(MParticle.Environment.Production)
```
--------------------------------
### Custom Push Handler Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-messaging.md
Example of a custom receiver to handle push notification received and tapped events, including logging analytics and navigating to a URL.
```java
public class CustomPushReceiver extends PushAnalyticsReceiver {
@Override
public boolean onNotificationReceived(ProviderCloudMessage message) {
// Log event for analytics
Map attrs = new HashMap<>();
attrs.put("campaign_id", message.getCampaignId());
attrs.put("notification_title", message.getTitle());
MParticle.getInstance().logEvent(
new MPEvent.Builder("push_notification_received")
.eventType(MParticle.EventType.Other)
.customAttributes(attrs)
.build()
);
// Display notification manually or suppress
return false; // Let mParticle display
}
@Override
public boolean onNotificationTapped(ProviderCloudMessage message) {
String redirectUrl = message.getRedirectUrl();
if (redirectUrl != null && !redirectUrl.isEmpty()) {
// Log click event
MParticle.getInstance().logEvent(
new MPEvent.Builder("push_notification_clicked")
.eventType(MParticle.EventType.Navigation)
.addCustomAttribute("url", redirectUrl)
.build()
);
// Navigate to URL
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(redirectUrl));
getContext().startActivity(intent);
return true;
}
return false;
}
}
```
--------------------------------
### Identify Task
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/configuration.md
Set task to be executed after identify operation completes at startup.
```java
public Builder identifyTask(@Nullable BaseIdentityTask task)
.identifyTask(new BaseIdentityTask()
.addSuccessListener(result -> {
Log.d("TAG", "Initial identify succeeded");
})
.addFailureListener(result -> {
Log.e("TAG", "Initial identify failed");
}))
```
--------------------------------
### onNotificationTapped Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-messaging.md
Example implementation of the onNotificationTapped method to handle custom tap actions, such as opening a URL in a browser. It returns true if the action is handled, false otherwise.
```java
@Override
public boolean onNotificationTapped(ProviderCloudMessage message) {
String actionUrl = message.getRedirectUrl();
if (actionUrl != null && !actionUrl.isEmpty()) {
// Custom handling - open URL in browser
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(actionUrl));
startActivity(intent);
return true; // We handled it
}
return false; // Let default handling occur
}
```
--------------------------------
### onNotificationReceived Example
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-messaging.md
Example implementation of the onNotificationReceived method to log a custom event when a push notification is received. It returns false to allow mParticle to handle the default display.
```java
@Override
public boolean onNotificationReceived(ProviderCloudMessage message) {
// Log custom event
MParticle.getInstance().logEvent(
new MPEvent.Builder("push_received")
.addCustomAttribute("campaign_id", message.getCampaignId())
.build()
);
// Let mParticle display it
return false;
}
```
--------------------------------
### getTransactionAttributes()
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-events.md
Get transaction details.
```java
public TransactionAttributes getTransactionAttributes()
```
--------------------------------
### Product Getters - getVariant()
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-events.md
Get variant.
```java
public String getVariant()
```
--------------------------------
### Location Tracking Configuration
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/configuration.md
Enable location tracking with provider and frequency settings.
```java
MParticleOptions.LocationTracking tracking = new MParticleOptions.LocationTracking();
tracking.enabled = true;
tracking.provider = LocationManager.GPS_PROVIDER;
tracking.minTime = 60000; // 1 minute
tracking.minDistance = 100; // 100 meters
.locationTracking(tracking)
```
--------------------------------
### Product Getters - getBrand()
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-events.md
Get brand.
```java
public String getBrand()
```
--------------------------------
### Add local Maven repository to app's build.gradle
Source: https://github.com/mparticle/mparticle-android-sdk/wiki/Building
Configures the app's build.gradle script to pull artifacts from a local Maven repository.
```groovy
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.2'
}
}
allprojects {
repositories {
mavenLocal() //ADD THIS, ABOVE ALL OTHER REPOSITORIES
mavenCentral()
}
}
```
--------------------------------
### Product Getters - getCategory()
Source: https://github.com/mparticle/mparticle-android-sdk/blob/main/_autodocs/api-reference-events.md
Get category.
```java
public String getCategory()
```