Search code examples
javaandroidkotlinacra

Acra: How to retrieve a token from a custom class inheriting from ReportSenderFactory


I have a token that I generate in one of my activities and that I want to be able to retrieve it from my HttpSender when I do sendHttpRequests.

The problem is that I always end up with a null token... The sendHttpRequests() method is triggered when a crash occurs.

(I'm a beginner on Acra)

@AcraCore(reportSenderFactoryClasses = [SenderFactory::class])
class MyApp : Application() {

    override fun onCreate() {
        super.onCreate()
        ACRA.init(this)
    }
}
class SenderFactory : ReportSenderFactory {

    override fun create(context: Context, config: CoreConfiguration): ReportSender = AcraSender(config)
}

class AcraSender(
    config: CoreConfiguration,
    method: Method = POST,
    type: StringFormat? = null
) : HttpSender(config, method, type) {

    override fun sendHttpRequests(
        configuration: CoreConfiguration,
        context: Context,
        method: Method,
        contentType: String,
        login: String?,
        password: String?,
        connectionTimeOut: Int,
        socketTimeOut: Int,
        headers: Map<String, String>?,
        content: String,
        url: URL,
        attachments: MutableList<Uri>
    ) {

        //I want to retrieve my TOKEN here
    }
}

Solution

  • There are a few solutions depending on your requirements:

    • If you want your token to be part of your report, use ErrorReporter.putCustomData, the retrieve it in ReportSender.send with
    ((JSONObject)report.get(ReportField.CUSTOM_DATA.name())).optString("YOUR_KEY")
    
    • If your token is generated without user interaction, just generate it in the ReportSender.
    • Otherwise, use any persistent storage like SharedPreferences or plain files.

    Background info:

    Acra runs ReportSenders in a separate process (because a dying process after a crash is not a good place to do network stuff).

    This means most in-memory storage can't be used for sharing data between the app and ReportSenders.

    ErrorReporter.putCustomData works because reports are saved to disk temporarily.