0

I have searched for this scenario on SO. But I need some basic information.

The case is simple: The application needs to restarted but the launcher screen of the device is not supposed to be shown. (for some obvious reason, I want to free the application memory).

A pending intent is used to restart the application:

 restartTime = 0;
 alarmManager.set(AlarmManager.RTC, System.currentTimeMillis()
                    + restartTime, pendingIntent); //Restarting application

& the application is killed with this command:

android.os.Process.killProcess(android.os.Process.myPid()); 

Logs:

02-05 11:01:59.475: D/HomeActivity(31009): Restarting application 
02-05 11:01:59.485: I/Process(31009): Sending signal. PID: 31009 SIG: 9
02-05 11:01:59.635: I/HomeActivity(956): On Create
02-05 11:01:59.715: D/dalvikvm(956): GC_FOR_ALLOC freed 163K, 15% free 50758K/59248K, paused 22ms, total 22ms
02-05 11:01:59.745: I/dalvikvm-heap(956): Grow heap (frag case) to 65.724MB for 15816616-byte allocation
02-05 11:01:59.815: D/dalvikvm(956): GC_FOR_ALLOC freed 2K, 12% free 66204K/74696K, paused 17ms, total 17ms
02-05 11:01:59.845: I/dalvikvm-heap(956): Grow heap (frag case) to 78.908MB for 13824016-byte allocation
02-05 11:01:59.915: D/dalvikvm(956): GC_FOR_ALLOC freed <1K, 10% free 79709K/88200K, paused 18ms, total 18ms
02-05 11:02:00.045: I/HomeActivity(956): On Resume

As can be seen, the GC is called after onCreate of HomeActivity. Is it possible that any thread running with the (last)application context is still alive?

The clear question: If in case the CPU usage of device is high, is it possible, that the application is restarted (pending intent fires) before the application is destroyed.

vipulfb
  • 63
  • 1
  • 7
  • Is the application in the foreground when you call `killProcess()`. What component is calling `killProcess()`? – David Wasser Feb 06 '15 at 10:55
  • @DavidWasser Yes, the application is in foreground. Say, a simple button click is calling killprocess(). – vipulfb Feb 06 '15 at 11:00

1 Answers1

0

Using killProcess() is really bad architecture. If your app is in the foreground then the user will get a dialog ("Application has stopped working" or something like that). Also, If this happens, Android assumes that the Activity on the top of the stack has done something bad, and it removes the Activity from the stack and automatically restarts the application starting with the Activity underneath it (this behaviour may be different in different versions of Android).

Instead of doing this you should write some kind of reinitialization method that clears out old junk and reestablishes a clean state. Either that, or simply restart your app by launching your root activity again with Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK

David Wasser
  • 93,459
  • 16
  • 209
  • 274