android CountDownTimer lag - android

im trying CountDownTimer on android studio and it works fine, but after about 5 minutes passed apps seems to badly lag. how to prevent this?
*note :
my logcat give this warning "Skipped 60 frames! The application may be doing too much work on its main thread."
and im using this CountDownTimer for a listview, so there is a CountDownTimer as listview item (if the item less or equal to 2 items there is no problem so far).
here is my code :
int milis = Integer.valueOf(timeinseconds[position]);
myTimer = new CountDownTimer(milis, 1000) {
public void onTick(long millisUntilFinished) {
tempminute = (int) Math.floor((millisUntilFinished/1000)/60);
minutes = tempminute%60;
seconds = (int) (millisUntilFinished/1000)%60;
hours = tempminute/60;
vouchercountdown.setText("00 day " + hours + " hr " + minutes + " min " + seconds + " sec");
}
public void onFinish() {
vouchercountdown.setText("00 day 00 hr 00 min 00 sec");
}
};
Runnable mHandlerTask = new Runnable() {
#Override
public void run() {
myTimer.start();
}
};
mHandlerTask.run();
Thanks

Related

How to display Time in appropriate way ( Min:Sec)?

I'm coding a media player app but the Time (for seekbar) appears incorrectly. Is there an error in calculation? How can I adjust the Time in the code?
private void updateSeekBar() {
seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / mediaFileLength)*100));
if(mediaPlayer.isPlaying())
{
Runnable updater = new Runnable() {
#Override
public void run() {
updateSeekBar();
realtimeLength-=1000; // declare 1 second
textView.setText(String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes(realtimeLength),
TimeUnit.MILLISECONDS.toSeconds(realtimeLength) -
TimeUnit.MILLISECONDS.toSeconds(TimeUnit.MILLISECONDS.toMinutes(realtimeLength))));
}
};
handler.postDelayed(updater,1000); // 1 second
}
}
You are calculating the seconds incorrectly. You need to multiply the minutes by 60 and then subtract it from total seconds to get the seconds in this minute.
TimeUnit.MILLISECONDS.toSeconds(realtimeLength) - 60 * TimeUnit.MILLISECONDS.toMinutes(realtimeLength)
This should work.
You should use Debugger to try to debug why your output is incorrect.
Please pass duration in below method & it will give you formatted result back.
long secs = mediaPlayer.getDuration()/1000;
public String makeShortTimeString(final Context context, long secs) {
long hours, mins;
hours = secs / 3600;
secs %= 3600;
mins = secs / 60;
secs %= 60;
String durationFormat = context.getResources().getString(
hours == 0 ? R.string.durationformatshort : R.string.durationformatlong);
return String.format(durationFormat, hours, mins, secs);
}
where durationformatshort = %2$d:%3$02d
and durationformatlong = %1$d:%2$02d:%3$02d

why countdown counter with thread show wrong value?

I don't know why this count down counter shows a random number at the end?
I mean that it sometimes shows 60:15, sometimes 60:07, so on this way
min=sec=0;
new Thread(new Runnable() {
#Override
public void run() {
while (min < 60 && flagTime) {
try {
Thread.sleep(1);
G.HANDLER.post(new Runnable() {
#Override
public void run() {
String preSec="";
String preMin="";
if (sec < 59) {
sec += 1;
}
if (sec < 10) {
preSec = "0";
}
if (min < 10) {
preMin = "0";
}
score =preMin + min + ":"
+ preSec + sec;
txt[elementNumber + 1].setText(score);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
Please someone tell me why it works so weird?
Timing in ALL OSes is NOT precise, unless you use a framework or tools that is already designed for this task. You can however work with Thread.Sleep with a reasonable uncertainty. But for "reasonable" and "precise" timing, it depends on the problem you are trying to solve.
In threads, sleep(1000) does not mean that the thread will sleep exactly 1 second, so that the thread will sleep less or more every time you run your app. that is why you get random results.
This has many things else to consider like the priority of the thread.
so a better way to count down is to use other ways which is provided by android:
CountDownTimer
Timer
you may check on google and you will find many examples about how to use them.
those are more reliable and more precise.
hope this helps.
The likely reason that you're getting weird results in your TextView is that you're updating it from a thread that is not the main UI thread.
But you're making this harder than it needs to be. An easier approach would be to use a simple CountDownTimer object like this:
final long SECS_IN_1_MIN = 60;
final long MILLIS_IN_1_SEC = 1000;
final long MILLIS_IN_60_MINS = 3600000;
final TextView timer = (TextView) findViewById(R.id.timer);
new CountDownTimer(MILLIS_IN_60_MINS, MILLIS_IN_1_SEC) {
public void onTick(long millisUntilFinished) {
if (flagTime) {
long secs = (MILLIS_IN_60_MINS - millisUntilFinished) / MILLIS_IN_1_SEC;
timer.setText(String.format("%02d:%02d", secs / SECS_IN_1_MIN, secs % SECS_IN_1_MIN));
} else {
timer.setText("cancelled");
cancel();
}
}
public void onFinish() {
timer.setText("time expired");
}
}.start();
Edit: It uses a CountDownTimer to handle the timing, while using its millisUntilFinished value to calculate and display what appears to be an increasing seconds count. I threw in some symbolic names to make the code clearer and a String.format to handle single digit values in a more elegant fashion. Enjoy!

Android: Updating int ever second

I am creating a text file with data related to my App's game.
I want to show the score at each second in the game.
How can I ensure that my int for seconds is updated, starting at zero
Example of output wanted:
Seconds Score
0 3
1 9
2 16
3 20
.....etc
Current output (seconds always 0):
Seconds Score
0 3
0 9
0 16
0 20
.....etc
Current code:
int seconds=0;
//creating header in the txt file Note: Blanked out as it is generating every second
writeToFileEEGPower(order("Seconds")+order("highAlpha")+order("lowAlpha")+order("highBeta")+order("LowBeta")+
order("lowGamma")+order("midGamma")+order("Delta")+order("Theta")+ "\n");
//creating the string to be written to file
String line = order(seconds+"")+order(eegPower.highAlpha+"")+order(eegPower.lowAlpha+"")+order(eegPower.highBeta+"")+
order(eegPower.lowBeta+"")+order(eegPower.midGamma+"")+order(eegPower.delta+"")+order(eegPower.theta+"")+ "\n";
//write the string to file
writeToFileEEGPower(line);
seconds++;
I think you should rather use a sqlite table for this. Greendao
is a good tool for managing those tables. You can save the information every second to a table. When the game is finished, you have a full list of the score for each second of the game.
In your code example the "second" variable is set to 0 each time before you write a new line. I think that is the problem.
Using TimerTask or Handler with postDelayed() method can do the trick.
You can use a handler to update your text file every second:
public class MyActivity extends Activity {
private android.os.Handler mHandler = new android.os.Handler();
private Runnable textFileLogger;
private int seconds = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
//Create header for text file
writeToFileEEGPower(order("Seconds") + order("highAlpha") + order("lowAlpha") + order("highBeta") + order("LowBeta") +
order("lowGamma") + order("midGamma") + order("Delta") + order("Theta") + "\n");
textFileLogger = new Runnable() {
#Override
public void run() {
seconds++;
String line = order(seconds + "") + order(eegPower.highAlpha + "") + order(eegPower.lowAlpha + "") + order(eegPower.highBeta + "") +
order(eegPower.lowBeta + "") + order(eegPower.midGamma + "") + order(eegPower.delta + "") + order(eegPower.theta + "") + "\n";
//write the string to file
writeToFileEEGPower(line);
//Repeats the logging after 1 second
mHandler.postDelayed(this, 1000);
}
};
//Starts the logging after 1 second
mHandler.postDelayed(textFileLogger, 1000);
}
#Override
protected void onDestroy() {
super.onDestroy();
//To stop the logging:
mHandler.removeCallbacks(textFileLogger);
}
}

Problems creating timer in android

I am trying to build a timer that counts down in seconds and updates a TextView every time so it shows the time remaining. From what I can tell the timer code is working fine (1 second between events and converts from hrs and mins to secs fine) cause I have tested it outside of Android and using Log.d() in android. Updating the textview is whats giving me problems. I was getting null pointers when originally trying to update the textview cause only the UI thread can access the UI(my interpretation of the error message) and I added the runOnUiThread() which allows it to be accessed and updated but it now doesn't update correctly. I think this is where the problem lies but I am not totally sure and don't know enough to figure out how to fix it or come up with a better way to do this. I would appreciate another set of eyes. Thanks
final static int delay = 1000;
final static int period = 1000;
public void start(int hin, int min) {
run = true;
int hrinsec = (hin * (60 * 60));
int mininsec = (min * 60);
secs = hrinsec + mininsec;
run = false;
interval = secs;
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
public void run() {
// Convert seconds back to hrs and mins
hrsFromSecs(secs);
minsFromSecs(secs);
secsFromSecs(secs);
dint total = hours + minutes + seconds;
output = hours + " Hours " + minutes + " Minutes " + seconds
+ " Seconds";
// Countdown and update the textview
runOnUiThread(new Runnable() {
#Override
public void run() {
timer.setText(output);
}});
secs = secs - 1;
checkIfDone(total);
}
}, delay, period);
}
Use CountDownTimer no need to reinvent anything

Android rolling digital time display wanted

I'm looking for Android code to do a digital timer display that looks like one of the standard timers that came (I think) with some HTC phones. The timer look is different than most in that it uses digits but has a mechanical scroll wheel look, as if the numbers were painted on a roller. It does not mimic an LED timer nor does it mimic a mechanic "flip" type digital timer. It may need graphic files to work.
There is code on googlesource that seems it may have what I want. But I can't find any index that has images of the code running. And it is not always easy (for me) to get the code running so I can see what it looks like. Some code that looks promising is the following:
(https://android.googlesource.com/device/htc/common/)
http://st.gsmarena.com/vv/reviewsimg/htc-droid-incredible-4g-lte/sshots/gsmarena_109.jpg">Link to image</a>">
See http://code.google.com/p/android-wheel/
You might be able to adapt it for your needs.
Here's code provided by a previous user:
private Handler mHandler = new Handler();
OnClickListener mStartListener = new OnClickListener()
{
public void onClick(View v)
{
if (mStartTime == 0L)
{
mStartTime = System.currentTimeMillis();
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
}
}
};
.........
private Runnable mUpdateTimeTask = new Runnable()
{
public void run()
{
final long start = mStartTime;
long millis = SystemClock.uptimeMillis() - start;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
if (seconds < 10)
{
mTimeLabel.setText("" + minutes + ":0" + seconds);
}
else
{
mTimeLabel.setText("" + minutes + ":" + seconds);
}
mHandler.postAtTime(this,start + (((minutes * 60) + seconds + 1) * 1000));
}
};
https://stackoverflow.com/users/559090/khawar

Categories

Resources