I need to make every second the health to go down by "1" after going the health under 20 or is equal to 20 to show the "alertDialog" i don't have any errors in the code. The problem is crushing after the "Health" passed the border/limit the application is crushing, i don't know why is that happening, is there someone to help me with it ?
I also make sure that there is one time show of the "alertDialog" with boolean but doesn't help...
Thanks in advice :)
Code:
new Timer().schedule(new TimerTask() {
#Override
public void run() {
Health -= 1;
if (Health <= 20) {
if (!canSeeWarnDialog) {
final AlertDialog alertDialog2 = new AlertDialog.Builder(
MainActivity.this).create();
alertDialog2.setTitle("Im hungry");
alertDialog2.setMessage("The dog health is going low "
+ "\ngive him some food");
alertDialog2.setButton("Got it",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
alertDialog2.cancel();
}
});
alertDialog2.show();
canSeeWarnDialog = true;
return;
}
}
}
}, 1000, 1000);//TimeUnit.SECONDS.toMillis(1));
Why don't you use a CountDownTimer ? It seems more suitable to your task and it handles all the callbacks on the UI thread for you.
You need a CountDownTimer.
When taking "length" as amount of Health in miliseconds (*1000 -> 30 max health => 30000 length).Current health should be millisUntilFinished/1000.
boolean notified = false;
new CountDownTimer(length, 1000) {
#Override
public void onTick(long millisUntilFinished)
{
if(millisUntilFinished <= 20 && !notified)
{
final AlertDialog alertDialog2 = new AlertDialog.Builder(
MainActivity.this).create();
alertDialog2.setTitle("Im hungry");
alertDialog2.setMessage("The dog health is going low "
+ "\ngive him some food");
alertDialog2.setButton("Got it",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
alertDialog2.cancel();
}
});
alertDialog2.show();
notified = true;
}
}
#Override
public void onFinish()
{
//Health is 0.
notified = false; // For next time.
//if you want to restart -> retrieve full health:
this.start();
}
};
Related
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 am new in android, I want see my message in a Toast but it shows to for a little time.
I want to show the message for example until one hour or more.
No you can't. Use a Custom Dialog and dismiss it when you want. But i wonder why do you want to display some kind of pop up for such a long time.
I would suggest re-considering your design.
You may also want to check Crouton
https://github.com/keyboardsurfer/Crouton
Try to use Dialog box instead of toast
SingleButtton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Creating alert Dialog with one Button
AlertDialog alertDialog = new AlertDialog.Builder(AlertDialogActivity.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Welcome to Android Application");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which)
{
// Write your code here to execute after dialog closed
}
});
// Showing Alert Message
alertDialog.show();
}
});
The values of LENGTH_SHORT and LENGTH_LONG are 0 and 1.they are treated as flags therefore I think it is not possible to set time other than this.
You can try this :
Edit:
int time = 1000*60 // 1 hour
for (int i=0; i < time; i++)
{
Toast.makeText(this, "Your msg", Toast.LENGTH_LONG).show();
}
Well, like said here, there is no proper way to do this.
But, there is a sort of hack to it - just run your Toast in a for-loop, and the amount of iterations will control the length. For example - running the loop twice (like below) will double the time. Running it 3 times will triple the length. Again, it is just a work-around that works :-)
for (int i=0; i < 2; i++)
{
Toast.makeText(this, "test", Toast.LENGTH_LONG).show();
}
You must take into account that it does have flaws - it the user quits the app before the end of loop it will continue to show, and, on some devices the Toast might flicker between each iteration. So, up to you!
The purpose of toast is showing a simple message in a time. You can't show it for long time. you can customized your own UI for Toast messages using dialog.
public static void showCustomToast(final Activity mActivity,final String helpText,final int sec) {
if(mActivity != null){
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
int mSec = 3000;
if(sec != 0){
mSec = sec;
}
LayoutInflater inflater = mActivity.getLayoutInflater();
View messageDialog = inflater.inflate(R.layout.overlay_message, null);
layer = new CustomLayout(mActivity);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
messageDialog.setLayoutParams(params);
TextView message = (TextView) messageDialog.findViewById(R.id.messageView);
Button okBtn = (Button) messageDialog.findViewById(R.id.messageOkbtn);
if(okBtn != null){
okBtn.setVisibility(View.GONE);
}
message.setText(helpText);
final Dialog dialog = new Dialog(mActivity,R.style.ThemeDialogCustom);
dialog.setContentView(messageDialog);
dialog.show();
final Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
if(dialog.isShowing()){
dialog.dismiss();
}
t.cancel();
}
},mSec);
}
});
}
}
For referance
Sets toast to a specific period in milli-seconds:
public void toast(int millisec, String msg) {
Handler handler = null;
final Toast[] toasts = new Toast[1];
for(int i = 0; i < millisec; i+=2000) {
toasts[0] = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toasts[0].show();
if(handler == null) {
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
toasts[0].cancel();
}
}, millisec);
}
}
}
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.