Always return to the login screen

I have run the application using Splash activity screen for 5 seconds. Then open the Login activity screen , after you put the correct password and password, open Menu activity (listActivity) , then each line open MyCity activity .

UPDATE:

What I'm trying to get is: wherever you are in my application, and you leave my application for some reason, not only when you press the home button , but for examples:

  • You press the home button to check another application, and then return to my application.

  • You have a notification showing a new message about whatsup or email, you open your message or open an email, and then return to your application.

3. You left your mobile phone for a certain period of time, after which you want to check my application again.

4- press the power button to close the phone (lock the screen), then open the lock and want to return to my application.

what do I mean, when you leave my application for some reason, but without pressing the back button, which will exit the entire application, you want to return to my application again, you need to open the login screen to enter your username and password.

I called finish(); for splash activity and input activity.

I tried: android:clearTaskOnLaunch="true" in the activity of entering the manifest, but it does nothing.

Any advice would be appreciated,

PLEASE WRITE A FULL WORK CODE.

INPUT ACTIVITY:

  public class Login extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login); Button b = (Button) findViewById(R.id.loginbutton); b.setOnClickListener(new OnClickListener() { public void onClick(View v) { EditText username = (EditText) findViewById(R.id.login); EditText password = (EditText) findViewById(R.id.password); if(username.getText().toString().length() > 0 && password.getText(). toString().length() > 0 ) { if(username.getText().toString().equals("test") && password.getText(). toString().equals("test")) { Intent intent = new Intent(Login.this, Menu.class); startActivity(intent); finish(); } } } }); } } 

Menu activity:

  public class Menu extends ListActivity { String classes[] = { "City1", "City2", "City3", "City4", "City5"}; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1, classes)); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { // TODO Auto-generated method stub super.onListItemClick(l, v, position, id); String cheese = classes[position]; try { Class ourClass = Class.forName("com.test.demo.MyCity"); Intent ourIntent = new Intent(Menu.this, ourClass); ourIntent.putExtra("cheese", cheese); startActivity(ourIntent); } catch (ClassNotFoundException e) { e.printStackTrace(); } }} 

MyCity Activity:

  public class MyCity extends Activity { TextView tv1; String city; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.city); initializeTextViews();} private void initializeTextViews() { tv1=(TextView)findViewById(R.id.city_tv); city=getIntent().getStringExtra("cheese"); if(city.equalsIgnoreCase("City1")){ tv1.setText(Html.fromHtml(getString(R.string.city1)));} else if(city.equalsIgnoreCase("City2")){ tv1.setText(Html.fromHtml(getString(R.string.city2)));} else if(city.equalsIgnoreCase("City3")){ tv1.setText(Html.fromHtml(getString(R.string.city3)));} else if(city.equalsIgnoreCase("City4")){ tv1.setText(Html.fromHtml(getString(R.string.city4)));} else if(city.equalsIgnoreCase("City5")){ tv1.setText(Html.fromHtml(getString(R.string.city5)));} }} 

MY MANIFEST:

 <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.test.demo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".Splash" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".Login" android:label="@string/app_name" android:clearTaskOnLaunch="true"> <intent-filter> <action android:name="com.test.demo.LOGIN" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name=".Menu" android:label="@string/app_name" > <intent-filter> <action android:name="com.test.demo.MENU" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name=".MyCity" android:label="@string/app_name" > <intent-filter> <action android:name="com.test.demo.MYCITY" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> </application> </manifest> 

SECOND UPDATE : I got to what I want, but still I can’t achieve some steps, as described below:

By applying android:clearTaskOnLaunch="true" to Splash activity,

and prevent the back button from working in the menu action:

  @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { moveTaskToBack(true); return true; } return super.onKeyDown(keyCode, event); } } 

SO now when you press the home button from my application, and then return to your application:

Go directly to login activity .

but the main goal now:

if:

THE SCREEN IS LOCKED when you are away from your mobile phone, or press the power button lightly to lock the phone.

or

OPEN MESSAGE NOTIFICATIONS

or

OPEN EMAIL NOTIFICATIONS

or

you have a call and answer it,

THEN return my application , it does not switch to login activity , but you will return to the page where you were.

ANY ADVICE PLEASE THANKS.

THIED UPDATE:

I used different code to override the home button and controlled the back button, not the application: android:clearTaskOnLaunch="true" to activate the activity in the manifest, just apply the code down to the menu activity:

  @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { moveTaskToBack(true); return true;} else if (keyCode == KeyEvent.KEYCODE_HOME) { Intent i=new Intent(Menu.this,Login.class); startActivity(i); finish(); return true;} return super.onKeyDown(keyCode, event);} 
+6
source share
15 answers

Here is the solution I came up with.

Please download the project at the end of the blog post and test it.

Tested:

  • Samsung S3 is running Android 4.0.4
  • The emulator works with Android 2.3.1

Main idea . We will create RequireLoginActivity, which will be expanded by all our actions except LoginActivity.

When calling the onResume function, you need to fix three cases:

  • Moving from one RequireLoginActivity to another RequireLoginActivity using startActivity.
  • Going from one RequireLoginActivity back to the previous RequireLoginActivity, completing the current activity.
  • Returning to RequLoginActivity after hiding it (we must show the login here!)

The main idea of ​​my solution is to have 2 counters: the number of started actions ( startCounter ) and the number of paused actions ( pauseCounter ). Every time an action begins, we increase startCounter . Similarly, when an action is paused, pauseCounter should be incremented. In our onResume function, we decide whether to go to the sign by comparing 2 counters. We will get gotoLogin () if the two counters are equal!

Let me explain: In any case, case 1 can be captured simply because when starting new actions, our startCounter will always be greater than pauseCounter by 1. This is true because we will always have one additional activity started, but not suspended.

In addition, case 3 is easily captured, because as soon as you leave our application, say, using the HOME button, we will increase the pauseCounter , and 2 counters will become equal. When the application is resumed, onResume will solve gotoLogin ().

Case 2 is a bit complicated, but simple. The trick is to override the finish () function and halve the startCounter and pauseCounter . Remember that onPause is called when the operation completes and our counters are equal. Now, by decreasing startCounter once and pauseCounter twice, we will eventually return to the counts of the previous action, and startCounter will remain larger than pauseCounter by 1 when resuming the previous action.

+2
source

If you understand correctly, your goal is for users to re-enter their username and password when they return to your application. Therefore, I think that the most logical way to achieve this would be to add a check on all your onResume() actions to find out if you have a username and password, and if not, just go to login activity. The easiest way is to have BaseActivity that implements validation and allow all your other actions (except spash and login) to inherit from this BaseActivity.

in pseudo-java code

 class BaseActivity extends Activity { onResume() { super.onResume(); if (!havingUsernameAndPassword()) { startActivity(loginActivity); finish(); } } } class AnyOfYourActivitiesExceptSpashAndLogin extends BaseActivity { onResume() { super.onResume(); // ... further code } // ... further code } 

The implementation of havingUsernameAndPassword() , of course, depends on how you store the username and password in your login activity. A very simple way would be to store them in some static members of the class, so they will survive as long as the application is running.

Update: A More Concrete Example

I gave a new example, which also shows how you can save login information for a login, so you can check it later. Actually, it would be even more reasonable to have only the “loggedIn” flag and some user ID, but it depends on your implementation, so I will stick with the username / password here.

 class SimpleDataHolder { public static String username = null; public static String password = null; } class LoginActivity extends Activity { // ... // when user has entered valid username/password, store them in SimpleDataHolder: SimpleDataHolder.username = username; // <-- store username entered SimpleDataHolder.password = password; // <-- store password entered } class BaseActivity extends Activity { onResume() { super.onResume(); if (SimpleDataHolder.username == null || SimpleDataHolder.password == null) { startActivity(loginActivity); // <-- go to login finish(); // <-- end current activity } } } class AnyOfYourActivitiesExceptSpashAndLogin extends BaseActivity { // ... your existing code (if any) onResume() { super.onResume(); // <-- this calls BaseActivity.onResume() which checks username/password // ... your existing code (if any) } 
+7
source

The application CANNOT redirect the home button without changing the framework code. Sorry, maybe NOT ...

+4
source

For your second update problem, I would suggest overriding the OnResume () method, but you have to be careful what you do in it. I also suggest that you learn how the Android life cycle works .

+4
source

My efforts can help you, I successfully redefined the HOME button (under Android 4.0)

You can format the code according to your requirements.

Reply to SO

Source at GITHUB

How can you now control the Home button so that you can easily create your own logic to execute the application flow.

this is the event you are aiming for

 @Override public boolean dispatchKeyEvent(KeyEvent event) { if ( (event.getKeyCode() == KeyEvent.KEYCODE_HOME) && isLock) { //Logic when Home button pressed return true; } else return super.dispatchKeyEvent(event); } 

In the hope that this will exactly meet our requirements.

Note. All this for capturing the HOME button for others you can control with

+3
source

This is my suggestion:

Have a key in SharedPreferences called exit . In onCreate() set the output value to false

 public void onCreate(Bundle ..) { SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor=preferences.edit(); editor.putString("exit","false"); editor.commit(); ..... } 

then in onResume() check the value of exit . If this is true, take the user to the login screen, do nothing else.

 public void onResume() { super.onResume(); SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context); String exit=preferences.getString("exit",""); if(exit.equals("true")) { Intent i=new Intent(this_activity.thi,login_activity.class); startActivity(i); finish() } } 

then in onPause() set the value of exit to true .

 public void onPause() { super.onPause(); SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor=preferences.edit(); editor.putString("exit","true"); editor.commit(); } 

You said you took care of the backbutton . Then it should do it. Your application will always be returned to the login screen.

+3
source

Another workaround would be to create an activity (FinisherActivity) and end the call () in the onCreate () method. Then, when you need to complete the action when you press the Home or Back button and prevent it from remaining on the stack, use Intent to call FinisherActivity. But don't forget setFlags for Intent.FLAG_ACTIVITY_CLEAR_TOP intent ... I know this is not an efficient approach, but it should work.

+2
source

Actually, I don’t think that I’m sure what exactly you are asking is if you want to press the Home Key built into your Android device and get started?

Listener for beginners

Try the following: if it works then amazingly, simply with the intention here to trigger your login activity.

 @Override public boolean dispatchKeyEvent(KeyEvent e) { if (e.getKeyCode() == KeyEvent.KEYCODE_HOME) { Toast.makeText(MainActivity.this, "Home Key is pressed Toast.LENGTH_LONG).show(); return true; } Toast.makeText(MainActivity.this, "Didnt work", Toast.LENGTH_SHORT) .show(); return super.dispatchKeyEvent(e); }; 
+1
source

You cannot override the default behavior in the home button. You will achieve the desired result by clicking the "Back" button, the default "Home" button is the "Home screen". My suggestion Override the back button. Then, using the intention and settings flags, you can go to the login screen.

  @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub super.onKeyDown(keyCode, event); switch(keyCode) { case KeyEvent.KEYCODE_BACK: Intent i= new Intent("yourpackage.login"); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |Intent.FLAG_ACTIVITY_NO_HISTORY); startActivity(i); finish(); break; } return super.onKeyDown(keyCode, event); } 
+1
source

what you ask contradicts how android works.

when the user clicks the home button, he expects that when he returns to the application, everything will remain as it was before, unless he was there for a long time or if he launched a resource-consuming application.

it is as if in the windows, when you press ALT + TAB, you will not expect to log in to the mail client (either in the messenger or in any other application).

in any case, you can use onWindowFocusChanged along with any function functions (onResume, onStart, onRestart, onPause, onStop, ...) and handle only the appropriate cases that you want to use.

+1
source

this is not possible because the home button is exclusive for invoking the launch application, but you can make your application to launch the application running in kiosk mode, for example, see it and it .

to enable activity in startup activity add this on itentfilter in manifest.xml

 <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.HOME" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> 
+1
source

Your code is almost correct: to clear the activity stack when the application starts, you must add android:clearTaskOnLaunch="true" to your root activity , which is Splash , not Login (this will be the first one working, see this question on determining root activity )!

From the documentation:

This attribute only makes sense for actions that start a new task (root activity); It is ignored for all other actions in Task.

So, if you move the attribute in the manifest from Login to Splash , it should work, your application will always be launched using the pop-up screen.

UPDATE: To restart the application even with incoming calls, screen locks or notifications, you need to add android:noHistory="true" (docs here ) to all your other actions or call finish() in all of your onPause() methods.

It’s worth noting that our answers are so different and complicated, because what you want to achieve is completely contrary to the concepts of Android Android (for example, here is a good article on exiting applications), so really, do nothing of the kind outside your private application .

+1
source

It is difficult to say exactly what you are asking, however I believe that this is what you are looking for: How to make the screen saver not load if the application is already in memory . To summarize my post:

This is a design issue. Your launch activity should not be your screensaver activity. Instead, open your burst activity in your main onCreate method. Thus, if it is open, onCreate is called and the splash screen is displayed. Otherwise, if the application simply resumed, which calls onResume, there would be no call to open the screensaver activity.

Then you can change your manifest to this:

 <activity android:name=".ui.MainActivity" android:noHistory="true" android:screenOrientation="portrait" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <activity android:name=".ui.SplashActivity"/> 
+1
source

Have you tried the android: noHistory activity attribute (for each of your actions) in the Android manifest? This is similar to what you are looking for.

+1
source

You should call finish() in all of your onPause() actions, except for input activity. And you can call startActivity(new Intent (this, LoginPage.this)) in your onResume() method. Therefore, whenever actions come to the fore, the user will again be redirected to the login page.

+1
source

Source: https://habr.com/ru/post/927611/


All Articles