I have solved the problem by taking a workaround. It is not the exact solution but my problem has been solved. What I have done is that I have used AlarmManager
to launch a repeated service (say After 10 seconds) which checks for new application top of the activity stack every time. If the Application is different from the last application (already saved) this is the new app that has been opened. The major drawback of this approach is that it eats up battery but you can select a suitable period and do not wake up the device.
This service launching code is given below:
//Start a Service that is started every 5 seconds
AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(MyActivity.this, MyService.class);
PendingIntent pintent = PendingIntent.getService(context, 0, intoo, 0);
alarm.setRepeating(AlarmManager.RTC, cal.getTimeInMillis(), 5*1000, pintent);
In MyService.java
you should check for new application on top of the activity stack.