At particular point of time in my app, I want to restart the app completely i.e. killing the process associated with the app and then restarting it again. I want to do this to free up heap space as my app contains lot of bitmaps.
I used this SO link with the highest voted answer and created following extra activity as following:
/** This activity shows nothing; instead, it restarts the android process */
public class MagicAppRestart extends Activity {
// Do not forget to add it to AndroidManifest.xml
// <activity android:name="your.package.name.MagicAppRestart"/>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.exit(0);
}
public static void doRestart(Activity anyActivity) {
anyActivity.startActivity(new Intent(anyActivity.getApplicationContext(), MagicAppRestart.class));
}
}
and calling this activity as MagicAppRestart.doRestart(this);
from the required place in another activity.
Now, the issue is this works fine on android 2.3 but on 4.0, this code only exits the app but do not restart it.
Am I doing anything wrong? Is there exist a solution for this issue which will work on all OS?
Also, I have already tried following code, it restarts the but not process and hence does not free up the heap, so it is of no use to me:
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
Any help appreciated !
Edit
I have 7 activities in my app including home activity. Barring home activity, other 6 activities use ViewFlipper
with 5-8 screens.
I'm using unbindDrawables() in onStop()
and onDestroy()
of every activity but it releases only little portion of the memory.
Hence I'm looking to completely restart the app process.
Edit 2
I just came across this:
In addition, Android changed the way bitmap memory is allocated. Prior to Android 3.0, bitmaps were allocated in native memory, with only a small descriptor kept on the Java heap; now the entire bitmap is allocated from the Java heap. This can lead to the Java heap being used up very quickly if multiple bitmaps are kept in memory.
I guess this is the reason why my approach is working in device with 2.3OS and not on device with 4.0 OS.