Can I use a Toast for the CountDownTimer - android

I want to use a Toast inside the CountdownTimer, but the problem is the Toast counts too slow and when the new Activity stars the Toast isn't finished counting.I know it is easier to use a TextView but I just wanted to know if it is possible.Any ideas?
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(Edt.getText().toString().length() == 0){
Toast.makeText(MainActivity.this,"What, bro?",Toast.LENGTH_LONG).show();
}else if(sec.getText().toString().length() == 0){
Toast.makeText(MainActivity.this,"When, bro?",Toast.LENGTH_LONG).show();
}else{
Event=new String(Edt.getText().toString());
final int time = Integer.parseInt(sec.getText().toString());
Intent myInt = new Intent(MainActivity.this,Receiver.class);
myInt.putExtra("key",Event);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,2,myInt,PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+(time*1000),pendingIntent);
new CountDownTimer(time*1000, 1000) {
public void onTick(long millisUntilFinished) {
Toast.makeText(MainActivity.this,"Alarm starts in"+ +millisUntilFinished/1000 + "seconds",Toast.LENGTH_SHORT).show();
}
public void onFinish() {
}
}.start();
}

If you mean that they stack up causing a delay then you should cancel the prior toast before showing a new one.
If you want something more fancy you could try using a PopupWindow instead to show the countdown, there you have more freedom for layout etc.
http://developer.android.com/reference/android/widget/PopupWindow.html

Related

I need to change the colour of a button in an android widget

I have a widget with a button that users must press within a given interval. The button works fine and resets the interval but I want the button to change colour green -> amber -> red depending on time left. I have no problem changing the text on the button using remote views with code like this:
RemoteViews views =new RemoteViews(context.getPackageName(), R.layout.example_widget);
views.setCharSequence(R.id.example_widget_button, "setText", buttonText);
But I can not make any sort of code change the button colour. I've tried several things along the lines of:
views.setCharSequence(R.id.example_widget_button, "setBackgroundTint", "#039be5");
I have also tried using a drawable background and changing that. I'm missing something really obvious -it must be possible- I just can't find an example that works in my context.
Can anyone point me?
You can do this:
views.setInt(R.id.example_widget_button, "setBackgroundColor", android.graphics.Color.BLACK)`;
and you change the color to be what you want at that time.
You can either use Handler or CountDownTimer.
If you want to use Handler, here is the example:
long totalTime = 10000;
long warningTime = 6000;
long alertTime = 30000;
Runnable warningColorChangeRunnable = new Runnable() {
#Override
public void run() {
button.setBackgroundColor(getResources().getColor(R.color.colorWarning));
}
};
Runnable alertColorChangeRunnable = new Runnable() {
#Override
public void run() {
button.setBackgroundColor(getResources().getColor(R.color.colorAlert));
}
};
final Handler handler = new Handler();
handler.postDelayed(warningColorChangeRunnable, totalTime - warningTime);
handler.postDelayed(alertColorChangeRunnable, totalTime - alertTime);
button.setOnClickListener(new OnClickListener() {
#Override public void onClick(View view) {
handler.removeCallbacks(warningColorChangeRunnable);
handler.removeCallbacks(alertColorChangeRunnable);
}
});
If you want to use CountDownTimer, here is the example:
long totalTime = 10000;
long warningTime = 6000;
long alertTime = 30000;
long interval = 1000;
CountDownTimer timer = new CountDownTimer(totalTime, 1000) {
public void onTick(long millisUntilFinished) {
if (millisUntilFinished <= warningTime && millisUntilFinished > warningTime - interval) {
button.setBackgroundColor(getResources().getColor(R.color.colorWarning));
}
if (millisUntilFinished <= alertTime && millisUntilFinished > alertTime - interval) {
button.setBackgroundColor(getResources().getColor(R.color.colorAlert));
}
}
public void onFinish() {
// Maybe show a failure dialog
}
}.start();
button.setOnClickListener(new OnClickListener() {
#Override public void onClick(View view) {
timer.cancel();
}
});

Show alert for 15 minute in android on button click

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

Android Force quit CountDownTimer/Toast

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();

why does Just the last alarm sat have been worked

i have a project that use alarmmanager. many avtivity set alarms and then when alarm have been rise,specific activity in name of AlarmSetter that started show alarm and also set a new (next) alarm and snooz alarm(if user needs). my problem is just the last alarm setted . this mean all activity set alarm byut the last alarm set has worked .for example in alarm setter if user select snooz button then main alarm dont work(just snooz work as well = the last alarm sat).
i set alarmmanager in G class(common) and use and set alarm in activity alarm.java
This is My G Class :
public class G extends Application {
public static AlarmManager alarmManager;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
}
}
Alarm Setter Java IS :
public class ActivityAlarm extends ActivityMain {
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.alarmshower);
//at first reminder will start, should register next alarm time :
long MilisectoAlarmManager = mDbHelper.SetNextTime_andIsactiveYET(DrugRegID);
if (MilisectoAlarmManager != 0 && IsFor10minlater == 0) {
Intent intentMain = new Intent(G.context, ActivityAlarm.class);
intentMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intentMain.putExtra("DrugID", String.valueOf(DrugRegID));
intentMain.putExtra("IsItFor10MinLate", String.valueOf(0));
PendingIntent pendingIntentMain = PendingIntent.getActivity(G.context, 0, intentMain, PendingIntent.FLAG_UPDATE_CURRENT);
String AA = mDbHelper.GetStartDateAlarm(DrugRegID);
Date D = new Date(MilisectoAlarmManager);
System.out.println("current Date(ms): " + MilisectoAlarmManager);
G.alarmManager.set(AlarmManager.RTC_WAKEUP, MilisectoAlarmManager, pendingIntentMain);
}
//Finished Activing Alarm Manager and switch Off Alarmn
else if (MilisectoAlarmManager == 0 && IsFor10minlater == 0) {
mDbHelper.UpdateAlarmSwitch(DrugRegID, false);
}
handler.postDelayed(r, HowLongRemainAlarm_var);
//End CountDown Finished Activity
//Procedure for 10 min later button
btn10minLater_var.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
btn10minLater_var.setBackgroundColor(Color.parseColor("#1174b9"));
Intent intentFor10min = new Intent(G.context, ActivityAlarm.class);
intentFor10min.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intentFor10min.putExtra("DrugID", String.valueOf(DrugRegID));
intentFor10min.putExtra("IsItFor10MinLate", String.valueOf(1));
PendingIntent pendingIntent10min = PendingIntent.getActivity(G.context, 0, intentFor10min, PendingIntent.FLAG_UPDATE_CURRENT);
G.alarmManager.set(AlarmManager.RTC_WAKEUP, new Date().getTime() + 20000, pendingIntent10min);
ActivityAlarm.this.finish();
}
});
i found asnwer ! in PendingIntent.getActivity secound parameter must have diffrent in each alarm set !

CountDownTimer inside AlertDialog

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?

Categories

Resources