I am trying to write code for my android application for things to happen when the activity is Resumed. Although I only want this stuff to happen when the activity is re-visited for the second time and not the first time.
So I want the user to do what they need in the onCreate method in their first visit to the activity and then when they go back to the activity then the onResume code happens.
Should I be using a different method or how can I achieve what I am looking to do?
public void onResume(){
super.onResume();
RunningStatus = sharedPreferences.getBoolean("RunningStatus", false);
if (isS1Pressed) {
if (isPressed) {
if (RunningStatus = false) {
pause.setBackgroundResource(R.drawable.start);
}
}
}
EDIT:
I don't mean second time I mean every time after. Basically I have a production line and my app determines whether it is ahead or behind. So when the user enters this activity then the can perform the calculation. We have a pause button where the user can pause the line if the production line has been stopped in real life. Although I would like that the user can then go out of that specific production line and do calculations on other lines too. Although at the minute once I leave the activity I lose all its state.
Thanks
You could use a boolean flag. in onResume e.g.
if (secondVisit) {
...
} else secondVisit = true;
If you want to do some stuff for very specific time (only 2nd, not 1st or 3rd, 4th,...), I suggest you should use some counter variable and use activity method onSaveInstanceState() and onRestoreInstanceState() to store and retrieve. If you don't want to reset the counter when app got killed, use data persist like SharePreference to store counter.
i assume that you have gone through the activity life cycle if not then visit
https://developer.android.com/guide/components/activities/activity-lifecycle
boolean secondUse=false;//this should be a field in the activity class
onRestart() method is called only when we visited the activity and and came back and then we visit(i.e. when the activity already in the activity stack).
if you have other use case, then using sharedPreference would be better.
override the onRestart()
inside it write the following
if(!seconduse){
//do your stuff
secondUse=true;
}
as you said in the edit you need the stuff to work on every visit after first visit then simply put your code in onRestart() method
public void onRestart(){
super.onRestart();
RunningStatus = sharedPreferences.getBoolean("RunningStatus", false);
if (isS1Pressed) {
if (isPressed) {
if (RunningStatus = false) {
pause.setBackgroundResource(R.drawable.start);
}
}
}
}
Related
So I've looked up similar problems to this, and have followed the advice in those threads, but it seems to give me no change in behavior.
So I'm writing an app that essentially notifies the user when they're going too fast or too slow based on GPS onLocationChanged() calls. I overrided the onBackPressed() method to finish() and return but the activity continues to run in the background when I go back to the main activity.
To be clear, I DO want the activity to run when the app is minimized or screen is off. I only want it to stop when the user goes back to the menu (IE, hits the back button)
Here's the link to the class on pastebin:
http://pastebin.com/V7z5c3HH
Thanks for your help! =D
Unsubscribe your location listener in the onDestroy method.
However, what you need for your GPS processing is probably a Service, not an Activity.
You need to remove the updates for that listener.
#Override
protected void onDestroy() {
locationManager.removeUpdates(locationListener);
super.onDestroy();
}
I have two Activities in one application.
First one updates its TextViews every 3 seconds. It works fine.
When the keyguard (lock screen) is activated the first activity launches the second activity which appears over the lock screen (in order to show data even if the screen is locked). It also works fine.
I would like the TextViews of the second activity to be updated periodically by the first activity. I have played hours with this and tried a lot of suggestions I found with Google but none of them worked for me. The second activity always crashes with NullPointerException at the moment when the TextView.setText() is called.
What is the best practice for doing this?
Thanks in advance for any help.
I don't think there is a good way to do this, as your first activity could get collected by the system, and you generally don't want to do work after onPause has been called.
I would move that logic that updates the views into a service that runs in the background. Since it sounds like you only need this service while the application is running I would create a bound one.
http://developer.android.com/guide/components/services.html
You can pass the data on calling another activity as :
Intent intent =new Intent(FirstActivity.this, SecondActivity.class);
intent.putStringExtra("TextName","Value");
startActivity(intent);
As Ashish said you could use EventBus.
Add the library to your app and in your Second Activity register your activity in the EventBus in onCreate method:
EventBus.getDefault().register(this);
Create a new class in your project to define an event type:
public class TestEvent {
public TestEvent() {}
}
So in your second activity create a method to receive the event:
public void onEvent(TestEvent event) {
//stuff to do
}
Now, in your first activity you just have to "fire" the event in the method executed each 2 seconds:
EventBus.getDefault().post(new TestEvent());
Each time you execute post method, the onEvent of your second activity will be run.
A way to do it is by defining a Singleton object that holds the value to be displayed on the TextView, for instance, a Integer or a String.
Both activities have access to read/write into this object. So when you come back to the second activity, maybe on the onResume() method..you can the following:
public void onResume() {
super.onResume();
textview.setText(""+ MySingleton.getInstance().getValue());
}
On the other activity:
public void updateMethod() {
int newValue = .....;
MySingleton.getInstance().setValue(newValue);
}
This will make sure that whenever you come back to this activity (as onResume() is called), the value will be updated into the TextView. Of course, assuming that you are updating the value from the other activity accordingly.
Note this is the simplest solution you can do, professionally, I would do an event driven solution, where the observer gets notified when the value is changed. For that you can play with http://square.github.io/otto/ library.
I'm new to Android programming, so I'm probably missing something trivial here.
The goal is to create a prototype of a digital signage app. Right now I've created three activities; MainActivity has a method which switches to the second activity after a certain period of time. The same method is then called from the second activity to third, and from third back to main.
There are two problems though: first, is it ok to create new Intent every time the app switches between the activities? As I mentioned, I started learning Android recently, so please don't be mad if this is a super dumb question.
Second: the app launches itself after I've hit home button in my emulator even though I'm calling finish(); after the startActivity(intent);
Here is the method in the MainActivity:
public void switchActivities(final Class<?> classObject) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getApplicationContext(), classObject);
startActivity(intent);
finish();
}
}, 1000);
}
The activities Second and Third extend MainActivity and call the switchActivities method:
switchActivities(Third.class); (from Second to Third).
Thanks in advance!
UPDATED:
I added public boolean isRunning = true; to my MainActivity and
if(isRunning) startActivity(intent); to the switchActivities method;
I also added a method
#Override
protected void onPause(){
super.onPause();
isRunning = false;
}
as advised here.
Although finish(); should have cleared the method stack, the app didn't close after pressing Home button but went to previous activity instead, so I added this line to every activity in the AndroidManifest file:
android:noHistory="true"
as advised here.
Sorry for not upvoting helpful answers, I don't have enough reputation yet.
Yeah, it is the proper way of switching activities by creating new intents. I am little confused about your second questions. if you are saying that as you are using postDelayed method which gets triggered after some interval, is being called even you have finished your activity or pressed home button, you can handle this by creating a boolean variable isRunning in your activity which gets false when onPause or onDestroy gets called. Then you in your postdelayed method, you can check the flag and then proceed as required.
The Intent used in navigation between the Activities , so it's cool to using it , no problem
The second problem because the Activity object still in your memory after you hit Home button , then the Handler will continue its work and start the activity after the certain period you determined in your code
For your first question: it's not a problem that you're creating a new Intent every time
The second one is a bit trickier. When you press the home button the current activity stays in memory, so it can start the new one even though you think it's not running. The easiest way to handle this to check weather the activity is finishing, and if so, you don't show the next one.
if (!isFinishing()) startActivity(intent);
This if statement prevents your activity to start a new one when it's in the background.
Does a page know that it's being loaded as the result of the back button being pressed? We have a global routine that catches the back button press, gives a notification and then carries on the super.onBackPressed();
This is all fine, but theres an instance where the page is jumped forwards in certain situations - so when a back button is pressed before it gets in a loop and forwards the page forward again.
Essentially I want the previous page to have an if around the forward to say in psudo
if(page-load-is-a-result-of-the-back-button){
finish();
} else {
dothejumpforward;
}
A lot like .nets if ispostback type thing?
Any help would be really appreciated.
You make a static variable in your Main Activity, your first activity that is launching with your app. Let's say it will be: public static int backFromActivity;
So when you press the back button while you are in Activity2, you will override the onBackPressed method, and when this method is called you set the MainActivity.backFromActivity = 2;
Now in your onResume method from the Activty1 you check from what activity reached this on.
if ( MainActivity.backFromActivity == 2 ) // do stuff
Its simple if your activity gains control back from other activity as a result its Oncreate should not get called instead OnResume will get called. Put a bool value to check it ,...
Eg: within OnPause() set the bool paused = true;
Within OnResume()
If(paused)
//Its a result
Is there anyway to check if the application is minimized or if you have locked your device?
Because when I do minimize / lock my device the application is still runnig, this is mainly because I'd like to pause the music / sfx not to annoy people.. Like if someone is calling.
I am using Activity and SurfaceView with threads.
I have tried putting my pause method in the surfaceDestroyed / surfaceChanged but without success.
You should understand the activity lifecycle first
when the activity comes int the foreground it'll enter onPause() and it'll enter onResume if the user returns to the activity, an example to use onPause is like this
#Override
public void onPause() {
super.onPause(); // Always call the superclass method first
// DO YOUR STUFF HERE
}
}
for furthere reference about onPause you can see it here -> onPause Tutorial