In my app, I want a media file to play, and to keep playing if the user rotates the screen (destroying the Activity), but I want it to stop playing if the user moves to a differ
Your solution has at least one potential problem.
According to Android documentation:
Some device configurations can change during runtime (such as screen orientation, keyboard availability, and language). When such a change occurs, Android restarts the running Activity (onDestroy() is called, followed by onCreate()).
Testing for a change in rotation only handles one case. Since this is likely to be the most common cause of configuration change, it's an OK solution. But what if you could handle all cases, existing or added in some future version of Android, without the overhead of handling configuration yourself?
Updated to use onRetainNonConfigurationInstance
. Android docs have this to say about it:
Called by the system, as part of destroying an activity due to a configuration change, when it is known that a new instance will immediately be created for the new configuration.
Also changed chain to super.onDestroy() to happen after stopping media, but not entirely sure about that. Guess it depends on what stopping media means, and what effect destroying may have on stopping media.
private Boolean mConfigurationChange = false;
public Object onRetainNonConfigurationInstance() {
mConfigurationChange = true;
return null;
}
public void onDestroy() {
if (!mConfigurationChange) {
// Code to stop media file goes here.
}
super.onDestroy();
}