### Add Dependency to build.gradle
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Add this dependency to your build.gradle file for one-step installation.
```gradle
dependencies {
implementation 'cat.ereza:customactivityoncrash:2.4.0'
}
```
--------------------------------
### Force App Crash Example
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Use this code to intentionally cause an app crash for testing purposes.
```java
throw new RuntimeException("Boom!");
```
--------------------------------
### Retrieve Library Config from Intent
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Get the `CaocConfig` instance active during the crash, serialized in the error activity's launch Intent. Essential for calling `restartApplication()` or `closeApplication()`.
```java
// Inside your CustomErrorActivity.onCreate():
final CaocConfig config = CustomActivityOnCrash.getConfigFromIntent(getIntent());
if (config == null) {
// Should never happen in practice; defensive guard
finish();
return;
}
Button actionButton = findViewById(R.id.btn_action);
if (config.isShowRestartButton() && config.getRestartActivityClass() != null) {
actionButton.setText("Restart App");
actionButton.setOnClickListener(v ->
CustomActivityOnCrash.restartApplication(CustomErrorActivity.this, config)
);
} else {
actionButton.setText("Close App");
actionButton.setOnClickListener(v ->
CustomActivityOnCrash.closeApplication(CustomErrorActivity.this, config)
);
}
```
--------------------------------
### Get Library Configuration from Intent
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Retrieve the library's configuration at the time of the crash from the intent. This is used to call other methods like restarting the application.
```java
CustomActivityOnCrash.getConfigFromIntent(getIntent());
```
--------------------------------
### Retrieve Activity Navigation Log from Intent
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Get the timestamped activity lifecycle log as a string. Requires `.trackActivities(true)` to be set in `CaocConfig.Builder`. Useful for reconstructing user actions before a crash.
```java
// Requires: .trackActivities(true) in CaocConfig.Builder
String activityLog = CustomActivityOnCrash.getActivityLogFromIntent(getIntent());
// activityLog:
// "2024-03-20 14:21:50: SplashActivity created\n"
// "2024-03-20 14:21:52: SplashActivity destroyed\n"
// "2024-03-20 14:21:53: MainActivity created\n"
// "2024-03-20 14:22:01: SettingsActivity created\n"
// "2024-03-20 14:22:04: SettingsActivity resumed\n"
if (activityLog != null) {
Log.d("CAOC", "Activity log:\n" + activityLog);
} else {
Log.d("CAOC", "Activity tracking was not enabled");
}
```
--------------------------------
### Get All Error Details from Intent
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Retrieve all available error details, including stack trace, activity log, and custom crash data, from the intent. This is useful for displaying detailed error information.
```java
CustomActivityOnCrash.getAllErrorDetailsFromIntent(getIntent());
```
--------------------------------
### Retrieve Stack Trace from Intent
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Use this method inside your custom error activity to get the full stack trace string passed via the launch Intent. It's useful for displaying or transmitting crash information.
```java
String stackTrace = CustomActivityOnCrash.getStackTraceFromIntent(getIntent());
// stackTrace: "java.lang.RuntimeException: Boom!\n at com.example.MainActivity..."
TextView tvStackTrace = findViewById(R.id.tv_stack_trace);
tvStackTrace.setText(stackTrace != null ? stackTrace : "No stack trace available");
```
--------------------------------
### Get Activity Log from Intent
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Retrieve the activity log as a string if `trackActivities` was enabled. Returns null otherwise. This helps in debugging by providing a history of activities.
```java
CustomActivityOnCrash.getActivityLogFromIntent(getIntent());
```
--------------------------------
### Get Stack Trace from Intent
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Extract the stack trace string that caused the crash from the intent. This method is useful when you only need the stack trace.
```java
CustomActivityOnCrash.getStackTraceFromIntent(getIntent());
```
--------------------------------
### Get Custom Crash Data from Intent
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Retrieve custom crash data collected via `CustomCrashDataCollector` if it was enabled. Returns null otherwise.
```java
CustomActivityOnCrash.getCustomCrashDataFromIntent(getIntent());
```
--------------------------------
### Advanced Configuration in Application Class
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Configure the library's behavior within your Application class's onCreate method. Recommended for early availability.
```java
@Override
public void onCreate() {
super.onCreate();
CaocConfig.Builder.create()
.backgroundMode(CaocConfig.BACKGROUND_MODE_SILENT) //default: CaocConfig.BACKGROUND_MODE_SHOW_CUSTOM
.enabled(false) //default: true
.showErrorDetails(false) //default: true
.showRestartButton(false) //default: true
.logErrorOnRestart(false) //default: true
.trackActivities(true) //default: false
.minTimeBetweenCrashesMs(2000) //default: 3000
.errorDrawable(R.drawable.ic_custom_drawable) //default: bug image
.restartActivity(YourCustomActivity.class) //default: null (your app's launch activity)
.errorActivity(YourCustomErrorActivity.class) //default: null (default error activity)
.eventListener(new YourCustomEventListener()) //default: null
.customCrashDataCollector(new YourCustomCrashDataCollector()) //default: null
.apply();
//If you use Firebase Crashlytics or ACRA, please initialize them here as explained above.
}
```
--------------------------------
### Restart Application with CustomActivityOnCrash.restartApplication()
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Kills the current process and relaunches the app from the configured restart activity. Must be called instead of manually calling startActivity() to avoid multiprocess issues.
```java
// Inside your CustomErrorActivity:
Button restartBtn = findViewById(R.id.btn_restart);
final CaocConfig config = CustomActivityOnCrash.getConfigFromIntent(getIntent());
restartBtn.setOnClickListener(v -> {
// Restarts to config.getRestartActivityClass() (or the app's default launch activity)
CustomActivityOnCrash.restartApplication(CustomErrorActivity.this, config);
});
```
--------------------------------
### CustomActivityOnCrash.restartApplication()
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Kills the current process and relaunches the app from the configured restart activity. This method must be called instead of manually calling startActivity() to prevent multiprocess issues.
```APIDOC
## CustomActivityOnCrash.restartApplication()
### Description
Kills the current process and relaunches the app from the configured restart activity. Must be called instead of manually calling `startActivity()`, otherwise multiple `Application` instances will exist simultaneously causing multiprocess issues.
### Method Signature
`CustomActivityOnCrash.restartApplication(Context context, CaocConfig config)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```java
// Inside your CustomErrorActivity:
Button restartBtn = findViewById(R.id.btn_restart);
final CaocConfig config = CustomActivityOnCrash.getConfigFromIntent(getIntent());
restartBtn.setOnClickListener(v -> {
// Restarts to config.getRestartActivityClass() (or the app's default launch activity)
CustomActivityOnCrash.restartApplication(CustomErrorActivity.this, config);
});
```
### Response
None (This method performs an action and does not return a value.)
### Error Handling
None explicitly documented.
```
--------------------------------
### Read Current Crash Configuration
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Use CaocConfig.Builder.get() to retrieve the current configuration snapshot without applying any changes. This is useful for inspecting live settings.
```java
CaocConfig currentConfig = CaocConfig.Builder.create().get();
boolean isEnabled = currentConfig.isEnabled();
boolean tracksActivities = currentConfig.isTrackActivities();
int bgMode = currentConfig.getBackgroundMode();
int minCrashMs = currentConfig.getMinTimeBetweenCrashesMs();
Log.d("Config", "CAOC enabled=" + isEnabled + ", bgMode=" + bgMode);
```
--------------------------------
### Restart Application with Custom Intent
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Similar to `restartApplication`, but allows specifying a custom intent to launch upon restart. Ensures proper app restart and avoids multiprocess issues.
```java
CustomActivityOnCrash.restartApplicationWithIntent(activity, intent, config);
```
--------------------------------
### Configure Crash Handling Behavior with CaocConfig.Builder
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Use CaocConfig.Builder in your Application.onCreate() before other crash handlers to configure crash handling. Ensure static or top-level classes for event listeners and data collectors.
```java
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
CaocConfig.Builder.create()
.backgroundMode(CaocConfig.BACKGROUND_MODE_SHOW_CUSTOM)
.enabled(BuildConfig.DEBUG ? false : true)
.showErrorDetails(true)
.showRestartButton(true)
.logErrorOnRestart(true)
.trackActivities(true)
.minTimeBetweenCrashesMs(2000)
.errorDrawable(R.drawable.ic_error_custom)
.restartActivity(MainActivity.class)
.errorActivity(MyCustomErrorActivity.class)
.eventListener(new MyEventListener())
.customCrashDataCollector(new MyCrashDataCollector())
.apply();
// IMPORTANT: If using Firebase Crashlytics, initialize it AFTER this call:
// FirebaseApp.initializeApp(this);
// IMPORTANT: If using ACRA, initialize it here (not in attachBaseContext) with
// alsoReportToAndroidFramework = true
}
private static class MyEventListener implements CustomActivityOnCrash.EventListener {
@Override
public void onLaunchErrorActivity() {
FirebaseAnalytics.getInstance(MyApplication.instance).logEvent("app_crash", null);
}
@Override
public void onRestartAppFromErrorActivity() {
}
@Override
public void onCloseAppFromErrorActivity() {
}
}
private static class MyCrashDataCollector implements CustomActivityOnCrash.CustomCrashDataCollector {
@Override
public String onCrash() {
return "User ID: " + MyApp.getCurrentUserId()
+ "\nSession ID: " + MyApp.getSessionId()
+ "\nNetwork: " + MyApp.getNetworkType();
}
}
}
```
--------------------------------
### CustomActivityOnCrash.closeApplication()
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Gracefully closes the application and kills the current process. This method must be called instead of `finish()` alone to avoid multiprocess issues.
```APIDOC
## CustomActivityOnCrash.closeApplication()
### Description
Gracefully closes the app and kills the current process. Must be called instead of `finish()` alone to avoid multiprocess issues with lingering `Application` instances.
### Method Signature
`CustomActivityOnCrash.closeApplication(Context context, CaocConfig config)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```java
// Inside your CustomErrorActivity:
Button closeBtn = findViewById(R.id.btn_close);
final CaocConfig config = CustomActivityOnCrash.getConfigFromIntent(getIntent());
closeBtn.setOnClickListener(v -> {
// Fires config.getEventListener().onCloseAppFromErrorActivity() if set, then terminates
CustomActivityOnCrash.closeApplication(CustomErrorActivity.this, config);
});
```
### Response
None (This method performs an action and does not return a value.)
### Error Handling
None explicitly documented.
```
--------------------------------
### Restart Application with CustomActivityOnCrash.restartApplicationWithIntent()
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Restarts the app using a fully custom Intent, allowing for extra data passing or navigation to a specific screen after recovery. This is an alternative to restartApplication() for more control over the restart process.
```java
// Restart the app and navigate directly to the home screen after crash recovery
Button restartBtn = findViewById(R.id.btn_restart);
final CaocConfig config = CustomActivityOnCrash.getConfigFromIntent(getIntent());
restartBtn.setOnClickListener(v -> {
Intent restartIntent = new Intent(CustomErrorActivity.this, HomeActivity.class);
restartIntent.putExtra("from_crash", true);
restartIntent.putExtra("crash_timestamp", System.currentTimeMillis());
CustomActivityOnCrash.restartApplicationWithIntent(
CustomErrorActivity.this,
restartIntent,
config
);
});
```
--------------------------------
### CustomActivityOnCrash.getConfigFromIntent()
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Retrieves the `CaocConfig` instance that was active when the crash occurred. This configuration object is serialized into the error activity's launch Intent and is required for actions like restarting or closing the application.
```APIDOC
## CustomActivityOnCrash.getConfigFromIntent()
### Description
Returns the `CaocConfig` instance that was active when the crash occurred, serialized into the error activity's launch `Intent`. Required to call `restartApplication()` or `closeApplication()`. Also re-logs the stack trace if `logErrorOnRestart` is `true`.
### Method Signature
```java
static CaocConfig getConfigFromIntent(Intent intent)
```
### Parameters
* **intent** (Intent) - The launch Intent of the error activity.
### Returns
* (CaocConfig) - The configuration object used when the crash occurred, or null if it could not be retrieved.
### Example
```java
// Inside your CustomErrorActivity.onCreate():
final CaocConfig config = CustomActivityOnCrash.getConfigFromIntent(getIntent());
if (config == null) {
// Should never happen in practice; defensive guard
finish();
return;
}
Button actionButton = findViewById(R.id.btn_action);
if (config.isShowRestartButton() && config.getRestartActivityClass() != null) {
actionButton.setText("Restart App");
actionButton.setOnClickListener(v ->
CustomActivityOnCrash.restartApplication(CustomErrorActivity.this, config)
);
} else {
actionButton.setText("Close App");
actionButton.setOnClickListener(v ->
CustomActivityOnCrash.closeApplication(CustomErrorActivity.this, config)
);
}
```
```
--------------------------------
### Specify restart activity
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Sets the activity to be launched when the user presses the restart button. If not set, it falls back to an activity with the `cat.ereza.customactivityoncrash.RESTART` intent filter or the default launchable activity. If none is found, the button becomes 'Close app'.
```java
restartActivity(Class extends Activity>);
```
```xml
```
--------------------------------
### restartActivity
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Specifies the activity to be launched when the user presses the restart button on the error activity. If not set, the library attempts to find a suitable activity or defaults to closing the app.
```APIDOC
## restartActivity
### Description
This method sets the activity that must be launched by the error activity when the user presses the button to restart the app. If you don't set it (or set it to null), the library will use the first activity on your manifest that has an intent-filter with action `cat.ereza.customactivityoncrash.RESTART`, and if there is none, the default launchable activity on your app. If no launchable activity can be found and you didn't specify any, the "restart app" button will become a "close app" button, even if `showRestartButton` is set to `true`.
As noted, you can also use the following intent-filter to specify the restart activity:
```xml
```
### Method
`restartActivity(Class extends Activity>)`
```
--------------------------------
### Restart Application
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Kills the current process and restarts the app. You MUST call this method to avoid multiprocess issues. It uses `startActivity()` with the provided intent.
```java
CustomActivityOnCrash.restartApplication(activity, config);
```
--------------------------------
### launchWhenInBackground
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Defines if the error activity should be launched when the app crashes while in the background. Supports three modes: SHOW_CUSTOM, CRASH, and SILENT.
```APIDOC
## launchWhenInBackground
### Description
Defines if the error activity should be launched when the app crashes while in the background.
There are three modes:
- `CaocConfig.BACKGROUND_MODE_SHOW_CUSTOM`: launch the error activity even if the app is in background.
- `CaocConfig.BACKGROUND_MODE_CRASH`: launch the default system error when the app is in background.
- `CaocConfig.BACKGROUND_MODE_SILENT`: crash silently when the app is in background.
### Method
`launchWhenInBackground(int)`
### Default Value
`CaocConfig.BACKGROUND_MODE_SHOW_CUSTOM`
```
--------------------------------
### Configure background crash behavior
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Defines if the error activity should launch when the app crashes in the background. Options include showing the custom activity, showing the system error, or crashing silently. Defaults to showing the custom activity.
```java
launchWhenInBackground(int);
```
--------------------------------
### Close Application with CustomActivityOnCrash.closeApplication()
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Gracefully closes the app and kills the current process. Must be called instead of finish() alone to prevent multiprocess issues with lingering Application instances.
```java
// Inside your CustomErrorActivity:
Button closeBtn = findViewById(R.id.btn_close);
final CaocConfig config = CustomActivityOnCrash.getConfigFromIntent(getIntent());
closeBtn.setOnClickListener(v -> {
// Fires config.getEventListener().onCloseAppFromErrorActivity() if set, then terminates
CustomActivityOnCrash.closeApplication(CustomErrorActivity.this, config);
});
```
--------------------------------
### CustomActivityOnCrash.getAllErrorDetailsFromIntent()
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Retrieves a formatted multi-line string containing the full error report, including app version, build date, device model, OS version, stack trace, activity log, and custom crash data. Suitable for display or transmission to a bug tracker.
```APIDOC
## CustomActivityOnCrash.getAllErrorDetailsFromIntent()
### Description
Returns a formatted multi-line string containing the app version, build date, current date, device model, OS version, full stack trace, activity log (if `trackActivities` was enabled), and custom crash data (if a `CustomCrashDataCollector` was set). Suitable for display or transmission to a bug tracker.
### Method Signature
```java
static String getAllErrorDetailsFromIntent(Context context, Intent intent)
```
### Parameters
* **context** (Context) - The context of the error activity.
* **intent** (Intent) - The launch Intent of the error activity.
### Returns
* (String) - A formatted string containing all error details, or an empty string if no details are available.
### Example
```java
// Inside your CustomErrorActivity.onCreate():
String fullReport = CustomActivityOnCrash.getAllErrorDetailsFromIntent(this, getIntent());
/*
Build version: 2.1.0
Build date: 2024-03-15 10:30:00
Current date: 2024-03-20 14:22:05
Device: Google Pixel 6
OS version: Android 13 (SDK 33)
Stack trace:
java.lang.RuntimeException: Boom!
at com.example.app.MainActivity.onClick(MainActivity.java:42)
...
User actions:
2024-03-20 14:21:55: MainActivity created
2024-03-20 14:22:00: SettingsActivity created
...
Additional data:
User ID: 12345
Session ID: abc-xyz
*/
// Show in a dialog:
new AlertDialog.Builder(this)
.setTitle("Error Details")
.setMessage(fullReport)
.setPositiveButton("Close", null)
.setNeutralButton("Copy", (d, w) -> {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(ClipData.newPlainText("Error", fullReport));
})
.show();
```
```
--------------------------------
### Custom Error Activity Implementation
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Implement a custom error activity to display crash details, handle restart and close actions, and send crash reports. Retrieve configuration and crash data using static methods from CustomActivityOnCrash.
```java
// error/MyCustomErrorActivity.java
public class MyCustomErrorActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_custom_error);
final CaocConfig config = CustomActivityOnCrash.getConfigFromIntent(getIntent());
if (config == null) { finish(); return; }
// Retrieve all crash data
String stackTrace = CustomActivityOnCrash.getStackTraceFromIntent(getIntent());
String activityLog = CustomActivityOnCrash.getActivityLogFromIntent(getIntent());
String customData = CustomActivityOnCrash.getCustomCrashDataFromIntent(getIntent());
String fullReport = CustomActivityOnCrash.getAllErrorDetailsFromIntent(this, getIntent());
// Display stack trace
TextView tvError = findViewById(R.id.tv_error);
tvError.setText(stackTrace);
// Send report to server asynchronously (do not block UI)
new Thread(() -> sendReport(fullReport)).start();
// Restart button
Button btnRestart = findViewById(R.id.btn_restart);
if (config.isShowRestartButton() && config.getRestartActivityClass() != null) {
btnRestart.setVisibility(View.VISIBLE);
btnRestart.setOnClickListener(v ->
CustomActivityOnCrash.restartApplication(this, config));
} else {
btnRestart.setVisibility(View.GONE);
}
// Close button
Button btnClose = findViewById(R.id.btn_close);
btnClose.setOnClickListener(v ->
CustomActivityOnCrash.closeApplication(this, config));
}
private void sendReport(String report) {
// Example: HTTP POST to your crash reporting endpoint
try {
URL url = new URL("https://crashes.example.com/report");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.getOutputStream().write(report.getBytes("UTF-8"));
conn.getResponseCode(); // fire and forget
conn.disconnect();
} catch (Exception e) {
Log.e("MyCustomErrorActivity", "Failed to send crash report", e);
}
}
}
```
--------------------------------
### CustomActivityOnCrash.restartApplicationWithIntent()
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Restarts the application with a custom Intent, allowing for passing extra data or navigating to a specific screen after recovery.
```APIDOC
## CustomActivityOnCrash.restartApplicationWithIntent()
### Description
Same as `restartApplication()` but accepts a fully custom `Intent`, allowing you to pass extra data to the restarted activity or navigate to a specific screen after recovery.
### Method Signature
`CustomActivityOnCrash.restartApplicationWithIntent(Context context, Intent intent, CaocConfig config)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```java
// Restart the app and navigate directly to the home screen after crash recovery
Button restartBtn = findViewById(R.id.btn_restart);
final CaocConfig config = CustomActivityOnCrash.getConfigFromIntent(getIntent());
restartBtn.setOnClickListener(v -> {
Intent restartIntent = new Intent(CustomErrorActivity.this, HomeActivity.class);
restartIntent.putExtra("from_crash", true);
restartIntent.putExtra("crash_timestamp", System.currentTimeMillis());
CustomActivityOnCrash.restartApplicationWithIntent(
CustomErrorActivity.this,
restartIntent,
config
);
});
```
### Response
None (This method performs an action and does not return a value.)
### Error Handling
None explicitly documented.
```
--------------------------------
### Implementing a Completely Custom Error Activity
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
This section provides methods to retrieve crash information and manage application restart/close within a custom error activity.
```APIDOC
## Implementing a Completely Custom Error Activity
### Retrieving Crash Information
Use the following static methods from `CustomActivityOnCrash` to get details about the crash from the intent:
- `getAllErrorDetailsFromIntent(Intent intent)`: Returns all error details including stack trace, activity log, and custom crash data as a string.
- `getStackTraceFromIntent(Intent intent)`: Returns the stack trace that caused the error as a string.
- `getActivityLogFromIntent(Intent intent)`: Returns the activity log as a string if `trackActivities` was enabled, `null` otherwise.
- `getCustomCrashDataFromIntent(Intent intent)`: Returns custom crash data if `customCrashDataCollector` was enabled, `null` otherwise.
- `getConfigFromIntent(Intent intent)`: Returns the library's configuration at the time of the crash.
### Application Control
Use these methods to manage the application's lifecycle:
- `restartApplication(Activity activity, Config config)`: Kills the current process and restarts the app. You **MUST** call this to avoid multiprocess issues.
- `restartApplicationWithIntent(Activity activity, Intent intent, Config config)`: Similar to `restartApplication`, but allows specifying a custom intent for restarting.
- `closeApplication(Activity activity, EventListener eventListener)`: Closes the app and kills the current process. You **MUST** call this to avoid multiprocess issues.
```
--------------------------------
### trackActivities
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Configures whether the library should track visited activities and their lifecycle calls, which are then displayed in the error details.
```APIDOC
## trackActivities
### Description
This method defines if the library must track the activities the user visits and their lifecycle calls. This is displayed on the default error activity as part of the error details.
### Method
`trackActivities(boolean)`
### Default Value
`false`
```
--------------------------------
### Customizing Default Error Activity
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
This section explains how to override resources to customize the appearance and behavior of the default error activity.
```APIDOC
## Customizing Default Error Activity
### Theme
Override the `android:theme` attribute in your `AndroidManifest.xml` for the `DefaultErrorActivity` to specify a custom theme.
```xml
```
### Image
Change the default bug image by using the `errorDrawable(int)` method or by providing a `customactivityoncrash_error_image` drawable.
### Strings
Override the default strings for the error activity by redeclaring them in your `res/values/strings.xml`.
```xml
An unexpected error occurred.\nSorry for the inconvenience.
Restart app
Close app
Error details
Error details
Close
Copy to clipboard
Copied to clipboard
Error information
```
```
--------------------------------
### Show restart button
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Determines whether the error activity displays a 'Restart app' or 'Close app' button. If false, the button closes the app. Note: If no launch activity is found, it defaults to 'Close app' even if this is true. Defaults to true.
```java
showRestartButton(boolean);
```
--------------------------------
### Retrieve Full Error Report from Intent
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Obtain a formatted multi-line string containing comprehensive crash details, including app version, device info, stack trace, activity log, and custom data. Suitable for bug trackers.
```java
String fullReport = CustomActivityOnCrash.getAllErrorDetailsFromIntent(this, getIntent());
/*
Build version: 2.1.0
Build date: 2024-03-15 10:30:00
Current date: 2024-03-20 14:22:05
Device: Google Pixel 6
OS version: Android 13 (SDK 33)
Stack trace:
java.lang.RuntimeException: Boom!
at com.example.app.MainActivity.onClick(MainActivity.java:42)
...
User actions:
2024-03-20 14:21:55: MainActivity created
2024-03-20 14:22:00: SettingsActivity created
...
Additional data:
User ID: 12345
Session ID: abc-xyz
*/
// Show in a dialog:
new AlertDialog.Builder(this)
.setTitle("Error Details")
.setMessage(fullReport)
.setPositiveButton("Close", null)
.setNeutralButton("Copy", (d, w) -> {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(ClipData.newPlainText("Error", fullReport));
})
.show();
```
--------------------------------
### showErrorDetails
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Determines whether the error activity displays a button to show error details (stack trace). Setting to false hides this button.
```APIDOC
## showErrorDetails
### Description
This method defines if the error activity must show a button with error details. If you set it to `false`, the button on the default error activity will disappear, thus disabling the user from seeing the stack trace.
### Method
`showErrorDetails(boolean)`
### Default Value
`true`
```
--------------------------------
### CustomActivityOnCrash.getStackTraceFromIntent()
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Retrieves the full stack trace string passed to the error activity via its launch Intent. This is useful for displaying or transmitting crash information within a custom error activity.
```APIDOC
## CustomActivityOnCrash.getStackTraceFromIntent()
### Description
Returns the full stack trace string passed to the error activity via its launch `Intent`. Use this inside a custom error activity to display or transmit the crash information.
### Method Signature
```java
static String getStackTraceFromIntent(Intent intent)
```
### Parameters
* **intent** (Intent) - The launch Intent of the error activity.
### Returns
* (String) - The full stack trace string, or null if not available.
### Example
```java
// Inside your CustomErrorActivity.onCreate():
String stackTrace = CustomActivityOnCrash.getStackTraceFromIntent(getIntent());
// stackTrace: "java.lang.RuntimeException: Boom!\n at com.example.MainActivity..."
TextView tvStackTrace = findViewById(R.id.tv_stack_trace);
tvStackTrace.setText(stackTrace != null ? stackTrace : "No stack trace available");
```
```
--------------------------------
### minTimeBetweenCrashesMs
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Sets the minimum time interval between crashes to prevent launching the error activity during a crash loop. If a crash occurs within this interval, the system crash screen is shown.
```APIDOC
## minTimeBetweenCrashesMs
### Description
Defines the time that must pass between app crashes to determine that we are not in a crash loop. If a crash has occurred less that this time ago, the error activity will not be launched and the system crash screen will be invoked.
### Method
`minTimeBetweenCrashesMs(long)`
### Default Value
`3000`
```
--------------------------------
### CustomActivityOnCrash.getActivityLogFromIntent()
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Retrieves the activity lifecycle log as a timestamped string. This is useful for reconstructing the user's actions before a crash, provided that `trackActivities` was enabled.
```APIDOC
## CustomActivityOnCrash.getActivityLogFromIntent()
### Description
Returns the activity lifecycle log as a timestamped string, or `null` if `trackActivities` was not enabled. Useful for reconstructing what the user was doing before the crash.
### Method Signature
```java
static String getActivityLogFromIntent(Intent intent)
```
### Parameters
* **intent** (Intent) - The launch Intent of the error activity.
### Returns
* (String) - The activity log string, or null if activity tracking was not enabled.
### Example
```java
// Requires: .trackActivities(true) in CaocConfig.Builder
String activityLog = CustomActivityOnCrash.getActivityLogFromIntent(getIntent());
// activityLog:
// "2024-03-20 14:21:50: SplashActivity created\n"
// "2024-03-20 14:21:52: SplashActivity destroyed\n"
// "2024-03-20 14:21:53: MainActivity created\n"
// "2024-03-20 14:22:01: SettingsActivity created\n"
// "2024-03-20 14:22:04: SettingsActivity resumed\n"
if (activityLog != null) {
Log.d("CAOC", "Activity log:\n" + activityLog);
} else {
Log.d("CAOC", "Activity tracking was not enabled");
}
```
```
--------------------------------
### Track user activity
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Enables or disables the tracking of visited activities and their lifecycle calls. This information is displayed in the default error activity's details. Defaults to false.
```java
trackActivities(boolean);
```
--------------------------------
### errorActivity
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Allows setting a custom activity to be launched instead of the default error activity for more advanced customization. The custom activity must be declared in the AndroidManifest.xml with the specific process.
```APIDOC
## errorActivity
### Description
This method allows you to set a custom error activity to be launched, instead of the default one. Use it if you need further customization that is not just strings, colors or themes (see below). If you don't set it (or set it to null), the library will use the first activity on your manifest that has an intent-filter with action `cat.ereza.customactivityoncrash.ERROR`, and if there is none, a default error activity from the library. If you use this, the activity **must** be declared in your `AndroidManifest.xml`, with `process` set to `:error_activity`.
Example:
```xml
```
As noted, you can also use the following intent-filter to specify the error activity:
```xml
```
### Method
`errorActivity(Class extends Activity>)`
```
--------------------------------
### Apply Custom Theme to DefaultErrorActivity
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Assign a specific theme to the `DefaultErrorActivity` by declaring it in your `AndroidManifest.xml`. Ensure the theme is defined in your app's `res/values/styles.xml` or `themes.xml`.
```xml
```
--------------------------------
### showRestartButton
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Controls whether the error activity shows a 'Restart app' button or a 'Close app' button. If false, the button closes the app.
```APIDOC
## showRestartButton
### Description
This method defines if the error activity must show a "Restart app" button or a "Close app" button. If you set it to `false`, the button on the default error activity will close the app instead of restarting. If you set it to `true` and your app has no launch activity, it will still display a "Close app" button!
### Method
`showRestartButton(boolean)`
### Default Value
`true`
```
--------------------------------
### Set custom error drawable
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Allows replacing the default bug image with a custom drawable or mipmap resource. Pass the resource ID. Defaults to null (uses the bug image).
```java
errorDrawable(Integer);
```
--------------------------------
### Retrieve Custom Crash Data from Intent
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Fetch the string generated by your `CustomCrashDataCollector.onCrash()` implementation. Returns `null` if no collector was configured. Requires `.customCrashDataCollector()` in `CaocConfig.Builder`.
```java
// Requires: .customCrashDataCollector(new MyCrashDataCollector()) in CaocConfig.Builder
String customData = CustomActivityOnCrash.getCustomCrashDataFromIntent(getIntent());
// customData: "User ID: 12345\nSession ID: abc-xyz\nNetwork: WIFI"
if (customData != null) {
sendCrashReportToServer(customData);
}
```
--------------------------------
### Close Application
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Closes the application and kills the current process. You MUST call this method to avoid multiprocess issues, such as multiple Application class instances.
```java
CustomActivityOnCrash.closeApplication(activity, eventListener);
```
--------------------------------
### Set minimum time between crashes
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Defines the minimum time in milliseconds that must pass between crashes to avoid triggering the error activity. If a crash occurs sooner, the system crash screen is shown. Defaults to 3000ms.
```java
minTimeBetweenCrashesMs(boolean);
```
--------------------------------
### enabled
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Enables or disables the CustomActivityOnCrash crash interception mechanism. Useful for controlling library behavior across different build flavors or types.
```APIDOC
## enabled
### Description
Defines if CustomActivityOnCrash crash interception mechanism is enabled. Set it to `true` if you want CustomActivityOnCrash to intercept crashes, `false` if you want them to be treated as if the library was not installed.
### Method
`enabled(boolean)`
### Default Value
`true`
```
--------------------------------
### Show error details button
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Controls the visibility of the 'error details' button on the error activity. Setting to false hides the button, preventing users from viewing the stack trace. Defaults to true.
```java
showErrorDetails(boolean);
```
--------------------------------
### Override Error Activity Theme in Manifest
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Redeclare the DefaultErrorActivity in your manifest to specify a custom theme for it. Ensure the theme is a child of Theme.AppCompat.
```xml
```
--------------------------------
### eventListener
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Provides a mechanism to register an event listener for notifications when the error activity is shown, or when the app is restarted or closed by the library.
```APIDOC
## eventListener
### Description
This method allows you to specify an event listener in order to get notified when the library shows the error activity, restarts or closes the app.
### Method
`eventListener(EventListener)`
```
--------------------------------
### Override String Resources for Error Activity
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Replace default error messages and button texts by overriding these string resources in your app's `res/values/strings.xml` file. This allows for full localization and branding of the crash screen.
```xml
Oops! Something went wrong.\nOur team has been notified.
Try Again
Exit
Show Details
Crash Report
Copy Report
Report copied!
Crash info
```
--------------------------------
### Override Default Error Activity Strings
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Provide new strings and translations for the default error activity by overriding these string resources in your project.
```xml
An unexpected error occurred.\nSorry for the inconvenience.
```
```xml
Restart app
```
```xml
Close app
```
```xml
Error details
```
```xml
Error details
```
```xml
Close
```
```xml
Copy to clipboard
```
```xml
Copied to clipboard
```
```xml
Error information
```
--------------------------------
### Specify Custom Crash Data Collector
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Use this method to provide a custom crash data collector. The collector will be invoked on crash to add extra data to error details. Ensure the collector is not an anonymous or non-static inner class, as it needs to be serializable. Setting it to null disables custom data collection.
```java
customCrashDataCollector(CustomCrashDataCollector);
```
--------------------------------
### Log error on restart
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Controls whether the stack trace is relogged when the custom error activity is launched. This aids in viewing the crash trace in Android Studio's Logcat. Defaults to true.
```java
logErrorOnRestart(boolean);
```
--------------------------------
### Set Custom Error Image
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Replace the default error drawable with a custom image by providing its resource ID using `errorDrawable()` in `CaocConfig.Builder`. Alternatively, place a file named `customactivityoncrash_error_image.png` in the appropriate density folders.
```java
// Use a custom image instead of the default upside-down bug (in Application.onCreate):
CaocConfig.Builder.create()
.errorDrawable(R.drawable.ic_sad_face) // any drawable or mipmap resource
.apply();
// OR place a file named customactivityoncrash_error_image.png in each density bucket:
// res/drawable-mdpi/customactivityoncrash_error_image.png
// res/drawable-hdpi/customactivityoncrash_error_image.png
// res/drawable-xhdpi/customactivityoncrash_error_image.png
// res/drawable-xxhdpi/customactivityoncrash_error_image.png
// res/drawable-xxxhdpi/customactivityoncrash_error_image.png
```
--------------------------------
### Set event listener
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Allows specifying an event listener to receive notifications when the error activity is shown, or when the app restarts or closes.
```java
eventListener(EventListener);
```
--------------------------------
### CustomActivityOnCrash.getCustomCrashDataFromIntent()
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Retrieves the string produced by a `CustomCrashDataCollector` implementation. This method returns the custom data collected during a crash, or null if no collector was configured.
```APIDOC
## CustomActivityOnCrash.getCustomCrashDataFromIntent()
### Description
Returns the string produced by your `CustomCrashDataCollector.onCrash()` implementation, or `null` if no collector was configured. This allows you to access and send any custom data you've chosen to collect during a crash.
### Method Signature
```java
static String getCustomCrashDataFromIntent(Intent intent)
```
### Parameters
* **intent** (Intent) - The launch Intent of the error activity.
### Returns
* (String) - The custom crash data string, or null if no custom collector was set.
### Example
```java
// Requires: .customCrashDataCollector(new MyCrashDataCollector()) in CaocConfig.Builder
String customData = CustomActivityOnCrash.getCustomCrashDataFromIntent(getIntent());
// customData: "User ID: 12345\nSession ID: abc-xyz\nNetwork: WIFI"
if (customData != null) {
sendCrashReportToServer(customData);
}
```
```
--------------------------------
### Register Custom Error Activity in AndroidManifest.xml
Source: https://context7.com/ereza/customactivityoncrash/llms.txt
Declare your custom error activity in the AndroidManifest.xml file. You can optionally use an intent-filter to specify the action that triggers this activity.
```xml
```
--------------------------------
### errorDrawable
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Allows replacing the default error drawable (upside-down bug image) with a custom drawable resource.
```APIDOC
## errorDrawable
### Description
This method allows changing the default upside-down bug image with an image of your choice. You can pass a resource id for a drawable or a mipmap.
### Method
`errorDrawable(Integer)`
### Default Value
`null` (the bug image is used)
```
--------------------------------
### Set custom error activity
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Allows specifying a custom activity to handle errors instead of the default one. This activity must be declared in the `AndroidManifest.xml` with `process` set to `:error_activity`. Falls back to an activity with the `cat.ereza.customactivityoncrash.ERROR` intent filter or the library's default error activity if not set.
```java
errorActivity(Class extends Activity>);
```
```xml
```
```xml
```
--------------------------------
### logErrorOnRestart
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Determines if the stack trace should be re-logged when the custom error activity is launched, aiding in debugging via Logcat.
```APIDOC
## logErrorOnRestart
### Description
This controls if the stack trace must be relogged when the custom error activity is launched. This functionality exists because the Android Studio default Logcat view only shows the output for the current process. This makes it easier to see the stack trace of the crash. You can disable it if you don't want an extra log.
### Method
`logErrorOnRestart(boolean)`
### Default Value
`true`
```
--------------------------------
### Enable or disable crash interception
Source: https://github.com/ereza/customactivityoncrash/blob/master/README.md
Determines if CustomActivityOnCrash should intercept crashes. Set to true to enable, false to disable. Useful for managing the library across different build flavors or types. Defaults to true.
```java
enabled(boolean);
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.