Destroy an activity when back button is pressed? - android

I have an app that allows user to select a txt file from a list and then goes off to the internet to get the contents of that file. All works well except when the user accidentally or deliberately presses the hardware back button to go and see the list again.
Now, when the user clicks a new item from the list (a new file that is), instead of loading a the new file, the app continues off from where it was suspended.I do not want that to happen. I know this is related to the life cycle of the activity.
How do I make sure that it loads the new file rather than continuing from where it left off ?

I suppose you're loading the file in onCreate(). You should do that in onResume() instead.
Do not force Activities to close (e.g. use finish()). First, this does not guarantee the Activity will be closed, and second, this is better left to Android to decide.

Another Method to kill an activity is by calling following method.
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}

You can override the onBackPressed method in the activity and call finish() to get the desired outcome.

You just need to finish your activity in onBackPressed() method by calling activity.finish();

To destroy activity on back press, use this code.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Destroys activity.
finish();
}

Related

How to disable or override the oncreate method in Android

I have 3 pages in my application. Page A,B,C. When i click next button in A page the page will navigate to B page. In that page there will be some request and response process and Progress indicator will happen. Then when i click next the page will navigate to C page. There also some request and response process and Progress indicator process will happen. Now my problem is when i click back button from page C The page is navigate to B page. But the request response process and progress indicator process is working. Here i don't want do this process when i click back button. Now i have try like this:-
#Override
protected void onStart() {
super.onStart();
Log.v(this.getClass().toString(),"onStart");
}
Here the request and response process is not working when i click back button. But the progress indicator is loading. This progress indicator is continuously rolling. How to disable all the functions. I just want to go back. Do not do any other work. Please help me to solve this issue. Sorry For the poor English..
As you can see, you add a flag Intent.FLAG_ACTIVITY_CLEAR_TOP. This flag will clear all previous activities.
Intent.FLAG_ACTIVITY_CLEAR_TOP - If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.
And also you finish the current activity, so navigating back to page B call B's onCreate method where you have those requests and process stuff. Avoid adding flag and finish() methods.
You don't want to override the onCreate() method for this usecase, why would you do that? The activity is created, and the process will run. What you want is to override the onBackPressed() method, so that you cannot exit the Activity until the process is complete.
Similarly to these: Android: Proper Way to use onBackPressed() with Toast but here you want to make a boolean that is set to false while the process is not complete, and set to true when it's done. Allow onBackPressed() to call super.onBackPressed() only when the boolean is true.
#Override
public void onBackPressed()
{
if(processesCompleted == true)
{
super.onBackPressed();
}
}
You can't disable the onCreate() method in android but you can however override it like you do with the onStart().
I suggest you take a look at the life cycles of either fragments or activities, depending on which you use.
Fragments:
http://developer.android.com/guide/components/fragments.html
Activities:
http://developer.android.com/reference/android/app/Activity.html
It is hard to understand what the problem really is without more code, but basically the code in onCreate will mostly not be called when you press the backbutton since an activity will be paused until the phone needs more resources and then destroys it. If an activity is destroyed the onCreate method will be called and there is nothing you can do to change that.
If my answer dosen't help, please provide more example code.
If all your cards have different activities, the backbutton should work perfectly. However if your activity is brought to the front, nothing will be reloaded, except the onresume. In the onresume you can perform a new loading structure or something you want to achieve.
When you don't have different activities, use the override at onBackPressed(), that will handle the backbutton.
But place some code for a better answer
You can create a new function in which you run the processes and call
it on onCreate and use a Boolean flag to make sure when you go back to
that activity and flag is checked the function is not called. Then
save the value of flag in savedPreference onPause() method and you are
done and onCreate() method load your saved preference.
Something like this
boolean flag = false;
#Override
public void onResume()
{
super.onResume();
// load savedPreferences
}
#Override
public void onPause()
{
super.onPause();
//save savedPreferences
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if(flag == false)
{
//function call
processes();
}
}
private void processes()
{
flag = true;
// do stuff here
}

Pressing back button reduces counter

I have made a simple app on Android which increases the counter value by one and goes to next activity. At this point, if i press the back button, instead of just leaving the app or going to homescreen of the app, it goes to previous screen and reduces the counter by one.
How do i prevent this from happening and keep the counter value same.
Thanks
use like that
#Override
public void onBackPressed() {
super.onBackPressed();
counter--;
// fireintent here or finish() call
}
You could intercept the back click and handle it differently:
#Override
public void onBackPressed() {
// do something else.
}
When starting your new intent make sure you include NOHISTORY to prevent the activities piling up on the stack. You will need to save the value into your applications shared prefrences or another file to ensure that the value will be kept when your application exits.

Saving Activity State -

In my application, There is an activity UserMenu, in which (at on create) subsequent loading is done. I want that next time when the application is opened, this screen should not be reloaded again - I want to save the state of the UserMenu screen as it is.
I have been moving through this, but I am unable to look what I have to implement, I dont want to save any values, simply I want to recreate the same screen as I can get on pressing the home button in android.
Kindly help me regarding my matter.
Thanks
You can do like this
In your UserMenu Activity class
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
goToHome();
return true;
}
return super.onKeyDown(keyCode, event);
}
private void goToHome() {
moveTaskToBack(true);
}
So when you will press back button the Activity will no be destroyed and move to Home and once you will long press Home Button or start your app from menu it wont load the Activity again.
Thanks
It is not possible according to me as like what you are saying about home button. when home button is pressed your activity goes in onPause() and when you reopen it comes in onResume(). You can do what is suggested in the link you are following i.e you can save the values of your Actvity elements using onSavedInstanceState() also it is no guaranteed to execute read this onSavedInstanceState
you need to follow the Activity Lifecycle to make it simple.just make a function call from onCreate() method to load those data,save the data in some standalone class using ArrayList(),and in onResume() display the stored data from ArrayList().and yes,inside onCreate() check for the size of that ArrayList() just to decide whether the data has already been loaded or not.if it has not been loaded,load it.otherwise don't load.

How to prevent going back to the previous activity?

When the BACK button is pressed on the phone, I want to prevent a specific activity from returning to its previous one.
Specifically, I have login and sign up screens, both start a new activity called HomeScreen when successful login/signup occurs. Once HomeScreen is started, I want to prevent the users from being able to return to the login or sign up screens by pressing the BACK key.
I tried using Intent.FLAG_ACTIVITY_NO_HISTORY, but since the application has Facebook integration, when the 'Login with Facebook' is used, Facebook should return to the initial login screen, therefore I should keep a history of these activities.
I thought of overriding the behaviour of the BACK button on HomeScreen to directly finish an application when the button is pressed and I used
#Override
public void onBackPressed() {
finish();
}
but that also does not work.
My suggestion would be to finish the activity that you don't want the users to go back to. For instance, in your sign in activity, right after you call startActivity, call finish(). When the users hit the back button, they will not be able to go to the sign in activity because it has been killed off the stack.
Following solution can be pretty useful in the usual login / main activity scenario or implementing a blocking screen.
To minimize the app rather than going back to previous activity, you can override onBackPressed() like this:
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
moveTaskToBack(boolean nonRoot) leaves your back stack as it is, just puts your task (all activities) in background. Same as if user pressed Home button.
Parameter boolean nonRoot - If false then this only works if the activity is the root of a task; if true it will work for any activity in a task.
I'm not sure exactly what you want, but it sounds like it should be possible, and it also sounds like you're already on the right track.
Here are a few links that might help:
Disable back button in android
MyActivity.java =>
#Override
public void onBackPressed() {
return;
}
How can I disable 'go back' to some activity?
AndroidManifest.xml =>
<activity android:name=".SplashActivity" android:noHistory="true"/>
There are two solutions for your case, activity A starts activity B, but you do not want to back to activity A in activity B.
1. Removed previous activity A from back stack.
Intent intent = new Intent(activityA.this, activityB.class);
startActivity(intent);
finish(); // Destroy activity A and not exist in Back stack
2. Disabled go back button action in activity B.
There are two ways to prevent go back event as below,
1) Recommend approach
#Override
public void onBackPressed() {
}
2)Override onKeyDown method
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK) {
return false;
}
return super.onKeyDown(keyCode, event);
}
Hope that it is useful, but still depends on your situations.
Since there are already many great solutions suggested, ill try to give a more dipictive explanation.
How to skip going back to the previous activity?
Remove the previous Activity from Backstack. Simple
How to remove the previous Activity from Backstack?
Call finish() method
The Normal Flow:
All the activities are stored in a Stack known as Backstack.
When you start a new Activity(startActivity(...)) then the new Activity is pushed to top of the stack and when you press back button the Activity is popped from the stack.
One key point to note is that when the back button is pressed then finish(); method is called internally. This is the default behavior of onBackPressed() method.
So if you want to skip Activity B?
ie A<--- C
Just add finish(); method after your startActvity(...) in the Activity B
Intent i = new Intent(this, C.class);
startActivity(i);
finish();
finish() gives you method to close current Activity not whole application. And you better don't try to look for methods to kill application. Little advice.
Have you tried conjunction of Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NO_HISTORY? Remember to use this flags in Intent starting activity!
Put finish() just after
Intent i = new Intent(Summary1.this,MainActivity.class);
startActivity(i);
finish();
If you don't want to go back to all the activities on your application, you can use
android:launchMode="singleTask"
Learn more here: http://developer.android.com/guide/topics/manifest/activity-element.html
paulsm4's answer is the correct one. If in onBackPressed() you just return, it will disable the back button. However, I think a better approach given your use case is to flip the activity logic, i.e. make your home activity the main one, check if the user is signed in there, if not, start the sign in activity. The reason is that if you override the back button in your main activity, most users will be confused when they press back and your app does nothing.
This method is working fine
Intent intent = new Intent(Profile.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
#Override
public void onBackPressed() {
}
When you create onBackPressed() just remove super.onBackPressed();and that should work
Just override the onKeyDown method and check if the back button was pressed.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
//Back buttons was pressed, do whatever logic you want
}
return false;
}
Put
finish();
immediately after
ActivityStart
to stop the activity preventing any way of going back to it.
Then add
onCreate(){
getActionBar().setDisplayHomeAsUpEnabled(false);
...
}
to the activity you are starting.
AndroidManifest.xml
<activity
android:name=".welcome.SplashActivity"
android:noHistory="true" // just add this line
android:exported="true">
</activity>

Why Back button is not detecting in muti tab activities?

I have Main Activity. That has 4 tabs(TabHost). I have overridden onBackPress() in MainActvity , as well As All 4 activities. This button show user a dialog box and for conformation of Exit
When app start. It show 1st tab. Then if I press back it work fine. But if I go for next 3 tab and then press back, The app stop. OnDestroy() of Main is called. But there is not dialogue for the user.Even noting is print in log cat. That I have written in onBackPressed() method From and of 5 activities including MainActivity.
I have also try onKeyDown() for back key but result is same? Have any one experience the same? Please help me.
I come to know it was difficult to open new activity inside the previous tabs when I am using TabHost. I google it and found GroupActivity is the best solution for this problem.
GroupActvity Example
But GroupActivity have the same problem when open new activity in the previous tab. the back button not work properly for new activity. After search I found that was due to the focus was alwasys on parent activity. I have to make
setFocusable(true);
requestFocus();
on my new activity component to gain focus.
I am now using GroupActivity for customizing Tabbar and activities.As I ma also maintaining stack of activity ids in parent activity so that I can pop out the recent activity when user press back button.
else if you are NOT going to implement Activity focus then you should maintain stack in parent and when press the back button it will initiate parent onBackPressed(); and you can call the child onBackPressed() functionality as discussed in the link.
onBackPressed() not working inside ActivityGroup
well one thing i know for sure is that you will always get the onBackPressed() called in the MainActity if you are running with a tabHost and not in the child views. The only thing that comes to mind is if you have consumed the event in the onBackPressed method (return true) because if you didnt it will go and still follow the default process and destroy your activity.
I meet this problem,but i have shot it now.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK)
{
showExitDialog();
return true;
}
return super.onKeyDown(keyCode, event);
}
public void showExitDialog()
{
new AlertDialog.Builder(this)
.setTitle("Attention")
.setMessage("Do you want to exit this application")
.setPositiveButton("YES", exitListener)
.setNegativeButton("No", cancelListener)
.show();
}
at the first time i lost a "reture true" in onkeydown()

Categories

Resources