I want to know which method constantly calls when fragment is running? Is it onResume(). I have a condition (if statement), i want that the fragment constantly checks the condition and if it is true do the following task that i want to do.
For example:
if (heartdata >= 100 || bloodata >= 120 || tempdata >= 100)
{
sendMessage();
}
Where should i put this IF statement so that the android fragment/app constantly checks the condition and call the sendMessage();
i put the code in onCreate() it didn't worked i also put that in onCreateView() but didn't worked please tell me where to put this code..
The solution is to use a TimerTask and schedule it at regular intervals using Timer because Fragment Life cycle methods won't be called repeatedly while fragment is stable and running. Paste below code in onViewCreated method of your fragment
Example
Timer timer = new Timer(); //Global declaration
public void onViewCreated(..){
...
timer.schedule(new TimerTask() {
#Override
public void run() {
if (heartdata >= 100 || bloodata >= 120 || tempdata >= 100)
{
sendMessage();
}
}
},60 * 1000); // Which will run for every 60 seconds
...
}
#Override
public void onDestroy() {
super.onDestroy();
timer.cancel();
}
You can view the Fragment life-cycle here. Basically there is no method that "constantly checks". For example the method onResume() is called only when a the fragment is resumed.
If you want to constantly check if a condition is satisfied, i'd suggest creating a background thread and running the code you stated above inside that thread. Once the condition is met, send your message.
Create a boolean named isRunning
In onResume set isRunning to true and in onPause set it to false.
Or use onStart and inStop thatever you want.
And then your while statement:
while(isRunning) and do whatever you want there...
However I am not really sure if this is good for performance
P.S.: Use while or maybe for if you want to do aciton repeatedly.. not if... if is kind of check
I think for this purpose you should use a new Thread in which you continuously checking that condition and when that condition is reached give callback to fragment.
Try this code, it will check every 1SEC
public class MyFrag extends Fragment {
Runnable runnable = new Runnable() {
#Override
public void run() {
if(getActivity()!=null) {
mHandler.postDelayed(runnable, 1000);
}else{
mHandler.removeCallbacks(runnable);
return;
}
//Your check code will here
}
};
Handler mHandler = new Handler();
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mHandler.postDelayed(runnable,1000);
}
}
Related
I want to change from my current activity to another while I am inside a Handler. The idea is other code inside the handler will run until a certain condition doesnt match (with increment of the count value every time). When the count value matches the condition I close the activity and move to another.
my code is:
mHandler = new Handler();
mRunnable = new Runnable() {
#Override
public void run() {
if(count<CONDITION_VALUE)
{
//do other stuff...
count++;
}else
{
//change activity...
finish();
}
mHandler.postDelayed(mRunnable, 4000);
}
};
mHandler.postDelayed(mRunnable, (1000));
The code is running without any error but the old activity is not being destroyed (i guess) and the new activity is reloaded after every 4 seconds.
I want the new activity to load only once.
How can I achieve this?
try this, from enter link description here
in your Activity
#Override
public void onDestroy() {
mHandler.removeCallbacks(mRunnable);
super.onDestroy();
}
I'm not sure if this is the correct way to go about but I will try and explain what I want to do.
I have an Activity which creates a fragment called TemporaryFragment with a label. What I want to do is create and start a service with a Timer in it and that Timer then updates the time in that TextView.
The way I am thinking of going is somehow, when the Service is started, passing the TextView from the Activity to the Service and then the Service keeping a reference to it.
Another possible way is to make the Activity become a listener of the Service and then calling a method in the Service to update the TextView.
Any thoughts would be great and maybe some options.
Thanks in advance.
ADDITION
I'm sorry, I should also specify that I need this timer to run in the background. So when the application is sent to the background, I need the timer to carry on and only stop when I tell it to.
Service is not ideal for such minor task like this, moreover, Service can be run independently of activity. Also spawning new thread or using timer which introduces new thread into the application is not ideal for this relatively minor reason if you are thinking in the terms of mobile applications.
Instead use Handler in your fragment.
create handler in your fragment
private Handler mHandler = new Handler();
to execute your defined task call
mHandler.postDelayed(mUpdateTask, 1000);
or
mHandler.post(mUpdateTask);
and define your task in the fragment
private Runnable mUpdateTask = new Runnable() {
public void run() {
Toast.makeText(getActivity(), "hello world", Toast.LENGTH_SHORT).show();
mHandler.postDelayed(this, 1000);
}
};
If you are showing time-like information instead of countdown-like one, use
mHandler.removeCallbacks(mUpdateTimeTask);
in onPause() method to stop executing your task if the activity is not visible as updating UI isn't relevant and it saves battery (you start task again in onResume() method)
Basically, the idea behind the timer is eventually I am going to add some tracking into my application and therefore need it to continue running even if the application isn't in the foreground – Disco S2
Based on this comment I suggest you to use a local service which resides in the background, doing it's stuff (start a thread from Service#onStart), until it gets stopped by stopService(..).
Activities on the other hand may bind and unbind to that service (see: bindService(..)) to get notified about updates or to communicate with the service in any way.
I would use a more simple approach by using a Thread:
public class MainActivity extends Activity implements Callback {
private static final int MSG_UPDATE = 1;
private static final long INTERVAL = 1000; // in ms
private final Handler handler = new Handler(this);
private Thread worker;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MSG_UPDATE:
updateView();
return true;
}
return false;
}
private void updateView() {
// TODO tbd
}
#Override
protected void onStart() {
super.onStart();
// start background thread
worker = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(INTERVAL);
} catch (InterruptedException e) {
break;
}
// send message to activity thread
handler.sendEmptyMessage(MSG_UPDATE);
}
}
});
worker.start();
}
#Override
protected void onStop() {
super.onStop();
// stop background thread
worker.interrupt();
try {
worker.join();
} catch (InterruptedException e) {
}
worker = null;
}
}
You can use the TimerTask Class for this. Override the TimerTask.run() method and then add that TimerTask to Timer class.
Also check this question: controlling a task with timer and timertask
I have following code snippet in my application activity.
If user is landing on activity for the first time then only thing that will happen is changing the boolean variable shouldSleep to true.
Thereafter, else part will be executed which contains generation of notification at every 60 seconds.
But the main problem is if I execute this code, the activity NEVER gets displayed as it keeps looping in else part and hence go on sleeping.
What I want is remaining application should run normally while every 60 seconds, else part of this method should be executed.I guess it has got something to do with AsyncTask but I don't have much idea about it.
Any idea how to do this? Thanks in advance for your help.
boolean shouldSleep=false;
private void ShowNotification()
{
//DO SOME TASK
if (shouldSleep)
{
Thread.sleep(60000);
//DO SOME TASK
}
else
{
shouldSleep = true;
}
/** Calling the method recursively so that it always runs. */
ShowNotification();
}
Maybe you can use a Timer object :
new Timer().schedule(new TimerTask() {
#Override
public void run() {
//This code is run all 60seconds
myBooleanVar = true;
//If you want to operate UI modifications, you must run ui stuff on UiThread.
Activity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Activity.this.changeUiStuff();
}
});
}
}, 60000);
Just use a Timer. Instead of a thread approach, you could run your task every 60s:
new Timer().schedule(task, delay, period);
with period = 60*1000
I have an Activity with 3 spinners. These spinners get their data from a web-service by a method that takes about 1 minute to be completed.
I want to load the Activity first and after it is made visible, call that web-service method and load data. I have tested the following codes separately but none of them solved my problem. In these samples application goes into a black screen and when the web-service operation completed, it is made visible.
#Override
protected void onCreate() {
//.........
final Runnable r = new Runnable()
{
public void run()
{
loadMyData();
}
};
Utilities.performOnBackgroundThread(r);
}
#Override
protected void onResume() {
new Thread() {
#Override
public void run() {
loadMyData();
}
}.start();
super.onResume();
}
#Override
protected void onStart() {
if (comesFromOnCreateMethod)
{
final Runnable r = new Runnable()
{
public void run()
{
loadMyData();
}
};
Utilities.performOnBackgroundThread(r);
}
comesFromOnCreateMethod = false;
super.onStart();
}
#Override
protected void onResume() {
if (comesFromOnCreateMethod)
{
final Runnable r = new Runnable()
{
public void run()
{
loadMyData();
}
};
Utilities.performOnBackgroundThread(r);
}
comesFromOnCreateMethod = false;
}
If you are getting a black screen, then I would assume your code is being run on the UI thread and not on the background, causing the UI to hang until the work is completed.
One of the best solutions to doing background work is an AsyncTask. Using this, you can call it in your onCreate() method, and when its done, it will post a callback to the UI thread for you in which you can display you data.
If you want this method to run everytime this Activity displays, then call it in onResume(). Otherwise, call it in onCreate().
In your onCreate, make the async tasks as the others have advised. Make sure you generate the content for the app first and then call the asyncTasks. You can control your spinners from the callback.
First of all, you might want to increase your accept rate, 39% is pretty low.
Anyway, you might want to check AsyncTask, it should do the thing. http://developer.android.com/reference/android/os/AsyncTask.html
Typically, you will want to initialize in onPreExecute, do the networking in the doInBackGround, and set the result to the UI thread on the OnPostExecute. Hope this will help.
Use AssynchTask() and you should call super.onResume() or any lifecycle method in respective life cycle method first then other specific method you want to do....
I need to use idle listener to listen the user is using the application or idle when the activity is alive.
I need to do something when the user is not using the application more than ten seconds.
How can i make it possible?
Here is the idea how you can achieve this task:
Firstly you need a Runnable(), which will be Run when your timeout(e.g. 10 sec) occurs. Below is the Runnable():
private Runnable DoOnTimeOut = new Runnable()
{
public void run()
{
// Do something Here
}
}
Now, in your activity, you can call postDelayed for the DoOnTimeOut:
Handler hl_timeout = new Handler();
#Override
public void onCreate(Bundle b)
{
hl_timeout.postDelayed(DoOnTimeOut, 10000); // The DoOnTimOut will be triggered after 10sec
}
Now, most important part is that when you see user interaction, you want to cancel the call to DoOnTimeOut and then again set the call for next 10 sec. Here is the Override method of your Activity for User Interaction:
#Override
public void onUserInteraction()
{
super.onUserInteraction();
//Remove any previous callback
hl_timeout.removeCallbacks(DoOnTimeOut);
hl_timeout.postDelayed(DoOnTimeOut, 10000);
}
I hope it will be helpful for you.