Above all answers are really very good. But there are encounter problem of memory leakage.
This issue is often known in the Android community as "Leaking an Activity". Now what exactly does that mean?
When configuration change occurs, such as orientation change, Android destroys the Activity and recreates it. Normally, the Garbage Collector will just clear the allocated memory of the old Activity instance and we're all good.
"Leaking an Activity" refers to the situation where the Garbage Collector cannot clear the allocated memory of the old Activity instance since it's being (strong) referenced
from an object that out lived the Activity instance. Every Android app has a specific amount of memory allocated for it. When Garbage Collector cannot free up unused memory, the app's performance will decrease gradually and eventually crash with OutOfMemory
error.
How to determine whether the app leaks memory or not? The fastest way is to open the Memory tab in Android Studio and pay attention to allocated memory as you change the orientation.
If the allocated memory keeps on increasing and never decreases then you have a memory leak.
1.Memory leak when user change the orientation.
First you need to define the splash screen in your layout resource splashscreen.xml
file
Sample Code for splash screen activity.
public class Splash extends Activity {
// 1. Create a static nested class that extends Runnable to start the main Activity
private static class StartMainActivityRunnable implements Runnable {
// 2. Make sure we keep the source Activity as a WeakReference (more on that later)
private WeakReference mActivity;
private StartMainActivityRunnable(Activity activity) {
mActivity = new WeakReference(activity);
}
@Override
public void run() {
// 3. Check that the reference is valid and execute the code
if (mActivity.get() != null) {
Activity activity = mActivity.get();
Intent mainIntent = new Intent(activity, MainActivity.class);
activity.startActivity(mainIntent);
activity.finish();
}
}
}
/** Duration of wait **/
private final int SPLASH_DISPLAY_LENGTH = 1000;
// 4. Declare the Handler as a member variable
private Handler mHandler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(icicle);
setContentView(R.layout.splashscreen);
// 5. Pass a new instance of StartMainActivityRunnable with reference to 'this'.
mHandler.postDelayed(new StartMainActivityRunnable(this), SPLASH_DISPLAY_LENGTH);
}
// 6. Override onDestroy()
@Override
public void onDestroy() {
// 7. Remove any delayed Runnable(s) and prevent them from executing.
mHandler.removeCallbacksAndMessages(null);
// 8. Eagerly clear mHandler allocated memory
mHandler = null;
}
}
For more information please go through this link