Action-Bar Back key not working - java

I have made a action-bar back button in my app with:
Settings.java:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
and
AndroidManifest.xml:
<activity android:name=".Settings">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="at.mrminemeet.reviewcheck.MainActivity" />
</activity>
but I experienced that the software-key calls the "onPause" and so but the action-bar one won't do that.
I checked some other posts and so which tell me to try
#Override
public void onBackPressed(){
// stuff
super.onBackPressed();
}
but it didn't do anything. It completly ignores that I added the code.
Did I do anything wrong?
Other posts:
Post 1
Post 2

You need to override onOptionsItemSelected() and use the ID android.R.id.home to override the up botton action. What I would do is call the onBackPressed() function when the home button is pressed. A sample code will look like this
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
getActivity().onBackPressed()
return true;
}
return super.onOptionsItemSelected(item);
}
For further details, you can see the Android documentation on providing up Navigation
Note that the answer below was written before the original question was edited. I am leaving it here and have answered the question above.
Original Answer:
If you are specifically talking about
#Override
public void onBackPressed(){
super.onBackPressed();
// stuff
}
then the problem lies that you call super.onBackPressed() before your code. This call will go back to the previous activity or exit the app depending on which activity it is called on. Instead change it to-
#Override
public void onBackPressed(){
//your code to do stuff here
super.onBackPressed();
}
and it will first execute your code and then go back.

Related

Android: How to go back previous application on back button click [duplicate]

I want to do something simple on android app.
How is it possible to go back to a previous activity.
What code do I need to go back to previous activity
Android activities are stored in the activity stack. Going back to a previous activity could mean two things.
You opened the new activity from another activity with startActivityForResult. In that case you can just call the finishActivity() function from your code and it'll take you back to the previous activity.
Keep track of the activity stack. Whenever you start a new activity with an intent you can specify an intent flag like FLAG_ACTIVITY_REORDER_TO_FRONT or FLAG_ACTIVITY_PREVIOUS_IS_TOP. You can use this to shuffle between the activities in your application. Haven't used them much though. Have a look at the flags here: http://developer.android.com/reference/android/content/Intent.html
As mentioned in the comments, if the activity is opened with startActivity() then one can close it with finish().
If you wish to use the Up button you can catch that in onOptionsSelected(MenuItem item) method with checking the item ID against android.R.id.home unlike R.id.home as mentioned in the comments.
Try Activity#finish(). This is more or less what the back button does by default.
Just write on click finish(). It will take you to the previous Activity.
Just this
super.onBackPressed();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
This will get you to a previous activity keeping its stack and clearing all activities after it from the stack.
For example, if stack was A->B->C->D and you start B with this flag, stack will be A->B
Just call these method to finish current activity or to go back by onBackPressed
finish();
OR
onBackPressed();
Are you wanting to take control of the back button behavior? You can override the back button (to go to a specific activity) via one of two methods.
For Android 1.6 and below:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
// do something on back.
return true;
}
return super.onKeyDown(keyCode, event);
}
Or if you are only supporting Android 2.0 or greater:
#Override
public void onBackPressed() {
// do something on back.
return;
}
For more details: http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html
Try this is act as you have to press the back button
finish();
super.onBackPressed();
Add this in your onCLick() method, it will go back to your previous activity
finish();
or You can use this. It worked perfectly for me
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if ( id == android.R.id.home ) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
if you want to go to just want to go to previous activity use
finish();
OR
onBackPressed();
if you want to go to second activity or below that use following:
intent = new Intent(MyFourthActivity.this , MySecondActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//Bundle is optional
Bundle bundle = new Bundle();
bundle.putString("MyValue1", val1);
intent.putExtras(bundle);
//end Bundle
startActivity(intent);
If you have setup correctly the AndroidManifest.xml file with activity parent, you can use :
NavUtils.navigateUpFromSameTask(this);
Where this is your child activity.
Got the same problem and
finish(); OR super.onBackPressed();
worked fine for me, both worked same, but no luck with return
You can explicitly call onBackPressed is the easiest way
Refer Go back to previous activity for details
Start the second activity using intent (either use startActivity or startActivityForResult according to your requirements). Now when user press back button, the current activity on top will be closed and the previous will be shown.
Now Lets say you have two activities, one for selecting some settings for the user, like language, country etc, and after selecting it, the user clicks on Next button to go to the login form (for example) . Now if the login is unsuccessful, then the user will be on the login activity, what if login is successful ?
If login is successful, then you have to start another activity. It means a third activity will be started, and still there are two activities running. In this case, it will be good to use startActivityForResult. When login is successful, send OK data back to first activity and close login activity. Now when the data is received, then start the third activity and close the first activity by using finish.
You can try this:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
All new activities/intents by default have back/previous behavior, unless you have coded a finish() on the calling activity.
#Override
public void onBackPressed() {
super.onBackPressed();
}
and if you want on button click go back then simply put
bbsubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
I suggest the NavUtils.navigateUpFromSameTask(), it's easy and very simple, you can learn it from the google developer.Wish I could help you!
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if ( id == android.R.id.home ) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
Try this it works both on toolbar back button as hardware back button.
There are few cases to go back to your previous activity:
Case 1: if you want take result back to your previous activity then
ActivityA.java
Intent intent = new Intent(ActivityA.this, FBHelperActivity.class);
startActivityForResult(intent,2);
FBHelperActivity.java
Intent returnIntent = new Intent();
setResult(RESULT_OK, returnIntent);
finish();
Case 2: ActivityA --> FBHelperActivity---->ActivityA
ActivityA.java
Intent intent = new Intent(ActivityA.this, FBHelperActivity.class);
startActivity(intent);
FBHelperActivity.java
after getting of result call finish();
By this way your second activity will finish and because
you did not call finish() in your first activity then
automatic first activity is in back ground, will visible.
Besides all the mentioned answers, their is still an alternative way of doing this, lets say you have two classes , class A and class B.
Class A you have made some activities like checkbox select, printed out some data and intent to class B.
Class B, you would like to pass multiple values to class A and maintain the previous state of class A, you can use, try this alternative method or download source code to demonstrate this
http://whats-online.info/science-and-tutorials/125/Android-maintain-the-previous-state-of-activity-on-intent/
or
http://developer.android.com/reference/android/content/Intent.html
Just try this in,
first activity
Intent mainIntent = new Intent(Activity1.this, Activity2.class);
this.startActivity(mainIntent);
In your second activity
#Override
public void onBackPressed() {
this.finish();
}
First, thing you need to keep in mind that, if you want to go back to a previous activity. Then don't call finish() method when goes to another activity using Intent.
After that you have two way to back from current activity to previous activity:
Simply call:
finish()
OR
super.onBackPressed();
To go back from one activity to another by clicking back button use the code given below use current activity name and then the target activity.
#Override
public void onBackPressed() {
// do something on back.
startActivity(new Intent(secondActivity.this, MainActivity.class));
return;
}

Save when back button is pressed

In my android app, when the back button is pressed I want the app to save. This is my code:
#Override
public void onBackPressed() {
super.onBackPressed();
Log.d("VIVZ", counter + "Was Saved");
}
So when i press the back button It exits the app and then when I go back into the app It has not saved.
After 'back' press the Activity is expected to be finished - its instance state is lost. You won't e.g. get onSaveInstanceState() invoked - which is a method helping in preserving activity instance state.
If you want to save app state (if your counter belongs there) it is probably the easiest to use SharedPreferences. Even in that case probably you could consider placing state-saving code in onStop() rather than in onBackPressed()
Try this
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Do your saving code
}
return super.onKeyUp(keyCode, event);
}
Try to use the activity lifecycle methods instead.
#Override
onPause(){
//use some kind of SharedPreferences class or FileOutputStream
//because onPause() is called when the activity is removed from the ui
}

Android: How can I retain the state of an object on back button Action bar and back button of device

I have ActivityA and ActivityB. ActivityB is called from ActivityA.
I wanted to retain the object of ActivityA, when I press back button of ActionBar or back button of device.
I have created a Singleton object to save my object and to get my object.
onPause() I am saving the object and onResume() method I am getting the object.
My problem here is the behaviour is different, the object that I get when back button of Action (in ActivityB) is different from the object that I get when back button of back button is clicked.
Here is the code:
protected void onPause() {
//resetSort();
super.onPause();
MySingleton.getInstance().setMyObject(myObject);
}
#Override
protected void onResume() {
super.onResume();
myObject = MySingleton.getInstance().getMyObject();
}
Here is my manifest file.
<activity
android:name=".ActivityA"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
>
</activity>
<activity
android:name=".ActivityB"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name" >
</activity>
Code from ActivityB:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
Any solution is appreciated. Thanks
The most reliable way is to use SharedPreferences. It's both thread safe and remains even if your app is killed off.
Google's Storage Options guide is also definitely worth a look if you haven't had a chance to review it yet.
To save a String you would use:
String str = "abc";
getSharedPreferences("filename", Context.MODE_PRIVATE).edit().putString("String Name", str).commit();
And then to retrieve it:
String str = getSharedPreferences("filename", Context.MODE_PRIVATE).getString("String Name", "default string")

always return to Login screen

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:
You press home button to check another app then want to return to my app .
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);}
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)
}
An application CANNOT re-route the home button without modifying the framework code. Sorry this is NOT possible...
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.
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.
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:
Jumping from one RequireLoginActivity to another RequireLoginActivity using a flavor of startActivity.
Jumping from one RequireLoginActivity back to a previous RequireLoginActivity by finishing the current activity.
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.
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..
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);
};
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 .
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>
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);
}
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"/>
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.
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.
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.
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

Override back button to act like home button

On pressing the back button, I'd like my application to go into the stopped state, rather than the destroyed state.
In the Android docs it states:
...not all activities have the behavior that they are destroyed when BACK is pressed. When the user starts playing music in the Music application and then presses BACK, the application overrides the normal back behavior, preventing the player activity from being destroyed, and continues playing music, even though its activity is no longer visible
How do I replicate this functionality in my own application?
I think there must be three possibilities...
Capture the back button press (as below) and then call whatever method(s) the home button calls.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
Log.d(this.getClass().getName(), "back button pressed");
}
return super.onKeyDown(keyCode, event);
}
Capture the back button press and then spoof a home button press.
Capture the back button press, then start an Activity of the home screen, effectively putting my application's Activity into the stopped state.
Edit:
I know about services and am using one in the application to which this problem is related. This question is specifically about putting the Activity into the stopped state rather than the destroyed state on pressing the back button.
Most of the time you need to create a Service to perform something in the background, and your visible Activity simply controls this Service. (I'm sure the Music player works in the same way, so the example in the docs seems a bit misleading.) If that's the case, then your Activity can finish as usual and the Service will still be running.
A simpler approach is to capture the Back button press and call moveTaskToBack(true) as follows:
// 2.0 and above
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
// Before 2.0
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
I think the preferred option should be for an Activity to finish normally and be able to recreate itself e.g. reading the current state from a Service if needed. But moveTaskToBack can be used as a quick alternative on occasion.
NOTE: as pointed out by Dave below Android 2.0 introduced a new onBackPressed method, and these recommendations on how to handle the Back button.
Use the following code:
public void onBackPressed() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
If you want to catch the Back Button have a look at this post on the Android Developer Blog. It covers the easier way to do this in Android 2.0 and the best way to do this for an application that runs on 1.x and 2.0.
However, if your Activity is Stopped it still may be killed depending on memory availability on the device. If you want a process to run with no UI you should create a Service. The documentation says the following about Services:
A service doesn't have a visual user interface, but rather runs in the background for an indefinite period of time. For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it.
These seems appropriate for your requirements.
try to override void onBackPressed() defined in android.app.Activity class.
if it helps someone else, I had an activity with 2 layouts that I toggled on and off for visibilty, trying to emulate a kind of page1 > page2 structure. if they were on page 2 and pressed the back button I wanted them to go back to page 1, if they pressed the back button on page 1 it should still work as normal. Its pretty basic but it works
#Override
public void onBackPressed() {
// check if page 2 is open
RelativeLayout page2layout = (RelativeLayout)findViewById(R.id.page2layout);
if(page2layout.getVisibility() == View.VISIBLE){
togglePageLayout(); // my method to toggle the views
return;
}else{
super.onBackPressed(); // allows standard use of backbutton for page 1
}
}
hope it helps someone,
cheers
Working example..
Make sure don't call super.onBackPressed();
#Override
public void onBackPressed() {
Log.d("CDA", "onBackPressed Called");
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
}
In this way your Back Button act like Home button . It doesn't finishes your activity but take it to background
Second way is to call moveTaskToBack(true); in onBackPressed and be sure to remove super.onBackPressed
Even better, how about OnPause():
Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume().
When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure toenter code here not do anything lengthy here.
This callback is mostly used for saving any persistent state the activity is editing and making sure nothing is lost if there are not enough resources to start the new activity without first killing this one.
This is also a good place to do things like stop animations and other things that consume a noticeable amount of CPU in order to make the switch to the next activity as fast as possible, or to close resources that are exclusive access such as the camera.
Override onBackPressed() after android 2.0.
Such as
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
I have use #Mirko N. answser using made the new Custom EditText
public class EditViewCustom extends EditText {
Button cancelBtn;
RelativeLayout titleReleLayout;
public EditViewCustom(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public EditViewCustom(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EditViewCustom(Context context) {
super(context);
}
public void setViews(Button cancelBtn,RelativeLayout titleReleLayout){
this.cancelBtn = cancelBtn;
this.titleReleLayout = titleReleLayout;
}
#Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
Log.d("KEYCODE_BACK","KEYCODE_BACK");
cancelBtn.setVisibility(View.GONE);
this.setFocusableInTouchMode(false);
this.setFocusable(false);
titleReleLayout.setVisibility(View.VISIBLE);
return super.onKeyPreIme(keyCode, event);
}
return super.onKeyPreIme(keyCode, event);
}
}
Then set data from your activity
searchEditView.setViews(cancelBtn, titleRelativeLayout);
Thank you.
I've tried all the above solutions, but none of them worked for me. The following code helped me, when trying to return to MainActivity in a way that onCreate gets called:
Intent.FLAG_ACTIVITY_CLEAR_TOP is the key.
#Override
public void onBackPressed() {
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}

Categories

Resources