Wednesday, 30 April 2014

Timeouting onPause for activity for more operations

Here is some code how to timeout some time for onPause to i.e
  • show dialog (activity behaving like dialog) 
    • when we click on notification 
      • only when any of our activity is displaying  
This example is quite hard to describe in short but there is explanation how to make custom OnClickListener for notification in my one of the latest posts. And by using that code with this post you can achieve this magic trick..

Here will be some help how to open second activity with custom dialog. It makes no sense for normal displaying some data, but for notifications it is very helpful. This is just silly example, how to make it and make it clear.
 So what I did was:

In Application class

 public class MyApplication extends Application {  
      
      //... application methods  

      //declaring flag to know if activity is running  
      public boolean isRunning;  
      public long timeout;  
 }  

For every activity I added to onResume and onPause methods, flag - it will describing if activity is running.

 @Override  
 protected void onResume() {  
   super.onResume();  
   application.isRunning = true;  
 }  

 @Override  
 protected void onPause() {  
   super.onPause();  
   application.isRunning = false;//setting field in Application  
   application.timeout=System.currentTimeMillis();  
 }  

Also there was declared second field describing what is the current time - timeout - in Application class

Let's say we want show this "dialog" when I click the second activity, so in onCreate this second activity you need add something like th

 if (application.isRunning || timeoutLessThan(application, 300)) {  
   //showing dialog  
 } else {  
   //nothing to do  
 }  

 private boolean timeoutLessThan(NHApplication application, int value) {  
      long abs = Math.abs(application.timeout - System.currentTimeMillis());  
      Log.d(TAG, "diff timeout " + abs);  
      return abs < value;  
 }  


This timeout will help when you want do some fast action in 300ms before pausing the first activity.