I'm trying to make a popup which is supposed to count down from 90sec to zero. I'm using the CountDownTimer method, but somewhere the an error because it doesn't do anything.
Here is the code that I have:
final AlertDialog.Builder popup_timer = new AlertDialog.Builder(ScoreNewGame.this);
popup_timer.setTitle("Timer:\t90 sec between games");
popup_timer.setPositiveButton("Skip", new DialogInterface.OnClickListener()
new CountDownTimer(90000, 1000)
{
public void onTick(long millisUntilFinished)
{
popup_timer.setMessage("seconds remaining:\t"+millisUntilFinished);
}
#Override
public void onFinish()
{
popup_timer.setMessage("Begin next set");
}
}.start();
popup_timer.show();
The AlertDialog only show the Title and the skip button, but no CountDownTimer, any ideas?
Related
How can I pause the countdownTimer if a dialog need to appear first. What can I do so that the timer will not start until I click the ok button.
countDownTimer = new CountDownTimer(320000, 1200) {
#Override
public void onTick(long l) {
timeText.setText(String.valueOf(timeValue));
timeValue = timeValue - 1;
if (timeValue == -1){
FLAG = 3;
playAudio.setAudioforEvent(FLAG);
timerDialog.timerDialog();
countDownTimer.cancel();
dbHandler.addScore2(tag,Integer.parseInt(txtCorrect.getText().toString()));
}
}
#Override
public void onFinish() {
// timerDialog.timerDialog();
}
}.start();
This is the dialog that will appear first.
public void fillDialog(){
fillDialog = new Dialog(mnContext);
fillDialog.setContentView(R.layout.activity_instruction_fill);
final Button btdialog = (Button) fillDialog.findViewById(R.id.ok_btn_fill);
btdialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fillDialog.dismiss();
}
});
You can use the countdownTimer.cancel() method to pause the countdown timer. When the dialog appears, call this method to pause the timer. When the user clicks the "OK" button on the dialog, you can then call the countdownTimer.start() method to resume the timer from where it left off.
Alternatively, you can also use countdownTimer.pause() and countdownTimer.resume() to pause and resume the timer.
It would be good to keep in mind that countdownTimer is a android class and you need to call the above methods from your activity class
I'm working on app which is required user in active feature like if user is not available on the application more than 15 min. it shows some popup on the last activity we used, when we click okay it redirects to login screen.
It is working absolutely fine when i opened back my app exactly after 15 minutes to around 30 minutes .
My problem is now, when i open my app after 45 min or more than 1 hour, it doesn't work, it doesn't show in activity popup. it just opened the last activity i used.
I tried with below code added in splash activity:
if (!isTaskRoot()
&& getIntent().hasCategory(Intent.CATEGORY_LAUNCHER)
&& getIntent().getAction() != null
&& getIntent().getAction().equals(Intent.ACTION_MAIN)) {
finish();
return;
}
Here is my BaseActivity class used for in active state checking
public class MyBaseActivity extends AppCompatActivity {
AlertDialog alertDialog;
Context context;
public static final long DISCONNECT_TIMEOUT = 900000; // 15 min = 15 * 60 * 1000 ms
private Handler disconnectHandler = new Handler(){
public void handleMessage(Message msg) {
}
};
private Runnable disconnectCallback = new Runnable() {
#Override
public void run() {
LayoutInflater li = LayoutInflater.from(MyBaseActivity.this);
View promptsView = li.inflate(R.layout.acount_status_dialogue, null);
final TextView userInput = (TextView) promptsView.findViewById(R.id.txtTitle);
final TextView userInput1 = (TextView) promptsView.findViewById(R.id.txtTitle1);
userInput1.setText("USER IN-ACTIVE");
userInput.setText("Due to user is inactive from last 15 minutes. Please Login Again");
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MyBaseActivity.this,R.style.DialogLevelsStyle);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//do things
Intent i = new Intent(MyBaseActivity.this, SignInActivity.class);
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
Constant.val = 1;
AccountUtils.setValue("1");
}
});
// create alert dialog
alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
// Perform any required operation on disconnect
}
};
public void resetDisconnectTimer(){
Log.i("Main", "Invoking logout timer");
//disconnectHandler.removeCallbacks(disconnectCallback);
disconnectHandler.postDelayed(disconnectCallback, DISCONNECT_TIMEOUT);
}
public void stopDisconnectTimer(){
Log.i("Main", "cancel timer");
disconnectHandler.removeCallbacks(disconnectCallback);
}
#Override
public void onUserInteraction(){
resetDisconnectTimer();
}
#Override
public void onResume() {
super.onResume();
resetDisconnectTimer();
}
#Override
public void onStop() {
if (Constant.isAppIsInBackground(this)) {
stopDisconnectTimer();
resetDisconnectTimer();
}else {
stopDisconnectTimer();
}
super.onStop();
//stopDisconnectTimer();
}
}
Please find out my issue. thanks in advance.
Save the current time when the user put your app to background (for example in SharedPreferences), and when the user starts again your app calculate the diff and show what you want on the screen.
I want my alert to be appear for 15 minutes when user click button 5 times.Please help me I am not able to understand handler in android.
if(btn_count==5){
handler = new Handler();
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
alert("Your account has been blocked for 15 minutes due to 5 unsuccessfull attempts.");
btn_count=0;
} catch (Exception e) {
// error, do something
}
}
});
}
};
timer.schedule(task, 0, 60*1000);
try to put this in alert dialog method
Step 1 : change this
if(btn_count==5){
alert("Your account has been blocked for 15 minutes due to 5 unsuccessfull attempts.");
}
Step 2 : Put this in alert code
btn_count= 0;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
dismiss();
}
}, 900000);
Try this
new Handler().postDelayed(() -> {
//Show the Alert here
}, 90000);
if(btn_count==5){
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.loader);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
new CountDownTimer(900000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
dialog.dismiss();
}
}.start();
}
First don't use Handler inside Timer only use Handler which are better.
Have one variable that stores clicks
private int clickCount = 0;
and in onClick() of your button do like this
#Override
public void onClick(View view){
if(v == btn_login && clickCount < 5){
if(WrongPassword){
clickCount++;
if(clickCount == 5){
showAlert();
}
}else{
clickCount = 0;
// put your login code here
}
}
}
private long mLastClickTime = 0
private void showAlert(){
mLastClickTime = SystemClock.elapsedRealtime();
alert("Your account has been blocked for 15 minutes due to 5 unsuccessfull attempts.");
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putLong("mLastClickTime", mLastClickTime);
editor.commit();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
dismiss();
clickCount = 0;
}
}, 900000);
}
and finally in onCreate() you need to check that previously user have tried more than 5 times or not(in case user kills the app an come back immediately)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
Long oldLastClick = prefs.getLong("mLastClickTime", 0);
if (oldLastClick != 0) {
Long currentTime = SystemClock.elapsedRealtime();
if((currentTime < oldLastClick) < 90000){
clickCount = 5;
alert("Your account has been blocked for 15 minutes due to 5 unsuccessfull attempts.");
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
dismiss();
clickCount = 0;
}
}, (currentTime - oldLastClick));
return;
}
}
}
#Shivangi, I believe that CountDownTimer is best match to your requirement because you can update UI thread from there as well.
You can achieve this in following way:
Set a count so that you can have button click count.
if(btnClickCount == 5)
{
//Show alert to user
Toast.makeText(getBaseContext(), "You account locked for next 15 min.", Toast.LENGTH_SHORT).show();
//Pretended that you have login button like this.
//Disable login button so that user will not click this until it enabled again after so called 15 minute
btnLogin.setEnabled(false);
//Start count down timer from 15 minute like this
CountDownTimer countDownTimer = new CountDownTimer(900000, 1000) {
#Override
public void onTick(long millisUntilFinished)
{
//You can update your UI here if you want,like time remaining for re-login attempt. So that user UX appear good. It'll be called every second as I set it to 1000.
// You can user a dialog to show time remaining to unlock account and use this method to get formatted time
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));
//Output will be like this 00:14:59
}
#Override
public void onFinish()
{
//Enable button as 15 minute lock period is over. and reset the button click counter
btnClickCount = 0;
btnLogin.setEnabled(true);
}
}.start();
}
You can break down this code into function as well.
Thanks
So I have this "hack" to have a toast duration a little bit longer:
// Toast...
zanimivosti = new Toast(getApplicationContext());
zanimivosti.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
zanimivosti.setView(layout);
new CountDownTimer(4000, 1000) {
public void onTick(long millisUntilFinished) {
zanimivosti.show();
}
public void onFinish() {
zanimivosti.show();
}
}.start();
PROBLEM: When a user go to another intent, it can happen that the toast reaper again in new intent.
In my case CountDownTimer.cancel(); won't work
ALTERNATIVE:
In my toast I am displaying news every time the user lunch the app. I would also take in consideration a better solution whit a toast that when a user click on it disappear or when new intent is called also disappear.
Should I use a pop up dialog? Can I make it disappear when user clicks on it?
At the end I did it like this:
Toast zanimivosti;
int cas = 4000;
int perioda = 1000;
boolean boolean_toast = true;
CountDownTimer timer;
timer = new CountDownTimer(time, perioda) {
public void onTick(long millisUntilFinished) {
zanimivosti.show();
}
public void onFinish() {
if (boolean_toast == true) {
zanimivosti.show();
} else {
}
}
}.start();
And stoping the timer with stopping/cancelling all the possible things:
boolean_toast = false;
time = 0;
perioda = 0;
timer.cancel();
zanimivosti.cancel();
I have an app that runs a countdown timer and brings up an alertbox when the timer runs out so that the game can restart. Unfortunately, when I hit the back button and open up the app again, it crashes around the time when the original countdowntimer should have run out.
The following code is located in onCreate of my Activity.
CountDownTimer cdt = new CountDownTimer(totalTime*1000, 1000) {
public void onTick(long millisUntilFinished) {
time = (int) ((millisUntilFinished)/1000)*100/totalTime;
TimeBar.setProgress(time);
}
public void onFinish() {
time = 0;
TimeBar.setProgress(time);
AlertDialog.Builder alertbox = new AlertDialog.Builder(mContext);
alertbox.setMessage("Sweet! " + score + " points!");
alertbox.setPositiveButton("Leaderboard", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
ScoreloopManagerSingleton.get().onGamePlayEnded((double) score, null);
startActivity(new Intent(BubblesActivity.this, LeaderboardsScreenActivity.class));
BubblesActivity.this.finish();
}
});
alertbox.setNeutralButton("Replay", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
BubblesActivity.this.finish();
startActivity(new Intent(BubblesActivity.this, BubblesActivity.class));
}
});
if(alertbox!= null)
alertbox.show();
}
}.start();
Without a stack trace it's hard to say what happens but it most likely has something to do you referencing a dead Activity from your CountDownTimer.
Calling enter code hereCountDownTimer.cancel() in onDestroy() would probably solve this.