Android Activity starting parallel? - java

i have four activities.
like (1) (2) (3) (4).
(1) is first activity or main activity.
i have a bottom bar for these activities.
if i click on (2) i want to open second activity.
after this if i click on (3) i want to open third activity.
and if i click on (4) i want to open fourth activity.
after this if i click on (1) i want to display first activity.
without finishing any other activity or again open (1) activity.
a image for easy understanding is attached..
please open this image in new tab to view clearly.
i want to do this without using tabhost.
can it done by using activity group.
suggest any example or tutorial for this.
thanks Rock Brown

This use case is already built into the platform:
In your AndroidManifest.xml there is an activity element for each activity. In the activity element for 1 set the launchMode:
android:launchMode="singleTask"
This causes the platform to only ever launch one instance of Activity 1 in the app's task (which is a stack of activities.)
When you start activity 1, 2, 3, or 4 set the Intent's flags to include FLAG_ACTIVITY_REORDER_TO_FRONT:
intent.setFlags(intent.getFlags() | FLAG_ACTIVITY_REORDER_TO_FRONT);
This causes the platform to bring any existing instances of 1, 2, 3, or 4 to the top of the activity stack, rather than creating a new activity and placing it on top of the stack.

An activity can be closed at any moment by the os if a memory pressure append and your activity is in the background.

I agree with Aashish that you probably want to look at the TabHost tutorial.
But, yes, you can do it without TabHost.
Activity (1) will get launched first, assuming it is the launch activity as defined in your manifest. You can switch to one of the other activities at any time using Context.startActivity(Intent).
You can even do this before (1) is displayed based on state preserved in a bundle or saved to user prefernces (i.e. so it restarts on the same activity that was last used). In a case like this you don't want to the current activity to be on the backstack so you call Activity.finish() after launching the next activity, so now you have.
public void showNextActivity() {
Intent intent = new Intent(this, NextActivity.class);
startActivity(intent);
finish(); // so ThisActivity isn't in the backstack.
}
You should probably have some code that is shared between your activities to manage the widgets that are used to change between activities (e.g. the Button's) and to handle the switching. Note that, even if each activity has its own resources, you can use the same r esource ID's on each - so the Button that selects activity 2 has ID 'act2' on each activity. This makes sharing code easier.

Related

Kotlin have two simultaneous activities

I am developing an Android Kotlin application which uses two different activities. In each one I have a button that allow me to move to the other one, to say, in Activity 1 I have a button that calls the follwing:
val intentActivity2 = Intent(this, Activity2::class.java)
startActivity(intentActivity2)
This launches correctly Activity2, which similarly inside it I have another button that calls the first activity to return to it:
val intentActivity1 = Intent(this, Activity1::class.java)
startActivity(intentActivity1)
The problem I have is that I want to have both activities running simultaneously (not needed to be shown at screen at the same time), and the issue right now is that every time I call the "startActivity(intent)" a new activity is created, loosing what I had in the previous one, so when I return to Activity1 everything is reset and the same when I go once again to Activity2. Both activities work fine and do their work, the problem is that I can't freely conmute between them.
Is there a way to have both activities at the same time or to not start a new activity everytime I want to change to the other one?
Thank you,
As someone just said you need ViewModel to retrieve your data after deleting/creating new activities. Maybe you can use fragments to do your things. Fragments are attached to activities and it is easier to use them instead of ViewModel.

What is diffrence between back button and setDisplayHomeAsUpEnabled in an activity?

I have two activtiy. When a boolean variable in activity 1 is true then the UI in activity 2 should be update (activity 2 is with fragment). When I back to activity 2 with (setDisplayHomeAsUpEnabled) it works correctly but with back button it does not work. What is the difference between this ways and how I can solve this. I try update the activity 2 with this code but it does not work:
#Override
public void onBackPressed() {
super.onBackPressed();
//update();
}
The Home Button is not meant to behave like the Back Button. See this reference. The Home or "Up" Button should take the user up within the view hierarchy (i.e. if you have a number of multiple choice fragments, don't go back through each of them, but back to the activity that started the first fragment)
Each activity should specify what it's parent activity is in order to properly use this functionality. You can do this through the manifest, or by overriding onOptionsItemSelected() as outlined here
In terms of why your activity 2 may be updating when using the "Up" button but not the back button, this could be because both handle the back stack in a different way. Back will take you to the last thing on the stack and resume it, assuming you don't haven't tagged the activity with a launchmode that alters this behavior. Here's more info on the back stack. If you haven't designated your Activity 2 as "singletop" then when you use the "Up" Button, a new instance of that parent activity is created. See here. This may means that the information is updating after using the home button because it's creating a new instance of the activity, while for the back button - you are not creating a new instance but resuming a previous instance... make sure you implement an onResume() function to properly handle this and update the information.

Up Navigation: From Activity to Fragment: Android Studio

The basic navigation of my app is a tab bar within one activity in which each tab is its own fragment. I am trying to get the back button to work to go back to the last tab it was on. I can get the back button to work/appear if the activities are going to the first tab by using this in the java class of the activity:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
and this in the AndroidManifest.xml:
<activity android:name=".CreateNewPost" android:parentActivityName=".MainActivity"></activity>
This works fine, however when I go to a new activity from a button within the other tabs, if I use this same method it goes to tab1. How do I tell it to go to a specific tab or the last active fragment?
Any suggestions would help!
When you launch a new activity the old one either paused or stopped , as in either OnPause() or OnStop() method has been called. Then when you navigate back to a previous activity it is either started (OnStart()) or resuemd (OnResume()). And sometime the activity is destroyed and created again when navigating back to it using OnDestroy() and OnCreate() respectively.
The most guaranteed way that I can think of is to store the state of the first activity somewhere persistently and when the user navigates back to it check what has been stored and show that fragment.
You can use SharedPreferences to store this kind of data, see the google developer documentation on that here. Or onSaveInstanceState(Bundle savedInstanceState) check out this SO question on saving activity state. Although from the answers it is clear that onSaveInstanceState should not work in your specific case, but you should look at it any way because it is useful in other cases like changing screen orientation for example.

Don't kill Activity when pressing back button

I have four activities, ABCD.
The user will initially go ABCD, then the user may want to tap the back button to check something on C before tapping a button on C to take them forward to D again.
The problem I have is that D is running a count down timer which needs to continue counting down and updating on an activity D view. If I currently tap back to go back to C then tap to go forward to D again, the countdown timer is still running but not connected as a new activity has been created for D.
I'd like the user to be able to navigate back to C without it affecting or destroying D so I can keep my timer hooked up to the view.
Finally, if the user clicks back to B, it would destroy both C and D activities (and the countdown timer).
It's quit easy save the timer value and current time on saveInstanceState call back when users leave the activity. When activity recreates use the timer value plus it with (current time - lastSavedTime) and set the timer.
it should work just fine but you can achieve this in better way by using fragments and ViewPager.
In case you didn't used ViewPager before. its a component that let you switch between different views by swiping screen to left or right. By default view pager loads the current view and one near it in both side. so if you are in page 1 (index 0) page 1 and page 2 is loaded. if your are in page 2, page 2, page 1, and page 3 will be loaded and so on. The good news is you can change the number of pages that will load near each fragment using simple code like this
mViewPager.setOffscreenPageLimit(3);
So now all 4 fragments are loaded. So you have 4 fragments all loaded on screen. According to developers.android.com all the others views (except one on screen) are loaded but in idle state so I don't think you can have your timer inside fragment D. But that wouldn't be a problem because you only have one activity. Implement your timer in the one and only activity you've got and it will work fine because this activity will not be destroyed when pages change. But you still need to save the same data (timer data + current time) because activity may stop due to user switching to another app.
last thing you need to do is accessing timer data inside your fragment. I will not explain how since there is so many tutorial on how to communicate between activities and fragments but just to give you and idea you need to declare an interface inside your fragment, implement this interface in activity and use this interface inside your fragment to access timer data.
The second solution is a lot more complex but it gives the user a better experience and performance increase is noticeable. Decide witch one is best for you. Good luck
You can use this
#Override
public void onBackPressed() {
Intent intent = new Intent(this, C.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
to put your D activity to background and then resume it from C like this
Intent intent = new Intent(this, D.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
However, you should use a service for this sort of background tasks.

how to make the appliction exit when pressing back button in the main activity?

In my application when i click the back button it passes through all the activities that i open them previously , i used the public void onBackPressed() method to make the back button back to the activity that i want as follow
public void onBackPressed()
{
startActivity(new Intent("com.MyDiet.Main"));
Tracker.this.finish();
}
is that true and safe way to code the back button ? how i can prevent the application from passing through all the previous opened activities when the back button is pressed ? and how i can make the application exit when i click the back button in the main activity?
In your application, and in ALL android applications, unless it's critical not to pass through unneeded steps (such as login if you're already logged in), it's VERY important not to override Android standard behaviour. Users normally complain about Android apps not having a common behaviour or style guideline.
Anyway, yeah, you can just override onBackPressed on all your activities and do whatever you want. But just don't.
This approach isn't good, because you're polluting the activity stack of your application
Example:
current stack: MainAct -> Act2 -> Act3 (we're in activity 3)
With your code above, when you press back, the stack now looks as follows:
MainAct -> Act2 -> MainAct
Because you ended Act3 and launched a NEW main activity, which may be not what you wanted.
To achieve what you want (Get back to main when the current activity is over) you need to work on the intermediate activities: In the example above, when from Act2 you call startActivity("Act3"), you should call "this.finish()". Therefore you don't have to override "onBackPressed()" of activity 3: simply the default value will terminate Act3 and the next activity in the stack will be MainAct
MainAct -> A2 (A2 launches A3 and then calls this.finish())
MainAct -> A3 (user now press back)
MainAct (the mainactivity is now on top)
To summarize, you don't have to override onBackPressed, you just have to correctly manage the lifecycle of the activity between the main one and the current one.
Generally speaking it's not recommended to make things work like user doesn't expect and that is considered as very bad practice. That's why it is not good to start activity from overriden onBackPressed().
When user press back by default activity will finish and one from back stack will be displayed. You as developer will (by writing code) decide which one is that. You can do it this way but later (or for somebody else) it will be a bit messy and difficult to find this unusual place for code which is starting other activity.
So..It would be useful to read about activity lifecycle and back stack to get impression how it works and understand terminology better.
If you want one of your activity not to stay on back stack you can add in manifest file file android:noHistory="true" for that activity.
Same thing you can achieve from code by adding appropriate flag to intent when you start activity: Intent.FLAG_ACTIVITY_NO_HISTORY
When user "go away" from ActivityOne (started using intent or defined in manifest like described), to new ActivityTwo and then press back, it will not go to ActivityOne because it will not be on back stack. Using this you can precisely control navigation through your activities.
More flags are available for use, but I guess this is what you wanted to achieve.
Hope you will find my answer useful. Cheers..
You can use a lot of tricks to exit your complet application for my part i use this start a intent and then from the androidmanifest i choose the category to home and than close the current activity such would be your mainactivity !
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}

Categories

Resources