6

I have an app start by Splash activity screen for 5 seconds Then open Login activity screen then after you put correct user and password open the Menu activity (listActivity) then each row click open MyCity activity.

UPDATE:

What I'm trying to get is: where ever you are in my app, and you go away from my app for any reason not only when you press the home button but also FOR EXAMPLES:

  1. You press home button to check another app then want to return to my app .

  2. You have notification show new message on whatsup or email, you open your whatsup or open email, then return to my app .

3- You left your mobile for period of time then you want to check my app again .

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

what I mean any time you go away my app for any reason but whithout press back back back button which will exit the whole app then want to return again to my app must open to you the login screen to re enter your usename and password again.

I Called finish(); for both Splash activity and Login activity .

I tried:android:clearTaskOnLaunch="true" in the Login activity in the manifest but it doesn'thing.

Any advice will be appreciated,

PLEASE WRITE FULL WORKING CODE.

LOGIN 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 reached halfway to what i want but still some steps i can't achieve it explained as below :

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

and prevent back button behaviour on Menu activity :

  @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 press home button away my app then return to my app its:

go directly to Login activity.

but main goal now is :

if :

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

or

OPENED MESSAGE from notification

or

OPENED EMAIL from notification

or

you have CALL and answer it ,

THEN return to my app it does not go to login activity but you will return to the page where you was befor .

ANY ADVICE PLEASE , THANKS.

THIED UPDATE :

i used another code for override home button and control the back button rather than appling :android:clearTaskOnLaunch="true" to Splash activity in manifest , just apply the down code to 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);}
androidqq6
  • 1,526
  • 2
  • 22
  • 47
  • 3
    you can't expect someone to write full working code. Suggestions and ideas will be given. You need to implement them in your way. – Raghunandan Oct 28 '12 at 07:05
  • @Raghunandan , im still learning java and android development , i tried what i can do , others im asking about it to learn more and more , thanks for all . – androidqq6 Oct 28 '12 at 19:39
  • May be a duplicate: http://stackoverflow.com/questions/13112329/how-to-make-splash-screen-not-to-load-if-app-is-already-in-memory – Phil Oct 29 '12 at 05:24
  • 1
    Is it me or are you asking to override Android's multitask/activities mentality/fundamentals/rules/design just to keep your app on foreground?.. – shkschneider Oct 30 '12 at 16:13
  • @downvoter can you give me reason for down vote please. – androidqq6 Oct 30 '12 at 20:17
  • You cannot force anybody to stare at your app's login screen. You can override everything except Home button **FOR THIS EXACT REASON**. However, you can keep track of your current application's state and act accordingly in the overriden onBackPressed() to return to where you want. Home button will always work the way it works and you should give up on trying to change it's behaviour. – Shark Oct 31 '12 at 17:23
  • or just launch your Login activity() in the onResume() ? – Shark Oct 31 '12 at 17:25
  • @androidqq6 : check out my answer - http://stackoverflow.com/questions/12868396/always-return-to-login-screen/13189099#13189099 – Ashwin Nov 02 '12 at 07:51

15 Answers15

8

If I understand you right, your goal is that users have to enter username and password again, when they come back to your App. So I think the most logical way to achieve this would be to add a check in all your Activities onResume() method to see if you have a username and password and if not, simply go to the login activity. Easiest way would be to have a BaseActivity implementing the check and let all your other activities (except for spash and login) inherit from that 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 class members, so they'd survive as long as the Application runs.

Update: a more concrete example

I made a new example also showing how you can save the login data on login to be able to check it later on. Actually it would make even more sense to have just a flag 'loggedIn' and some user-id, but that depends upon your implementation, so I'll stick with 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)
}
Ridcully
  • 23,362
  • 7
  • 71
  • 86
  • please can you explain more with writing some more codes , thanks . – androidqq6 Nov 04 '12 at 06:45
  • my dear friend i create BaseActivity as below :class BaseActivity extends Activity { protected void onResume() { super.onResume(); 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(BaseActivity.this, Login.class); startActivity(intent); finish();}}}} – androidqq6 Nov 04 '12 at 07:28
  • regard the second part of your code (class AnyOfYourActivitiesExceptSpashAndLogin extends BaseActivity { onResume() { super.onResume(); // ... further code } // ... further code }) , i will add it to all my classes exept login and splash class but what to write instead further code . sorry for sally question but have no experiance , thanks – androidqq6 Nov 04 '12 at 07:32
  • I think you misunderstood my suggestion a little bit. You shouldn't check EditText fields in the BaseActivity, as those probably will only exist in your LoginActivity. I meant, that you should store the username/password you get in your LoginActivity somewhere in your App, e.g. in static member variables, so you could access and check them in all the other Activities. I'll add a more concrete example to the answer. – Ridcully Nov 04 '12 at 19:10
  • @my dear sir , i have little experiance , i appreciate your help , if you explaine it by code i will be thankfull indeed my master – androidqq6 Nov 04 '12 at 19:21
  • I added a more concrete example in my answer. Just had a closer look at the Logn activity you posted -- this cannot work mate. You check the input of username/password in your onCreate method, but when this method runs, the user had no chance yet to enter anything. You'll have to add some kind of button (e.g. Login) to your layout and check username/password when the user clicks that button. – Ridcully Nov 04 '12 at 19:26
  • my dear do you mean the new code you post here will be all in Login activity only , also i update my post with all project class please take alook on it , thanks – androidqq6 Nov 04 '12 at 21:35
  • im sorry i think i cant do it by my self depend on my little experiance , thanks alot – androidqq6 Nov 04 '12 at 21:59
  • What you want in your question (going back to Login when the device is locked or after a phone call, etc.) isn't good behaviour. You wouldn't want this of other apps, do you? You just have to remember that the user is logged in (and who he is), so the user who already has logged in can continue his work after receiving a phone call or whatever. And to remember that a user is logged in, save this information in e.g. the SimpleDataHolder class I suggested. If you have so little experience with Android, maybe you should first do some simpler Apps without user authentication and stuff. – Ridcully Nov 05 '12 at 07:16
  • @Ridcully first of all i appreciate your endless help and support , second this app will be private ans will not publish , iknow its against the logic and customwr needs , last i will try and try with your code till it work with me , thanks indeed ,+1 upvote to your answer – androidqq6 Nov 05 '12 at 09:41
4

An application CANNOT re-route the home button without modifying the framework code. Sorry this is NOT possible...

JoxTraex
  • 13,423
  • 6
  • 32
  • 45
4

To your second update problem I would suggest overriding the OnResume() method, but you must be careful with what you do in it. I would also suggest you study on how the android lifecycle works.

Gabriel Netto
  • 1,818
  • 1
  • 16
  • 26
3

This is my suggestion :

Have a key in SharedPreferences called exit. In the onCreate() set the value of exit 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 it is true, take the user to the login screen else do not do anything .

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 that you have taken care of the backbutton. Then this should do it. Your app will always return to the login screen.

Ashwin
  • 12,691
  • 31
  • 118
  • 190
  • thanks for your answer , im working to adjust some behaviour of my apk with your code , i will replay you later , thanks – androidqq6 Nov 03 '12 at 00:28
  • @androidqq6 : yeah do replay, because I think it should work. – Ashwin Nov 03 '12 at 03:08
  • @ Ashwin when i test your code lets say 4 times , first when press home button in Menu activity then return to my app then press power button in Menu activity to lock screen then return to my app and again for second activity so we pause and resume 4 times , finally my question : im now in Login activity (if i press back button it must exit the app but actually it shift me to Login screen 4 times before it exit app , any advice my friend , thanks – androidqq6 Nov 03 '12 at 15:45
  • which mean resume methoid after calling Login activity which start second activity (Menu) , it didnot finish the login activity it self after start the second activity – androidqq6 Nov 03 '12 at 15:47
  • @androidqq6 : what happened when you pressed the home button and came back? did it go to the login screen or the original activity? – Ashwin Nov 03 '12 at 16:12
  • it go to Login but if you are in Login screen and press back the normal action is exit the app but its not by back it go to anther login screen then another login screen and so on till exit the app – androidqq6 Nov 03 '12 at 16:16
  • @androidqq6 : ok..then in your manifest add this to your login_screen activity - android:launchMode="singleTask" – Ashwin Nov 03 '12 at 16:19
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/19018/discussion-between-ashwin-and-androidqq6) – Ashwin Nov 03 '12 at 16:27
  • @androidqq6 : see the chat, I have given you a code. It worked for me. I tried pressing the home button and backbutton and power button in menu activity and in all cases, next time login screen was shown . Try to paste the same code. – Ashwin Nov 04 '12 at 08:51
  • i past it , we have two issue , 1- when you are in menu and press home button or power button or you get message in notification it exit the app i want it to go directly to login activity when i return to my app again not exit , 2- apply same code to second activity when home button or power pressed it return to menu activity not login , thanks any advice – androidqq6 Nov 04 '12 at 09:48
  • @androidqq6 : isn't login your first activity? the activity that is shown when the icon is pressed? – Ashwin Nov 04 '12 at 09:50
  • Splash is first which is LAUNCHER – androidqq6 Nov 04 '12 at 10:00
  • @androidqq6 : oh..then wait I will try something else. – Ashwin Nov 04 '12 at 10:36
2

Another workaround will be to create a activity(FinisherActivity) and call finish() in its onCreate() method. Then whenever you need to finish a activity on pressing the home button or back button and prevent it from staying on the stack just use an Intent to call FinisherActivity . But remember to setFlags for the intent to Intent.FLAG_ACTIVITY_CLEAR_TOP...I know its not an efficient approach, but it should work..

anz
  • 1,317
  • 2
  • 13
  • 25
2

Here is the solution I came up with.

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

Tested on:

  • Samsung S3 running android 4.0.4
  • Emulator running android 2.3.1

The basic idea: We will create a RequireLoginActivity which will be extended by all our activities except the LoginActivity.

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.

Sherif elKhatib
  • 45,786
  • 16
  • 89
  • 106
  • thnks alot sherif for your answer , i tyied you solution ,its overcome two things :1-press home button return to login activity .2- press power return to login activity which is good but still : 1- you recive call and answwer it then by back button you will be in second activity not login activity .2- you have notification that recived message or email and open it from notification bar then back button return you also to second activity not login activity as i wish , any advice regarding this two unsolved point , thanks my master – androidqq6 Nov 01 '12 at 21:14
  • @androidqq6 I just downloaded the project I have in my blog. I tested it on a 2.3.1 emulator. When I get a phone call and return to my app, I get the login screen. Same thing happens when I leave the app and go to any notifications. Please download and test the sample project in http://www.sherif.mobi/2012/11/application-which-always-requires-login.html – Sherif elKhatib Nov 01 '12 at 23:46
  • i already did and tested on galaxy s 1 run gingerbread , it acts as i told you , tomorrow i will test it on galaxy s 3 run ice cream and reply back to you , thanks – androidqq6 Nov 02 '12 at 00:29
  • ok its getting late here. I will try to fix this tomorrow maybe test it more. I'd like this to work (: – Sherif elKhatib Nov 02 '12 at 00:34
  • I have tested this on S3. Called the device and when the app resumed, it showed the login screen. – Sherif elKhatib Nov 02 '12 at 09:54
  • its work in ginger bread but im adjusting your code to my full project then i will reply you my friend , thanks – androidqq6 Nov 03 '12 at 15:50
  • im try to apply your codes to my project ,regard Class AnotherActivity it required ( public class AnotherActivity extends RequireLoginActivity {) but my class has extends ListActivity as : (public class Menu extends ListActivity) and without write RequireLoginActivity to refer to base class its not gave the needed behaviour so how to fix this . – androidqq6 Nov 04 '12 at 06:42
  • simple solution: Copy `RequireLoginActivity` and create `RequireLoginListActivity`. change `RequireLoginListActivity extends Activity` to `RequireLoginListActivity extends ListActivity`. Now use `RequireLoginListActivity` instead of `ListActivity` – Sherif elKhatib Nov 04 '12 at 12:10
  • Good explanation and follow up.\ – Mohammed Azharuddin Shaikh Nov 05 '12 at 05:10
  • @Sherif elKhatib my friend im trying to apply your code but i have force close and error regard this :((RequireLoginApplication)getApplication()).reset();} . would you please help me , thanks – androidqq6 Nov 06 '12 at 11:57
  • You need to add to your manifest ``. Use the correct name (: – Sherif elKhatib Nov 06 '12 at 12:15
  • @Sherif elKhatib yess when i recheck all your project i found that i miss this point coz my logcat point to ClassCastException now its ok , thanks my dear but actually i cant understand this point about ClassCastException and adding: android:name=".RequireLoginApplication" to manifest , please can you explain it to me if you would ,thanks – androidqq6 Nov 06 '12 at 13:23
  • Yes, each app has an Application class: This class is singleton, only one instance exists. You can override it, by creating a class that extends Application and specifying its name like I explained. – Sherif elKhatib Nov 06 '12 at 13:30
  • @Sherif elKhatib my dear i create:public class RequireLoginListActivity extends ListActivity,my Menu Class i did:public class Menu extends RequireLoginListActivity,that ok Menu class return to Login Class when leave app but it cause problem which is when click any row to open MyCity activity its open but when you click back button to return to Menu it doesnot,it go directly to Login, – androidqq6 Nov 07 '12 at 17:55
  • @Sherif elKhatib anther thing when apply RequireLoginListActivity to MyCity as:public class MyCity extends RequireLoginListActivity (MyCity class originally Activity not ListActivity) and run app then click any row in Menu Class to open MyCity Activity it gave force closeوthis logcat : java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.demo/com.ttest.demo.MyCity}:java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'.please any advice,thanks – androidqq6 Nov 07 '12 at 17:56
  • MyCity activity should extend RequireLoginActivity – Sherif elKhatib Nov 07 '12 at 18:14
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/19238/discussion-between-sherif-elkhatib-and-androidqq6) – Sherif elKhatib Nov 07 '12 at 19:03
  • @Sherifelkhatib you r right i create another class :RequiredLoginActivity and refer MyCity class to it and work fine i wll apply your code to rest of my project and forgive me if i will need more help from you my master sir .thanks – androidqq6 Nov 07 '12 at 20:46
1

Actually I dont think i'm sure what exactly your asking, Do you want to press the Home Key built into your android device and start an activity?

Homekey listener

Try This: if it works then awesome, just through an intent in there to call 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);
    };
The Tokenizer
  • 1,564
  • 3
  • 29
  • 46
1

You can't override the home button default behaviour. You achieve the desired result by clicking back button, Home button's default behaviour is to goto Home Screen. My suggestion Override Back Button. Then using intent and setting flags properly you can goto 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);
    }
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • Intent i= new Intent("yourpackage.Login"); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |Intent.FLAG_ACTIVITY_NO_HISTORY); startActivity(i);finish(); Do this on Key Down. Clear all Activities goto login screen. This should help you. – Raghunandan Oct 23 '12 at 04:19
  • NOTHING HAPPEN , maybe i miss some thing in writting my code regarding your answer , would you please update it with full working code also i will update my post with login activity , thanks alot – androidqq6 Oct 27 '12 at 23:35
  • Thanks alot for your answer , please check the updeted post , thanks – androidqq6 Oct 28 '12 at 15:09
  • 1)http://developer.android.com/training/basics/activity-lifecycle/starting.html. Please go through the note at he end.2) You need to know how to manage your activity lifecycle. 3)http://developer.android.com/training/basics/activity-lifecycle/index.html.3)http://developer.android.com/guide/components/tasks-and-back-stack.html. Go through the links especially the last one. I am sure it will help you. – Raghunandan Oct 28 '12 at 15:22
  • http://developer.android.com/training/basics/activity-lifecycle/starting.html. Here's the link. Also have a look at this link. http://developer.android.com/guide/components/tasks-and-back-stack.html – Raghunandan Oct 28 '12 at 15:30
  • android:noHistory=["true" | "false"]. http://developer.android.com/guide/topics/manifest/activity-element.html. Activity has no history in the stack if its true. Depending on your need define the same in manifest. Hope the above links will help you. – Raghunandan Oct 28 '12 at 15:35
  • http://tech.chitgoks.com/2011/09/05/how-to-override-back-home-button-in-an-android-app/. This might help you. – Raghunandan Oct 28 '12 at 18:56
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/18698/discussion-between-raghunandan-and-androidqq6) – Raghunandan Oct 29 '12 at 06:36
1

what you are asking is against the way that android works .

when the user presses the home button , he expects that when he returns to the app , everything will stay as it was before , unless he wasn't there for a long time or if he ran a resource consuming app .

it's as if on windows , when you click ALT+TAB , you won't expect to see login on the email client (or messenger , or whatever app you use) .

in any case , you can use onWindowFocusChanged together with any of the functions of activity (onResume,onStart,onRestart,onPause,onStop,...) , and handle only the relavant cases you wish to use .

android developer
  • 114,585
  • 152
  • 739
  • 1,270
  • im fully agree with you but this app will not publish , its private app to me and i need to do that , would you please write some code to achieve that please , coz im new in android development , thanks – androidqq6 Oct 22 '12 at 23:56
  • investigate the events i've written about (write in the logs if you wish) , and capture the scenario that you wish to handle , and then add the logic you want... – android developer Oct 23 '12 at 12:02
  • Thanks alot for your answer , please check the updeted post , thanks – androidqq6 Oct 28 '12 at 15:08
1

it's not possible because the home button is exclusive to call launcher application, but you can do your app a launcher application, running in kiosk mode for example, see it and it.

to turn a activity on launcher activity add this on itentfilter on 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>
Community
  • 1
  • 1
ademar111190
  • 14,215
  • 14
  • 85
  • 114
1

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

From the documentation:

This attribute is meaningful only for activities that start a new task (the root activity); it's ignored for all other activities in the task.

So if you move the attribute in the manifest from Login to Splash, it should work, your application will always start with the splashscreen.

UPDATE: To restart your app even on incoming calls, screen lock or notifications, you have to add android:noHistory="true" (docs here) to all your other activities, or call finish() in all their onPause() methods.

It's worth mentioning that our answers are so different and complicated because what you want to achieve is totally against core Android concepts (for example, here is a good article on exiting apps), so really, don't do anything like this outside your private app.

Community
  • 1
  • 1
molnarm
  • 9,856
  • 2
  • 42
  • 60
  • Thanks alot for your answer , please check the updeted post , thanks – androidqq6 Oct 28 '12 at 15:09
  • you are right i applied android:clearTaskOnLaunch="true" to splash in manifest and prevent back botton in Menu activity and removed finish(); from login activity so i get half way to my need the rest you CAN check it in my SECOND UPDATE , PLEASE,THANKS. – androidqq6 Oct 30 '12 at 17:08
1

It is difficult to tell exactly what you are asking, however I believe this is what you are looking for: How to make splash screen not to load if app is already in memory . To summarize my post there:

This is a design problem. Your launcher activity should not be your splash screen activity. Instead, open your splash activity in your main activity's onCreate method. That way, if it is opened fresh, onCreate is called and the splash screen is shown. Otherwise, if the app is merely resumed, which calls onResume, there would be no call to open the splash screen 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"/>
Community
  • 1
  • 1
Phil
  • 35,852
  • 23
  • 123
  • 164
  • my problem not in reload splash screen , i want any time you left my app by any reason mentioned above in my post and you want to return to my app , it force you to Login screen to re enter user name and password each time , thanks – androidqq6 Oct 29 '12 at 14:51
1

Have you tried the android:noHistory activity attribute (for each of your activities) in the Android Manifest? That sounds like exactly what you are looking for.

Phil
  • 35,852
  • 23
  • 123
  • 164
1

You should call finish() in all your activities' onPause() methods except Login activity. And you can call startActivity(new Intent (this, LoginPage.this)) in their onResume() method. So whenever the activities will come to foreground, user will be redirected to Login page again.

MysticMagicϡ
  • 28,593
  • 16
  • 73
  • 124
0

My little efforts may helps you, I had successfully Override the HOME button(below Android 4.0)

You can mould the code according to your requirement.

Answer on SO

Source at GITHUB

As you can now handle Home button so you can easily create your own logic to perform you Application flow.

this is you targetted event

@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);
    }

Hoping this will definitely going to meet our requirements.

Note: All this is for capturing Home Button for others you can manage

Community
  • 1
  • 1
Mohammed Azharuddin Shaikh
  • 41,633
  • 14
  • 96
  • 115
  • thanks alot for your answer i already test it , it override the home button , great , but as you saw in my SECOND UPDATE i already solve the problem of home button , but others issues i cant , tried with onpause(); methoid but i cant get it , i agree it my be simple for others but for me with no experience in jave or android coz in just starting learning java nowadays, any more advice my friend , thanks – androidqq6 Nov 02 '12 at 22:18
  • downvote for KEYCODE_HOME the Logic when Home button pressed will never be executed (but back in 2012 it was a solution - just want to indicate that the code is outdated) – Martin Pfeffer Apr 03 '17 at 18:14
  • 1
    @MartinPfeffer Agree, but it was working in earlier version of Android, I stated `I had successfully Override the HOME button(below Android 4.0)`(http://stackoverflow.com/questions/10025660/override-home-and-back-button-is-case-a-boolean-is-true/10025904#10025904) – Mohammed Azharuddin Shaikh Apr 04 '17 at 04:11