Application which always requires Login

In this tutorial is an attempt to disallow the user to resume an application without signing in again. Whatever happens that causes my app to go off-screen should force the user to sign in again. In this context, signing in is rather case-specific: Say, every time the app is hidden and then shown again, the app will go to one specific activity.

To start with, we will need an activity that will be extended by all our activities. I will call it here RequireLoginActivity which is a base class and all our work will be in it.

This activity has 2 requirements:

Requirement 1: Once resumed, it should go to the Sign in screen if it was resumed from the background.
Requirement 2: Once we decide to force the user to sign in, any instance of this activity should finish.

Requirement 2:

To start, I will accomplish the somehow easier requirement 2 by using Francesco Laurita's Solution. Simply stated, each RequireLoginActivity should register a receiver that will listen for a CLOSE broadcast. Once we decide to go to the Sign in screen, we broadcast this message and all RequireLoginActivities alive will just finish.

First of all, let's name this BroadCast intent Action as INTENT_LOGOUT in RequireLoginActivity.

public class RequireLoginActivity extends Activity {
 private static final String INTENT_LOGOUT = "mobi.sherif.INTENT_LOGOUT";
}

Now, we need the broadcast receiver: Each activity should have a logout receiver, so just after this INTENT_LOGOUT we initialize our receiver:

private final BroadcastReceiver mLogoutReceiver = new BroadcastReceiver() {

 @Override
 public void onReceive(Context context, Intent intent) {
  finish();
 }
};

Notice that this receiver's only function is to finish the current RequireLogin Activity.

Finally, we need to register the broadcast receiver in our onCreate function and unregister it when our activity is finished in our onDestroy function:

@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 IntentFilter intentFilter = new IntentFilter();
 intentFilter.addAction(INTENT_LOGOUT);
 registerReceiver(mLogoutReceiver, intentFilter);
}
@Override
protected void onDestroy() {
 unregisterReceiver(mLogoutReceiver);
 super.onDestroy();
}

For the sake of completeness and neatness, we shall add a function that will broadcast this intent once we need to go to the SignIn screen. I will call it gotoLogin():

private void gotoLogin() {
 Intent intent = new Intent(this, LoginActivity.class);
 startActivity(intent);
 Intent broadcastIntent = new Intent();
 broadcastIntent.setAction(INTENT_LOGOUT);
 sendBroadcast(broadcastIntent);
}


Requirement 1:

Now, we need a mechanism that will allow us to capture when that activity is hidden and shown. To be specific, we need one that allows us to differentiate between a normal onResume, onPause cycle due to activity navigation and a cycle caused by hiding the activity for any reason such as phone call, pressing the home button, screen lock, navigating to a different activity.

Three cases should be captured when the onResume function is called:

  1. Jumping from one RequireLoginActivity to another RequireLoginActivity using a flavor of startActivity.
  2. Jumping from one RequireLoginActivity back to a previous RequireLoginActivity by finishing the current activity.
  3. Coming back to a RequireLoginActivity after hiding it (we should here show the login!)


The basic idea of my solution is to have 2 counters: number of Started activities (startCounter) and number of Paused activities (pauseCounter). Each time an activity starts we will increment startCounter. Similarly, when an activity pauses, pauseCounter should be incremented. In our onResume 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!

Let me explain:
At any time, case 1 can be captured simply because upon starting new activities, our startCounter will always be greater that pauseCounter by 1. This is true because we will always have one extra activity started but not paused.

Also, case 3 is easily captured, because once you leave our app, say, using the HOME button, we will increment the pauseCounter and the 2 counters will become equal. Once the app is resumed, the onResume will decide to gotoLogin().

Case 2 is a bit tricky, but simple as well. The trick is by overriding the finish() function and decrementing the startCounter once and the pauseCounter twice in it. Remember that when finishing the activity, onPause is called and our counters are equal. Now by decrementing startCounter once and pauseCounter twice, we ultimately returned to the counters' values of the previous activity, and startCounter will remain greater the pauseCounter by 1 when the previous activity resumes.

Implementation:
I will implement the counters in my Application instance:

public class RequireLoginApplication extends Application {
 
 private static int nRequiredStarted = 0; //this is our startCounter

 public void incrementStart() {
  ++nRequiredStarted;
 }

 private static int nRequiredPaused = 0; //this is our pauseCounter

 public void incrementPause() {
  ++nRequiredPaused;
 }

 public void notifyFinish() { //this is called when the activity finishes
  --nRequiredPaused;
  --nRequiredPaused;
  --nRequiredStarted;
 }

 
 public boolean shouldLogin() { //this decides whether to go to the login screen(true)
  return (nRequiredPaused==nRequiredStarted);
 }
 
 public void reset() { //reset the counters in the login screen
  nRequiredPaused = 0;
  nRequiredStarted = 0;
 }
}

Now, in our RequireLoginActivity, we simply incrementStart in onCreateincrementPause  in onPause, and notifyFinish in finish.

@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 IntentFilter intentFilter = new IntentFilter();
 intentFilter.addAction(INTENT_LOGOUT);
 registerReceiver(mLogoutReceiver, intentFilter);
 ((RequireLoginApplication)getApplication()).incrementStart();
}

@Override
protected void onPause() {
 super.onPause();
 ((RequireLoginApplication)getApplication()).incrementPause();
}

@Override
public void finish() {
 ((RequireLoginApplication)getApplication()).notifyFinish();
 super.finish();
}

The last step is the onResume function: Just decide whether we need to gotoLogin:

@Override
protected void onResume() {
 super.onResume();
 if(((RequireLoginApplication)getApplication()).shouldLogin()) {
  gotoLogin();
 }
}


Click here for Sample Project + Source Code (download)

40 comments:

  1. Nice solution, much easier than what I currently have in my app. Thanks.

    ReplyDelete
  2. Obat Aborsi,, Obat Penggugur Kandungan,,
    Nice bag you can earn money from that
    Thanks for your posting
    Visit me @, Jual Obat Aborsi,,

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Salesforce is a cloud computing service as a software (SaaS) company that specializes in customer relationship management (CRM). ... The software has become the number one for customer success and helps businesses track customer activity, market to customers and many more services.
    Salesforce Training in Chennai

    Salesforce Online Training in Chennai

    Salesforce Training in Bangalore

    Salesforce Training in Hyderabad

    Salesforce training in ameerpet

    Salesforce Training in Pune

    Salesforce Online Training

    Salesforce Training


    ReplyDelete
  5. Then you may fine-track your marketing campaign messaging based totally on that feedback. A Valuable Partnership The ultimate cost of influencers to B2B entrepreneurs is their involvement. Influencers permit agencies to hook up with new and current clients in a researched, measured way. They accentuate service or product blessings several tiers ahead, within the eyes of fans. Prospects will pay more interest to an influencer than they'll to advertising. A pandemic won't appear like the proper time to amplify into influencer advertising, particularly while the financial panorama is an increasing number of confusing. Yet there's fantastic equity to be gained by way of speakme with authenticity and sincerity when humans need enter and reassurance.


    https://buymorefollower.com/buy-instagram-followers-singapore


    ReplyDelete
  6. The Ultimate Google Ads & search engine marketing Certification Bundle Google is an incredibly valuable aid for entrepreneurs due to the fact it offers each paid and organic traffic. In this direction, you may learn how to leverage both. You'll get an overview of paid marketing with Google and learn how to optimize your internet site for search engine marketing. Get The Ultimate Google Ads & search engine optimization Certification Bundle for $15 with promo code BFSAVE70. Prices subject to change. Related: 10 Marketing Skills You Can Start Learning Now For Less Than $20, Black Friday Sale 5 Reasons Marketing Hygiene Measures is a Must for Brands to Bounce Back Post Covid-19 Lockdowns Icnocuícatl, the Mexican poems by way of Cerveza Victoria to say good-bye to folks who left with out saying 'good-bye' 02 How retailers are adapting advertising and marketing techniques for the vacations in 2020 © 2020 CNBC LLC. All Rights Reserved. A Division of NBCUniversal Data is a actual-time snapshot *Data is delayed at the least 15 minutes.
    https://buymorefollower.com/buy-instagram-followers-greece

    ReplyDelete
  7. If you have a neutral room, it is advisable to use color. You can add a bright sign in a neon shade to make it stand out.https://neonsignsuk.weebly.com/blog/no-1-website-to-buy-for-custom-neon-signs-the-united-kingdom

    For a brighter room, combine multiple lighting fixtures. Additionally, neon lights create a more sophisticated texture that just works.

    ReplyDelete
  8. This could be a large armoire or a cabinet. Interior design success is all about combining small and big elements. This applies to accessories too. Interior designers love to use baskets and decorative bowls as trays or containers to store loose items. To add a touch more glamour to your coffee or ottoman table, you can add a gold tray. Place a candle, a few books and a small tray with colored stones. This little view may seem frivolous, however, it is essential for a well-layered, decorated aesthetic.
    click here

    ReplyDelete
  9. The idea behind mixing different types of furniture gives you the ability to balance the space without making it too big or too spindly.

    Even if you have a small apartment to decorate, there are still many decorating ideas. A majority of designers recommend that even the smallest rooms contain one large, statement piece.https://about.me/neoncave/

    ReplyDelete
  10. Now that you have a basic understanding of interior design, it is time for you to start implementing these tips. You can design your home yourself with some help from sites such as Pinterest and MYMOVE. These tips can be used to make your home unique, no matter whether you like rustic, vintage or minimalistic styles.

    You can add a mirror to the walls, glass table tops or mirrored cabinet doors to make your room feel larger. Have you thought of using mirrors to reflect light on the floor? A mirror on the floor is another smart way to make a space appear larger. Multi-functional furniture like a chest that doubles as a coffeetable, sofa bed, or storage drawers bed can make your room look bigger. Also, nesting tables, folding and expandable tables, as well a nesting table, are great choices.
    read more

    ReplyDelete
  11. Take into account that furniture that is too tall or heavy can eat up valuable space. Consider a sofa and chair with open arms, exposed legs. This allows light through the furniture, making the room feel larger. Use larger furniture against walls to make the room appear larger. Do not block access. If accessories and furniture block the view, it can make a room feel cramped.website

    ReplyDelete
  12. I took photographs of the coffee tables I wanted to build. From there, I used Kodak Easy Share Software's photo editor to transform the pictures into black/white. I used printed copies of black and white images to record the measurements and dimensions. This was a great way to visualize how each piece fit together.https://homedesign.co.uk/

    ReplyDelete
  13. , I used Kodak Easy Share Software's photo editor to transform the pictures into black/white. I used printed copies of black and white images to record the measurements and dimensions. This was a great way to visualize how each piece fit together.
    It is important to have a plan of what wood, supplies and wood type you need before you start building. You can then go to the hardware shop and estimate the cost for your building project. If you want to save money on your building project, make sure it is worth the effort.
    read more

    ReplyDelete
  14. . This should be your building motto. Don't hurry the process. Before cutting, take the time to think through every detail.
    After they have been cut, it is very helpful to label them. This way, you won't grab the wrong wood piece and have to re-cut it.
    website

    ReplyDelete
  15. This is one of my biggest financial errors as a furniture maker: tools. They rush out to buy the best and most advanced tools.
    In my case I borrowed tools to get started on my first few projects. This was to test my skill level and see if it was possible to build my own home. I also bought the essential tools needed to get started: an electric drill (miter saw), circular saw, and sanding device.
    click here

    ReplyDelete
  16. Neon signs are a great option for a variety of commercial spaces, adding bright, vibrant and exciting onto the walls. From the entryway to the inside neon signs specifically for the leisure sector specifically can take your business to the next step.

    A lot of leisure facilities are by their very nature, enjoyable and a great place to be with your family and friends. It doesn't matter if it's a place for your children or where adults can enjoy an afternoon of R&R A neon sign might be the perfect decorative element missing. Here's an in-depth look at five locations that look amazing with the neon sign.
    https://neoncave.co.uk

    ReplyDelete
  17. Bowling alleys can be fun and bustling areas that are full of both adults and children which makes it the perfect spot to enjoy a Saturday evening or afternoon. With ever-growing bowling alleys opening with original themes, as well as drinks and food served in the house It's a great method of occupying the time and have some entertainment.

    A neon sign added to every bowling alley provides visual appeal that is perfectly paired with the lights and music of the bowling alley, resulting in a wonderful atmosphere that everyone can enjoy.CINEMA
    Cinemas are the perfect location to escape everything for just a few hours to enjoy the latest blockbuster from Hollywood. With sweets, popcorn and fizzy drinks cinemas offer a fantastic chance to put up signage in the lobby. These signs are a great way to mark different areas, be it for the pick-and-mix or tills.
    https://neonsignshistory.blogspot.com/2021/09/the-golden-age-of-neon.html

    ReplyDelete
  18. Block painting walls using contrast or harmonious colors can change the perception of space, and can provide your decor with an interesting twist. For a clean, crisp look, apply decorator's tape or masking tape. Find a quick style fix by drawing geometric shapes. Then fill the gaps by using a variety of hues that show your individualityhttps://www.scarsocial.com/bring-customers-to-the-door-with-a-neon-open-sign/

    ReplyDelete
  19. . Modify Your Messaging Tone
    Excessive salesmanship is the best method to lose people's interest in your messages. Instagram isn't the place to make a hard sell. Remember that no one like having products shoved in their faces. Your content should be interesting and relevant. It isn't a bad thing if it is entertaining while conveying your point. Consider using teasers or other advertising strategies to pique people's attention. Younger folks, for example, will appreciate exclusive deals. They want to know that they are among the exclusive few who have access to a certain thing.
    https://www.thetechbizz.com/6-reasons-why-you-need-an-adjustable-bed/

    ReplyDelete
  20. Elabore conteúdo que atenda melhor ao comprador por meio de uma compreensão mais profunda do objetivo de busca / frase de efeito por meio das informações do Google. Aumente a eficiência dentro da empresa ajustando os grupos de promoção.
    https://seekingalpha.com/user/55395488/comments
    Antecipe que as equipes de SEO e redação devem ter um plano de jogo para mais de meio ano. Diminua o perigo de canibalização - uma vez que você planejou efetivamente seus bordões, não haverá nenhuma cópia e você saberá o que conectar, onde e por qual texto âncora.

    ReplyDelete
  21. This comment has been removed by the author.

    ReplyDelete
  22. Kаtе Moss é um еxаmрlе semelhante; Ela é difícil e de forma alguma leva problemas no local. Pareça itens importantes, mas lembre-se de mantê-los sempre. Não mantenha exibindo postagens; mantenha alguma restrição em seu planejamento. Definitivamente, você deseja evitar o efeito de irritar seus seguidores, https://comprarseguidoresportugal2.blogspot.com/
    podendo considerar que todos os lugares em que postar esse tipo de filme ou comer algo importante. Dê alguns dias de pausa e ininterruptos entre as partes e, rememorando, menos é mais longe. Se você não tem nada de bom, não planeje.

    ReplyDelete
  23. Certifique-se de que os CTAs estão nas posições corretas em um artigo, com a cor e o texto apropriados. Utilize palavras poderosas e emocionalmente carregadas que podem atrair vitórias rápidas. Você ficará surpreso em como uma pequena mudança de palavra ou ajuste de cor pode melhorar drasticamente as taxas de conversão. Esta é a maneira mais eficaz de garantir que o SEO traga mais leads e conversões. https://www.quora.com/profile/Juliana-Juliana-106

    ReplyDelete
  24. With our channel letter signs you also receive a three-year guarantee on the labor and parts, which means that if you experience any issues, you don't be obligated to make costly repairs. The warranty covers the sign itself and the installation. So you can rest assured knowing that the sign you choose to install will draw the attention you want and assist in growing your business faster than other type of advertising.Over the last 10 years approximately, the method by which companies advertise has seen an entire change. With increasing numbers of people choosing to stream their television shows and stay clear of printed media, traditional methods for getting a company's name known to potential buyers is becoming increasingly ineffective. Even popup ads and side advertisements aren't more effective than traditional ways of advertising since people can disguise or pay for them to be avoided.
    https://capsdoc.com/2021/11/23/lets-honor-the-queens/?fbclid=IwAR3bGaMKtw-ADpyfTGGPrycF_vqdEhOUcE4qd7mMy4Bjsws6uqOxtyvot20

    ReplyDelete
  25. Hank: Os profissionais de marketing devem enviar mensagens apenas para pessoas que desejam receber comunicações deles. Não há casos especiais. Um método para garantir que os endossantes realmente desejam suas mensagens é usar a seleção em duas etapas. Isso permite que os endossantes confirmem que desejam suas mensagens e também os ajuda a encontrar seus e-mails na caixa de entrada imediatamente e a remover a mensagem do spam, caso ela vá parar lá.
    https://pbase.com/juliana1123/profile

    ReplyDelete
  26. Luxury is hardly ever off the rack
    Designer and bespoke bed room fixtures hardly ever comes “off the rack” so updating larger pieces of furniture such as beds and wardrobes this close to Christmas could be a challenge. We have some immaculate items equipped to go from our ex-display furniture Our showroom is being updated so these pristine items are 50% off to make way for some new arrivals.

    https://www.articlesbids.com/2022/01/21/how-big-should-my-dining-room-table-be/

    ReplyDelete
  27. As you become your Instagram swarm, your posts and story content can contact more people who are excited about your business and can be found by people who have scarcely any understanding into your business. Accounted accounts measure the quantity of people who have seen your substance, including people who aren't following you. People can find your posts or story when they search for hashtags you use. As you collect relationship with people, you can invite them to team up with your business and look further into your commitments. This will help clients with thinking of you as when they are ready to make a purchase.
    https://makeandappreciate.com/comprar-seguidores-instagram-portugal/

    ReplyDelete


  28. While making your record, you should describe your inspiration for your aficionados. You should express out loud whatever your character is and what you do. Which isolates your picture? Contemplate who you are centering with your virtual amusement strategy on Instagram when you make your picture page. It's okay to be fiery and inventive in your portrayal, especially on the off chance that it's smart for your group. GoPro Instagram features an innovative yet informative biography. "We make the most versatile camera on earth. Share with #GoPro. " You can moreover recall an intuitive association for your diary. This is a huge land parcel, so mull over where you keep up with that your group ought to go. GoPro chooses to remember its allies for Instagram, sending them to the LinkinBio page.
    https://https://articleft.com/?p=11191&preview=true
    /

    ReplyDelete


  29. While making your record, you should describe your inspiration for your aficionados. You should express out loud whatever your character is and what you do. Which isolates your picture? Contemplate who you are centering with your virtual amusement strategy on Instagram when you make your picture page. It's okay to be fiery and inventive in your portrayal, especially on the off chance that it's smart for your group. GoPro Instagram features an innovative yet informative biography. "We make the most versatile camera on earth. Share with #GoPro. " You can moreover recall an intuitive association for your diary. This is a huge land parcel, so mull over where you keep up with that your group ought to go. GoPro chooses to remember its allies for Instagram, sending them to the LinkinBio page.

    https://wishpostings.com/?p=14990&preview=true

    /

    ReplyDelete
  30. Retargeting is one of the most interesting (and effective) marketing strategies that is the fact that you target people who are already in your conversion funnel , but not strangers. They will require a little more encouragement to convert into customers.
    .
    Remember that targeting via Facebook is a great tool to increase sales or cross-sell. It allows you to sell your customers products that are similar to the items they purchased or of higher quality.
    Consider retargeting your campaigns. If a customer bought a sweater from you within the last week, consider making a matching set of trousers or clothing in your next retargeting ad sets. You can also provide discounts specific to customers who are loyal through ads which target the retargeting.
    https://sevenarticle.com/click-here/

    ReplyDelete
  31. halema11223 halemas11223April 25, 2022 at 2:27 PM

    It's also important to think about scenarios that could be catastrophic, so you're prepared and practiced should this happen. Include provisions for the possibility of deleting or hiding comments, or removing users from the community if they break the rules of your social media community
    https://factoryextreme.com/click-here-2/

    ReplyDelete
  32. This guide will provide you with the necessary tools to write professional social media posts regularly. Find out about the tips you should know and information about the top social media platforms for insurance agents and already-written scripts to start your social media accounts in motion today.https://boastcity.com/?p=3351&preview=true

    ReplyDelete
  33. Movavi video editor Plus 22.5 Crack is one the majority strange and high-performance video editor with the skill to change any video to the expert movie. Movavi Crack Download

    ReplyDelete
  34. Discover and share First Day Of College Quotes. Explore our collection of motivational and famous quotes by authors you know and love. First Day School Wishes

    ReplyDelete