Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><a href="http://www.sherif.mobi/2012/11/application-which-always-requires-login.html" rel="nofollow">Here is the solution I came up with.</a></p> <p>Please Download the project at the end of the blog post and test it.</p> <p>Tested on: </p> <ul> <li>Samsung S3 running android 4.0.4</li> <li>Emulator running android 2.3.1</li> </ul> <p><strong>The basic idea</strong>: We will create a RequireLoginActivity which will be extended by all our activities except the LoginActivity.</p> <p>Three cases should be captured when the <em>onResume</em> function is called:</p> <ol> <li>Jumping from one RequireLoginActivity to another RequireLoginActivity using a flavor of startActivity.</li> <li>Jumping from one RequireLoginActivity back to a previous RequireLoginActivity by finishing the current activity.</li> <li>Coming back to a RequireLoginActivity after hiding it (we should here show the login!)</li> </ol> <p>The basic idea of my solution is to have 2 counters: number of Started activities (<strong>startCounter</strong>) and number of Paused activities (<strong>pauseCounter</strong>). Each time an activity starts we will increment <strong>startCounter</strong>. Similarly, when an activity pauses, <strong>pauseCounter</strong> should be incremented. In our <em>onResume</em> function, we will decide whether to go to the Sign in by comparing the 2 counters. We will gotoLogin() if the 2 counters are equal!</p> <p>Let me explain: At any time, case 1 can be captured simply because upon starting new activities, our <strong>startCounter</strong> will always be greater that <strong>pauseCounter</strong> by 1. This is true because we will always have one extra activity started but not paused.</p> <p>Also, case 3 is easily captured, because once you leave our app, say, using the HOME button, we will increment the <strong>pauseCounter</strong> and the 2 counters will become equal. Once the app is resumed, the <em>onResume</em> will decide to <strong><em>gotoLogin</em></strong>().</p> <p>Case 2 is a bit tricky, but simple as well. The trick is by overriding the <em>finish</em>() function and decrementing the <strong>startCounter</strong> once and the <strong>pauseCounter</strong> twice in it. Remember that when finishing the activity, <em>onPause</em> is called and our counters are equal. Now by decrementing <strong>startCounter</strong> once and <strong>pauseCounter</strong> twice, we ultimately returned to the counters' values of the previous activity, and <strong>startCounter</strong> will remain greater the <strong>pauseCounter</strong> by 1 when the previous activity resumes.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload