Rapid Subscribe Android App

Rapid Subscribe Android App
Rapid Subscriber

Recent Posts

How to create DoubleBackPress to exit from App



When we create an app, it's must to handle Back actions to our app.

And if we create a WebView in our App, then it's must to create a proper handling actions relation to WebView back history.

For that, we use a runnable thread to handle timing to create a double back press to exit our app.

The double back press is used when we don't want to use a dialog box to confirm exit from our app.

To implement double back press in your app then create 3 variable in your activity.
 public class MainActivity extends AppCompatActivity {  
   private java.util.Timer Timers = new Timer();  
   private double backpress = 0;  
   private TimerTask Timer;  
   

Then add a runnable thread at last in your activity.oncreate
 backpress = 1;  
     Timer = new TimerTask() {  
       @Override  
       public void run() {  
         runOnUiThread(new Runnable() {  
           @Override  
           public void run() {  
             backpress = 1;  
             Timer.cancel();  
           }  
         });  
       }  
     };  
     Timers.schedule(Timer,(int)(3000));  
     backpress=1;  
   
     tooltext.setOnEditorActionListener(new TextView.OnEditorActionListener() {  
       @Override  
       public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {  
         ValidateUrl(tooltext.getText().toString());  
   
         return true;  
       }  
     });  

in your OnBackPressed method, use this runnable code to execute.
We use 3000ms (3sec) wait time to exit.
 @Override  
   public void onBackPressed() {  
     if(mywebview.canGoBack())  
     {  
       mywebview.goBack();  
     }  
     else  
     {  
       if(backpress == 1)  
       {  
         Toast.makeText(this, "Press Again to Exit", Toast.LENGTH_SHORT).show();  
         Timer = new TimerTask() {  
           @Override  
           public void run() {  
             runOnUiThread(new Runnable() {  
               @Override  
               public void run() {  
                 backpress = 2;  
               }  
             });  
           }  
         };  
         Timers.schedule(Timer,(int)(0));  
       }  
       Timer = new TimerTask() {  
         @Override  
         public void run() {  
           runOnUiThread(new Runnable() {  
             @Override  
             public void run() {  
               backpress = 1;  
             }  
           });  
         }  
       };  
       Timers.schedule(Timer,(int)(3000));  
       if(backpress==2)  
       {  
         finish();  
       }  
     }  

Follow us for more posts like this, 
Subscribe Harpreet studio on Youtube  
Like Harpreet Studio on Facebook  
Follow me on Instagram 

1 comment: