Android Timer Updating a Textview (Ui)

Android timer updating a textview (UI)

protected static void startTimer() {
isTimerRunning = true;
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
elapsedTime += 1; //increase every sec
mHandler.obtainMessage(1).sendToTarget();
}
}, 0, 1000);
}

public Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
StopWatch.time.setText(formatIntoHHMMSS(elapsedTime)); //this is the textview
}
};

Above code will work...

Note: Handlers must be created in your main thread so that you can modify UI content.

Update TextView every second in Android

You can use following code:

Runnable updater;
void updateTime(final String timeString) {
timer=(TextView) findViewById(R.id.timerText);
final Handler timerHandler = new Handler();

updater = new Runnable() {
@Override
public void run() {
timer.setText(timeString);
timerHandler.postDelayed(updater,1000);
}
};
timerHandler.post(updater);
}

In this line:

 timerHandler.post(updater);

time will set for the first time. i.e, updater will execute. After first execution it will be posted after every 1 second time interval. It will update your TextView every one second.

You need to remove it when the activity destroys, else it will leak memory.

@Override
protected void onDestroy() {
super.onDestroy();
timerHandler.removeCallbacks(updater);
}

Hope it will help you.

Timer update UI when back to timer Fragment

I finnaly did it:
I created a new Class which make all the Timer treatment and in my my Fragment implement his callbacks:
I'll live the code here for any case:

Sample Image

MainActivity:

public class MainActivity extends AppCompatActivity {
private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

setFragmentTransaction(null);

}

/**
* A fragment transaction Method
*
* @param fragment the fragment we want to display
*/
public void setFragmentTransaction(Fragment fragment) {

fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();

//replacing fragments new Fragments
if (fragment != null ) {
fragmentTransaction.replace(R.id.container, fragment);
} else if(fragment == null && (fragmentManager.getBackStackEntryCount() == 0)) { // starting with main Fragment
fragmentTransaction.add(R.id.container, new MainFragment());
}

fragmentTransaction.addToBackStack(null);
fragmentTransaction.commitAllowingStateLoss();
fragmentManager.executePendingTransactions();

}
}

MainFragment:

public class MainFragment extends Fragment {

private Context context;
private View view;
private Button button;

@Override
public void onAttach(Context context) {
super.onAttach(context);

this.context = context;
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

view = inflater.inflate(R.layout.fragment_main, container, false);

button = (Button) view.findViewById(R.id.mainBTN);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((MainActivity)context).setFragmentTransaction(new TimerFragment());
}
});

return view;

}
}

TimerFragment:

public class TimerFragment extends Fragment implements MyTimer.TimerRuning {

private Context context;
private TextView timerUpTextView, timerDownTextView;
private Button startBTN, backBTN, stopTimerBTN;
private View view;

@Override
public void onAttach(Context context) {
super.onAttach(context);

this.context = context;

}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

MyTimer.getInstance().setTimerRuningListener(this);

view = inflater.inflate(R.layout.fragment_timer, container, false);
timerUpTextView = (TextView) view.findViewById(R.id.timerUpTextView);
timerDownTextView = (TextView) view.findViewById(R.id.timerDownTextView);
startBTN = (Button) view.findViewById(R.id.startBTN);
backBTN = (Button) view.findViewById(R.id.backBTN);
stopTimerBTN = (Button) view.findViewById(R.id.stopTimerBTN);

startBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyTimer.getInstance().startTimer(180);
}
});

stopTimerBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyTimer.getInstance().stopTimer();
}
});

backBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((MainActivity) context).setFragmentTransaction(new MainFragment());
}
});

return view;
}

@Override
public void onTimerChange(String remainSec, String startSec) {
timerUpTextView.setText(startSec);
timerDownTextView.setText(remainSec);
}

@Override
public void onTimerStopped(String remainSec, String startSec) {
timerUpTextView.setText(startSec);
timerDownTextView.setText(remainSec);
}
}

MyTimer - Class

public class MyTimer {    

private Timer timer;
private MyTimer.TimerRuning timerRuningListener;
private int remainingSec, startSec;
public boolean isRunning;

private static final String TAG = "MyTimer";

private static final MyTimer ourInstance = new MyTimer();

public static MyTimer getInstance() {
return ourInstance;
}

private final Handler mHandler = new Handler() {

@Override
public void handleMessage(Message msg) {

int[] timeArr = (int[]) msg.obj;

if (timeArr[0] == 0) {
MyTimer.this.stopTimer();
if(timerRuningListener != null) {
timerRuningListener.onTimerStopped(createDateFormat(0), createDateFormat(0));
}
} else {
if(timerRuningListener != null) {
timerRuningListener.onTimerChange(createDateFormat(timeArr[0]), createDateFormat(timeArr[1]));
}
}

}
};

public void startTimer(final int seconds) {

startSec = 0;

remainingSec = seconds;
timer = new Timer();

timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
Log.i(TAG, "Timer running......");
isRunning = true;
Message message = Message.obtain();
int[] counters = new int[2];
counters[0] = remainingSec;
counters[1] = startSec;
message.obj = counters;
message.setTarget(mHandler);
mHandler.sendMessage(message);
remainingSec--;
startSec++;

}
}, 100, 1000);

}

/**
* Setting the timer format
*
* @param seconds
* @return
*/
public String createDateFormat(int seconds) {

return String.format("%02d:%02d", (seconds % 3600) / 60, (seconds % 60));

}

public void setTimerRuningListener(MyTimer.TimerRuning timerRuningListener) {
this.timerRuningListener = timerRuningListener;
}

public interface TimerRuning {
void onTimerChange(String remainSec, String startSec);

void onTimerStopped(String remainSec, String startSec);
}

public void stopTimer() {
if (timer != null) {
timerRuningListener.onTimerStopped(createDateFormat(0), createDateFormat(0));
isRunning = false;
timer.cancel();
}
}

}

Countdown timers in the background updating the ui

You need to use service and broadcast receiver .
I have created some example for broadcast receiver for you .

Check it and let me know if you have some issues.

Create a service :TimerService.java

 @Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Initialize and start the counter
countDown = new HokusFocusCountDownTimer(timeDifference, 1000);

countDown.start();

return super.onStartCommand(intent, flags, startId);
}

In MainActivity.java

/*
* This is used to receive the updated time from broadcast receiver
* */
private final BroadcastReceiver timeBroadCaster = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//method used to update your GUI fields
updateGUI(intent);
}
};

private void updateGUI(Intent intent) {

AppLog.showLog("Update UI", "Timer Stopped");

if (intent.getExtras() != null) {

String focusHMS = intent.getStringExtra(Constants.HOCUS_FOCUS_TIMER);
focusMilliSecond = intent.getLongExtra(Constants.HOCUS_FOCUS_TIMER_MILLI_SECOND, 0);
txtFocusHourTimer.setText("" + focusHMS);
}
}

@Override
public void onResume() {
super.onResume();
registerReceiver(timeBroadCaster, new IntentFilter(
HokusFocusCountDownTimer.COUNTDOWN_BROADCAST_RECEIVER));

}

@Override
public void onPause() {
super.onPause();
try {
unregisterReceiver(timeBroadCaster);
} catch (Exception e) {
e.printStackTrace();
}

}

Hope my answer would be helpful to you

Android update textview timer and refresh map content?

This will demo a countdown from 15 to 0 (-1 at a second), and this task will repeat again after every 15 seconds!

    public class YourActivity extends Activity {

TextView textView;
android.os.Handler customHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
textView = (TextView) findViewById(R.id.text);

customHandler = new android.os.Handler();
customHandler.postDelayed(updateTimerThread, 0);
}

// count down timer is an abstract class, so extend it and fill in methods
public class MyCount extends CountDownTimer {

public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}

@Override
public void onFinish() {
textView.setText("done!");
}

@Override
public void onTick(long millisUntilFinished) {
textView.setText("Left: " + millisUntilFinished / 1000);
}
}

private Runnable updateTimerThread = new Runnable()
{
public void run()
{

// 10000 is the starting number (in milliseconds)
// 1000 is the number to count down each time (in milliseconds)
MyCount counter = new MyCount(15000, 1000);
counter.start();
customHandler.postDelayed(this, 15000); // repeat body after 15 seconds
}
};
}

Updating the List UI with Timer

Create a customHandler class that extends Handler class and call the sendEmptyMessage() of handler from the timer run() method.

In the Handler class override the handleMessage and update your listview values and call adapter.notifyDataSetChanged() which will refresh the listview with the updated values.

Here is the sample code :

Timer timer = new Timer();
CustomTimerTask customTimerTask = new CustomTimerTask();
customTimerTask.run();
timer.scheduleAtFixedRate(customTimerTask, 1000 , 1000);

class CustomTimerTask extends TimerTask {

@Override
public void run() {
myHandler.sendEmptyMessage(0);
}
}

class CustomHandler extends Handler{

@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
/// Do your listview update thing
}

}

How to do a timer based update to a text view on Android

I found out that a CountDownTimer worked perfectly for my situation. Its not clear why the snippet I posted does not work but in any case thanks for all the replies.



Related Topics



Leave a reply



Submit