I'm looking for some solution which will be faster than mine. I get a time difference between current time and my saved, next step is to put the time in TextView. This solution works but it makes my app very slowly. Does anyone know faster solution?
Thread counter = new Thread(){
public void run()
{
long saved
long difference;
while(true)
{
saved = Long.parseLong(getString(c, "0", "saved"));// sharedPreferences
difference = System.currentTimeMillis() - saved;
seconds = (int) (difference / 1000) % 60;
difference-=seconds;
minutes= (int)((difference/ 60000 ) % 60);
difference=minutes;
hours = (int) ((difference/ 3600000) % 24);
days = (int) ((difference/86400000) % 30);
difference-=days;
months= (int) ((difference/2592000)/1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
myTextView5.setText(Integer.toString(seconds));
myTextView4.setText(Integer.toString(minutes));
myTextView3.setText(Integer.toString(hours));
myTextView2.setText(Integer.toString(days));
myTextView1.setText(Integer.toString(months));
}
});
Your precision is 1s - so you can Thread.sleep (1000) in the while without missing a beat.
I would recommend the use of JodaTime library.
DateTime saved = //getSaved;
DateTime diff = DateTime.now().minus(saved);
//update TextView
txtView.setText(diff.getSecondsOfMinute().toString());
According to my understanding you are using runOnUiThread that created temporary shortlife objects that is the main reason your code is running slow because in each iteration it does it created a new instance of Runnable class and then updates your UI.
Read this topic to get a good understanding of Communication with Ui Thread
http://developer.android.com/training/multiple-threads/communicate-ui.html
You can use Handlers to overcome this issue all you need to do is pass message to handler and it will do the job for you.
This is how you do it.
First of all create a custom handler class
public class CustomMessageHandler extends Handler {
private IUpdateAudioProgressListView iUpdateRef;
public void setOnProgressUpdatedListner(IUpdateAudioProgressListView ref) {
this.iUpdateRef = ref;
}
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
YOUR HANDLING CODE HERE ......................
}
}
then in order to send message to UI thread from a custom thread you need to do following things
initialize a class level variable in your thread class like
public class Test {
CustomMessageHandler handler;
public Test() {
handler = new CustomMessageHandler();
Thread counter = new Thread() {
public void run() {
long saved
long difference;
while (true) {
saved = Long.parseLong(getString(c, "0", "saved"));// sharedPreferences
difference = System.currentTimeMillis() - saved;
seconds = (int) (difference / 1000) % 60;
difference -= seconds;
minutes = (int) ((difference / 60000) % 60);
difference = minutes;
hours = (int) ((difference / 3600000) % 24);
days = (int) ((difference / 86400000) % 30);
difference -= days;
months = (int) ((difference / 2592000) / 1000);
Message msg = handler.obtainMessage();
msg.obj = // send all your variables via a class or whatever logic you use
handler.sendMessage(msg);
}
}
};
}
}
If you don't want to use an external library, I would suggest the use of java.util.Calendar (Don't forget to import that!). For your solution, every time your value in SharedPreferences is changed, just run the code below.
Code to calc diff
Calendar c = Calendar.getInstance();
c.setTimeInMillis(difference);
int months = c.get(Calendar.MONTH);
int days = c.get(Calendar.DAY_OF_MONTH);
int hours = c.get(Calendar.HOUR_OF_DAY);
int minutes = c.get(Calendar.MINUTE);
int seconds = c.get(Calendar.SECOND);
myTextView5.setText(Integer.toString(seconds));
myTextView4.setText(Integer.toString(minutes));
myTextView3.setText(Integer.toString(hours));
myTextView2.setText(Integer.toString(days));
myTextView1.setText(Integer.toString(months));
Detect change in preferences
public class MyPreferences extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// handle the preference change here
}
}
Related
I am new to Android and Java and I have been trying to solve an issue on timers.Please help
I have an App where the user can create multiple countdown timers and multiple stopwatches.
Example code of countdown timer is given below .(Stop watch is also implemented in a similar fashion using handler). I want the timers and stopwatches to run in the background even when the user leaves the app.And the current state of timers should be shown when the user comes back to the app again,rather than showing the initial state.
The problem is my timers and stopwatches are running when I leave the app,but the results are not published into the UI when the user comes back to the app. A new instance is created and the fresh timers with 00:00:00 are shown again,while the old timers keep running in the background and goes on without being able to stop.Also in the following code I have a listener which publishes the result into the UI in its callback.This interface is implemented in my activity. So can anyone please suggest a solution for this ?
public class CountDownTimerService {
public interface CounterTimeChangeListener {
public void onCounterTimeChange(String time,Boolean counterFinished);
}
CounterTimeChangeListener listener;
MyCountDownTimer myCountDownTimer;
String output;
int length;
long startTime = 0;
long currentTime = 0;
long timeElapsed = 0;
long timeRemaining = 0;
long prevTimeRemaining = 0;
public CountDownTimerService(int countDownFutureTime)
{
myCountDownTimer= new MyCountDownTimer(countDownFutureTime,1000);
length=countDownFutureTime;
}
// code for countdown timer
// this function format the time to hours seconds and minutes format
public String formatTime(long mills)
{
output = "";
long seconds = mills / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
seconds = seconds % 60;
minutes = minutes % 60;
hours = hours % 60;
String secondsD = String.valueOf(seconds);
String minutesD = String.valueOf(minutes);
String hoursD = String.valueOf(hours);
if (seconds < 10)
secondsD = "0" + seconds;
if (minutes < 10)
minutesD = "0" + minutes;
if (hours < 10)
hoursD = "0" + hours;
output = hoursD +":" +minutesD +":"+ secondsD;
return output;
}
// this function is called on start button click
public void CountDownControl(int state) {
if(state==0)
{
startTime = System.currentTimeMillis();
myCountDownTimer.start();
}
else if(state==1)
{
// when the pause is clicked
myCountDownTimer.cancel();
currentTime = System.currentTimeMillis();
timeElapsed = currentTime - startTime;
if (prevTimeRemaining == 0)
timeRemaining = length - timeElapsed;
else
timeRemaining = prevTimeRemaining - timeElapsed;
prevTimeRemaining = timeRemaining;
myCountDownTimer= new MyCountDownTimer(timeRemaining,1000);
if (listener!=null) {
listener.onCounterTimeChange(formatTime(timeRemaining), false);
}
}
}
// this function is called on reset button click
public void resetInitial()
{
prevTimeRemaining = 0;
myCountDownTimer.cancel();
if (listener!=null) {
listener.onCounterTimeChange(formatTime(length),false);
}
myCountDownTimer= new MyCountDownTimer(length,1000);
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
public void onTick (long millisUntilFinished) {
// calls the fragment's callback function passing the time value
Log.e("in counter","1");
if (listener!=null) {
Log.e("in counter","2");
listener.onCounterTimeChange(formatTime(millisUntilFinished), false);
}
}
public void onFinish() {
/*
* write code for an alarm when timer times out
*
* */
prevTimeRemaining = 0;
if (listener!=null) {
listener.onCounterTimeChange(formatTime(length),true);
}
myCountDownTimer= new MyCountDownTimer(length,1000);
}
}
public void setCounterTimeChangeListener(CounterTimeChangeListener listener) {
this.listener = listener;
}
}
I'm trying to make a count down time loop.
I want it to make it loop till "int x" reaches 100.
I've tried adding a do/while and a for loop but I think I'm doing it wrong.
Any suggestions?
Thanks for looking. :-) `
public class MainActivity extends Activity{
Button buttonStartTime;
// clicking this button will start time count down
TextView textViewShowTime; // will show the time
TextView shots;
CountDownTimer countDownTimer; // built in android class CountDownTimer
long totalTimeCountInMilliseconds; // total count down time in milliseconds
long timeBlinkInMilliseconds; // start time of start blinking
boolean blink; // controls the blinking .. on and off
static int x = 3;
int whole = 100;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getReferenceOfViews (); // get all views
setActionListeners (); // set action listerns
totalTimeCountInMilliseconds = 60 * 1000; // time count for 3 minutes = 180 seconds
timeBlinkInMilliseconds = 10 * 1000; // blink starts at 1 minutes = 60 seconds
}
private void setActionListeners() {
buttonStartTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textViewShowTime.setTextAppearance(getApplicationContext(), R.style.normalText);
countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 500) {
// 500 means, onTick function will be called at every 500 milliseconds
#Override
public void onTick(long leftTimeInMilliseconds) {
long seconds = leftTimeInMilliseconds / 1000;
if ( leftTimeInMilliseconds < timeBlinkInMilliseconds ) {
textViewShowTime.setTextAppearance(getApplicationContext(), R.style.blinkText);
// change the style of the textview .. giving a red alert style
if ( blink ) {
textViewShowTime.setVisibility(View.VISIBLE);
// if blink is true, textview will be visible
} else {
textViewShowTime.setVisibility(View.INVISIBLE);
}
blink = !blink; // toggle the value of blink
}
textViewShowTime.setText(String.format("%02d", seconds / 60) + ":" + String.format("%02d", seconds % 60));
// format the textview to show the easily readable format
}
#Override
public void onFinish() {
x++;
// this function will be called when the timecount is finished
textViewShowTime.setText("SHOT!!!");
textViewShowTime.setVisibility(View.VISIBLE);
}
}
.start();
}
});
}
private void getReferenceOfViews() {
buttonStartTime = (Button) findViewById(R.id.btnStartTime);
textViewShowTime = (TextView) findViewById(R.id.tvTimeCount);
}
}`
totalTimeCountInMilliseconds =1000 * 1000; // time count for 3 minutes = 180 seconds
timeBlinkInMilliseconds = 10 * 1000; // blink starts at 1 minutes = 60 seconds
new CountDownTimer(totalTimeCountInMilliseconds , timeBlinkInMilliseconds )
above will call onTick 100 times
Let me preface that I'm new to programming for Android. I've been doing my due diligence to research to no avail. I have the source code below and I'm having issues with returning the value for returning.
I have the code laid out on eclipse and it's not triggering any errors. But when I build the code below, it comes back with an error. After inspecting the values in debug view, I can see the proper values just not binded to the TextView.
public class MyFirstActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
calculateResult(2012, 9, 29);
}
private void calculateResult(int year, int month, int day) {
long days = 0L;
int returning = 0;
java.util.Calendar cal = new java.util.GregorianCalendar(year, month-1, day);
long todayMI = new java.util.Date().getTime();
long calMI = cal.getTimeInMillis();
long millDiff = calMI - todayMI;
if (millDiff < 0) {
returning = 0;
} else {
days = millDiff / 1000 / 60 / 60;
returning = (int) Math.ceil(days / 24f);
}
TextView days_int_remaining = (TextView) findViewById(R.id.days_int_remaining);
days_int_remaining.setText(returning);
}
}
If it helps, here's the TextView on my layout XML:
<TextView
android:id="#+id/days_int_remaining"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:shadowColor="#5000"
android:shadowDx="4"
android:shadowDy="3"
android:shadowRadius="1"
android:textColor="#fff"
android:textSize="70dip"
android:textStyle="bold"
/>
It may be something simple that I'm missing. Anything to help me further understand the code is appreciated!
I believe that the error you get is "runtime-error - close application".
If you look at method setText(...) that is overloaded you will see that it takes arguments with CharSequence (this is probably what you want) and int resId (this is what you provide).
resId - will seek if there is an resource in /values/strings.xml with given name attribute.
The resolution is to provide String:
days_int_remaining.setText(String.valueOf(returning));
just use
TextView days_int_remaining = (TextView) findViewById(R.id.days_int_remaining);
days_int_remaining.setText(String.valueOf(returning));
instead of
TextView days_int_remaining = (TextView) findViewById(R.id.days_int_remaining);
days_int_remaining.setText(returning);
Turn your returning int into a string.
Try this code :
Basically you have to convert your int value to a string before calling setText();
public class MyFirstActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView days_int_remaining = (TextView) findViewById(R.id.days_int_remaining);
int resultat = calculateResult(2012, 9, 29);
days_int_remaining.setText(Integer.toString(resultat));
}
private int calculateResult(int year, int month, int day) {
long days = 0L;
int returning = 0;
java.util.Calendar cal = new java.util.GregorianCalendar(year, month-1, day);
long todayMI = new java.util.Date().getTime();
long calMI = cal.getTimeInMillis();
long millDiff = calMI - todayMI;
if (millDiff < 0) {
returning = 0;
} else {
days = millDiff / 1000 / 60 / 60;
returning = (int) Math.ceil(days / 24f);
}
return returning;
}
}
I have got a TimePickerDialog working to set time which is set to a TextView in order to display it. Now, I need help to set that TimePicker (inside the TimePickerDialog) minutues interval to 15 minutes. I have seen there is a post with 15 minutes interval issue related to TimePicker, but I don't know how to apply it to the TimePickerDialog because I don't know how to use the TimePicker that it is created inside the TimePickerDialog. I am new to Android and completely lost in this matter. Thanks in advance.
Using a combination of this from #Rizwan and this other thread, I came up with a combined solution that allows arbitrary minute increments in a TimePickerDialog. The main issue is that most of the functionality is hidden by the android TimePickerDialog and TimePicker classes and it doesn't appear to allow
Extend TimePickerDialog to allow us easier access
Use reflection to reach inside the display and access the required bits (see below)
rewire the minute 'NumberPicker' to display our values
rewire the TimePicker to receive and return values form the NumberPicker honoring our custom increment.
block onStop() so that it doesn't reset the value on close.
Warning
The main issue with reaching inside the UI is that elements are referenced by ids which are likely to change, and even the name of the id is not guaranteed to be the same forever. Having said that, this is working, stable solution and likely to work for the foreseeable future. In my opinion the empty catch block should warn that the UI has changed and should fall back to the default (increment 1 minute) behaviour.
Solution
private class DurationTimePickDialog extends TimePickerDialog
{
final OnTimeSetListener mCallback;
TimePicker mTimePicker;
final int increment;
public DurationTimePickDialog(Context context, OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView, int increment)
{
super(context, callBack, hourOfDay, minute/increment, is24HourView);
this.mCallback = callBack;
this.increment = increment;
}
#Override
public void onClick(DialogInterface dialog, int which) {
if (mCallback != null && mTimePicker!=null) {
mTimePicker.clearFocus();
mCallback.onTimeSet(mTimePicker, mTimePicker.getCurrentHour(),
mTimePicker.getCurrentMinute()*increment);
}
}
#Override
protected void onStop()
{
// override and do nothing
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try
{
Class<?> rClass = Class.forName("com.android.internal.R$id");
Field timePicker = rClass.getField("timePicker");
this.mTimePicker = (TimePicker)findViewById(timePicker.getInt(null));
Field m = rClass.getField("minute");
NumberPicker mMinuteSpinner = (NumberPicker)mTimePicker.findViewById(m.getInt(null));
mMinuteSpinner.setMinValue(0);
mMinuteSpinner.setMaxValue((60/increment)-1);
List<String> displayedValues = new ArrayList<String>();
for(int i=0;i<60;i+=increment)
{
displayedValues.add(String.format("%02d", i));
}
mMinuteSpinner.setDisplayedValues(displayedValues.toArray(new String[0]));
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
constructor accepts the increment value and retains some other references. Note that this omits error checking and we'd prefer 60%increment==0
onCreate uses the name of the UI fields and reflection to discover the current location. Again this omits error checking and should be 'fail-safe' ie revert to default behaviour if something goes wrong.
onClick overridden to return the correct minute value to the callback listener
onStop overridden to prevent the (incorrect) index value being returned a second time, when the dialog closes. Go on, try it yourself.
Most of this comes from digging into the TimePickerDialog source.
UPDATE FOR ANDROID 11+
The reflection used in the example above was marked as greylist-max-q, meaning it would no longer be possible after Android 10 (API 29 - Q). In the short term (until August 2021) it is possible to drop the target version back to API 29 while still building against Android 11 (API 30 - R) but after this date the Play Store will no longer accept these builds and will require API 30 as the build target. This eventual failure was anticipated and noted in the warning above.
well thats fine if you used time-picker instead of time-picker-dialog. But there is a solution for this actually.. here is what I used to meet the same requirement.. I used CustomTimePickerDialog. Every thing will be same, only TimePickerDialog will change to CustomTimePickerDialog in the code.
CustomTimePickerDialog timePickerDialog = new CustomTimePickerDialog(myActivity.this, timeSetListener,
Calendar.getInstance().get(Calendar.HOUR),
CustomTimePickerDialog.getRoundedMinute(Calendar.getInstance().get(Calendar.MINUTE) + CustomTimePickerDialog.TIME_PICKER_INTERVAL),
false
);
timePickerDialog.setTitle("2. Select Time");
timePickerDialog.show();
Here is my CustomTimePickerDialog class... Just use this class in your project and change TimePickerDialog to CustomTimePickerDialog..
public class CustomTimePickerDialog extends TimePickerDialog{
public static final int TIME_PICKER_INTERVAL=10;
private boolean mIgnoreEvent=false;
public CustomTimePickerDialog(Context context, OnTimeSetListener callBack, int hourOfDay, int minute,
boolean is24HourView) {
super(context, callBack, hourOfDay, minute, is24HourView);
}
/*
* (non-Javadoc)
* #see android.app.TimePickerDialog#onTimeChanged(android.widget.TimePicker, int, int)
* Implements Time Change Interval
*/
#Override
public void onTimeChanged(TimePicker timePicker, int hourOfDay, int minute) {
super.onTimeChanged(timePicker, hourOfDay, minute);
this.setTitle("2. Select Time");
if (!mIgnoreEvent){
minute = getRoundedMinute(minute);
mIgnoreEvent=true;
timePicker.setCurrentMinute(minute);
mIgnoreEvent=false;
}
}
public static int getRoundedMinute(int minute){
if(minute % TIME_PICKER_INTERVAL != 0){
int minuteFloor = minute - (minute % TIME_PICKER_INTERVAL);
minute = minuteFloor + (minute == minuteFloor + 1 ? TIME_PICKER_INTERVAL : 0);
if (minute == 60) minute=0;
}
return minute;
}
}
After using this CustomTimePickerDialog class, All you will need to do is use CustomTimePickerDialog instead of TimePickerDialog in your code to access/override default functions of TimePickerDialog class. In the simple way, I mean your timeSetListener will be as following after this...
private CustomTimePickerDialog.OnTimeSetListener timeSetListener = new CustomTimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
}
}// using CustomTimePickerDialog
You can use a regular AlertDialog and use setView to include a custom TimePicker view.
/**
* Set TimePicker interval by adding a custom minutes list
* TIME_PICKER_INTERVAL = Enter your Minutes;
* #param timePicker
*/
private void setTimePickerInterval(TimePicker timePicker) {
try {
int TIME_PICKER_INTERVAL = 10;
NumberPicker minutePicker = (NumberPicker) timePicker.findViewById(Resources.getSystem().getIdentifier(
"minute", "id", "android"));
minutePicker.setMinValue(0);
minutePicker.setMaxValue((60 / TIME_PICKER_INTERVAL) - 1);
List<String> displayedValues = new ArrayList<String>();
for (int i = 0; i < 60; i += TIME_PICKER_INTERVAL) {
displayedValues.add(String.format("%02d", i));
}
minutePicker.setDisplayedValues(displayedValues.toArray(new String[0]));
} catch (Exception e) {
Log.e(TAG, "Exception: " + e);
}
}
This is the first time I am posting something on StackOverflow and that it only because I felt like this is one of those times I was not able to find what I needed from the vast Internet!
I am currently making an Android Application that is a game where I have an ball that is an imageview and each time I click on the ball, it moves to a random location with this method I've built:
private void changePos() {
RelativeLayout gameLayout = findViewById(R.id.gameFrame);
int frameHeight = gameLayout.getHeight();
int frameWidth = gameLayout.getWidth();
Random ballLocationY = new Random();
int ballY = ballLocationY.nextInt(frameHeight);
Random ballLocationX = new Random();
int ballX = ballLocationX.nextInt(frameWidth);
gameLayout.setY(ballY);
gameLayout.setX(ballX);
}
So what I am struggling with is to reduce the timer with each click.
What I am trying to do is to reduce the timer with each click on the ball by a certain percentage.
Basically each time the user clicks on the ball, the timer starts off from 0 and counting upwards in seconds and milliseconds, and at 3 second mark the game is over.
This is the approach I am playing around with:
Runnable updateThreadTimer = new Runnable() {
#Override
public void run() {
timeInMilliseconds = System.Clock.uptimeMillis() - startTime();
updateTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updateTime / 1000);
countDownText.setText("" + String.format("%2d", secs) + ":"
+ String.format("%3d", timeInMilliseconds));
mHandler.postDelayed(this, 0);
if (secs == 3 && timeInMilliseconds >= 3000) {
timeSwapBuff += timeInMilliseconds;
mHandler.removeCallbacks(updateThreadTimer);
}
}
}
Variables necessary:
long startTime = 0L, timeInMilliseconds = 0L, timeSwapBuff = 0L, updateTime = 0L;
Handler mHandler = new Handler();
And then I have this in the Overridden onCreate method:
ball.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
changePos();
startTime = SystemClock.uptimeMillis();
mHandler.postDelayed(updateThreadTimer, 0);
}
return true;
}
}
So what I get is a timer that gets reset to 0 with each click on the button and starts again. And the timer displays in seconds and milliseconds: 0:0000, which is what I wanted, but I wanna reduce a certain percentage with each click and update the time.
So let's say the counter starts with 3 seconds limit, after clicking on the ball couple of times, the timer should eventually come down and the game should fail if the timer goes above that time.
Obviously I have simplified the code quite a lot to get straight to the point.
I was wondering if anyone has any suggestions on how I could approach the problem I have.
I also want to apologize if the question is not asked properly, being the first time posting, leave suggestions if theres any hatin' going on!
And I also want to mention it one more time, I've looked around for a solution like this, and the code I have put together is from lots of different sources, so I feel like I've done my research, and not being able to find something, hence I am turning to StackOverflow!
So I guess I am going to answer my own question as I have solved it now and also in hope that this may solve problems for some.
I redid some parts of the code and scratched the Runnable way, instead I took an approach that uses CountDownTimer class.
private long currentTime;
private long maxTimer = 3000;
private double fivePercent = .05;
private CountDownTimer myTimer = null;
protected void onCreate(Bundle savedInstanceState) {
// Some code...
// Assign 3000 to currentTime
currentTime = maxTimer;
ball.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
if (myTimer != null) {
// Cancel timer
myTimer.cancel();
// Calculating 5 % from maxTimer
long a = (long) (maxTimer * fivePercent);
maxTimer -= a;
// Storing new maxTimer in currentTime
currentTime = maxTimer;
}
myTimer = new CountDownTimer(currentTime, 1) {
#Override
public void onTick(long millisUntilFinished) {
countDownText.setText("Time: " + String.valueOf(millisUntilFinished));
currentTime = millisUntilFinished;
}
#Override
public void onFinish() {
Intent intent = new Intent(getApplicationContext(), ResultsActivity.class);
GameActivity.this.startActivity(intent);
}
}.start();
changePos();
scoreLabel.setText("Score: " + score++ + "");
}
return true;
}
});
}
I have simplified the code for demonstration purpose, but basically what I did was to create a CountDownTimer, and whenever I click on the ball, the CountDownTimer will get cancelled, and invoke a new one, before creating a new CountDownTimer it will calculate off 5 % and put the result into the new CountDownTimer.