In the latest version of my app, some users are experiencing a crash that I'm unable to reproduce. Currently only Samsung
devices running Lollipop
are having the issue, but that might just be coincidence.
After analyzing the stack trace and relevant code, I think that I may have found the culprit. To test my assumption, I simplified the code to the snippet below:
public class TestActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button b = new Button(this);
b.setText("Click me!");
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Handler().post(new Runnable() {
@Override
public void run() {
// This is the callback method
Log.d("TAG", "listenerNotified");
}
});
}
});
setContentView(b);
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("TAG", "onDestroy");
}
}
Every time I test the above application by first tapping the Click me button and then the back button, listenerNotified
is printed to the console before onDestroy()
.
I'm however not sure if I can rely on this behavior. Does Android
make any guarantees about the above scenario? Can I safely assume that my Runnable
will always be executed before onDestroy()
or is there a scenario where that won't be the case? In my real app, there is of course a lot more happening (like other threads posting to the main thread and more operations happening in the callback). But this simple snippet seemed sufficient to demonstrate my concern.
Is it every possible (possibly due to the influence of other threads or callbacks posted to the main thread) that I get the debug output below?
D/TAG: onDestroy
D/TAG: listenerNotified
I would like to know this, since that outcome being possible would explain the crash.