Android app background crashes
Thursday, Mar 24, 2016

I’ve been dealing with a tricky problem: our app crashing while in the background, but without any obvious pattern. My initial thoughts were that it was not handling bluetooth broadcasts correctly as defined in the manifest:

<receiver
    android:name=".Helper.BluetoothBroadcastReceiver"
    android:enabled="true">
    <intent-filter>
        <action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/>
    </intent-filter>
</receiver>

however, running the app in the background and flipping through bluetooth wasn’t causing any problems - at least not on my test phone. A friend reported crashes on his phone, so the next step was to find a way to capture the crash dumps. A very useful tool for this is acra - here is the Gradle dependency for it (you need to use the right acra version for your SDK build, newer versions will not automatically work as there are dependencies on com.android.support library versions)

compile 'ch.acra:acra:4.7.0'

It is fairly easy to get working (the guide is at theĀ acra website). You’ll need a server-side script to dump the crash logs, we were only interested in the raw data, so this PHP script was all that was needed:

<?php
$request = print_r($_REQUEST, true);
$fp = fopen('/var/tmp/crash.android.' . rand(), 'a');
fwrite($fp, $request);
fclose($fp);

After rolling out a new version it was just a case of waiting for a crash report to come in and sift through the information. In the end it was the Bluetooth broadcast - but it seems only under certain situations (the user was trying to connect to another peripheral and it seems that BT becomes unavailable for a short time).