How to display Android toast for longer time - android

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

Related

Android Background issues when user is in active state

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.

Issue about the return value of activityStarting

Today I'm developing an App which can intercept the launch between activities, My key code is:
ActivityManagerNative.getDefault().setActivityController(new InterceptActivityController(), false);
private class InterceptActivityController extends IWeChatActivityController.Stub {
void InterceptActivityController() {}
#Override
public boolean activityStarting(Intent intent, String pkg) {
showDialog();
return false;
}
}
private void showBottomDialog() {
Log.d(TAG, "showBottomDialog");
Dialog bottomDialog = new Dialog(mContext);
View contentView = LayoutInflater.from(this).inflate(android.R.layout.simple_list_item_2, null);
bottomDialog.setContentView(contentView);
ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
layoutParams.width = getResources().getDisplayMetrics().widthPixels;
contentView.setLayoutParams(layoutParams);
bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
bottomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
bottomDialog.show();
}
I defined a Button and planned to start an Activity after clicking it. But now I intercept this action and just show a dialog in the function of activityStarting and then return false, after dismissing this dialog, I click the button again, but nothing works, dialog doesn't show any more, Who knows the reason ? Maybe I think this is a google source bug, but I'm not sure.
You know the Dialogs need to be Shown in a Timely manner. I mean You need the Dialog to be Shown for How Long? When you Start showing a Dialog and Dismiss it, It's Not Destroyed, It's just Dismissed.
Look at the Code below. I wrote this in my own app, It's Safe. Try it and see if you're satisfied with it:
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bottomDialog.show();
new Thread(new Runnable() {
#Override
public void run() {
try {
for (int i = 0; i <= 1200; i++) {
Thread.sleep(100); //The time it takes to update i
if (i = 1200) {
bottomDialog.dismiss();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
You can use AsyncTask as well. Also, I put the whole thing in a Click Listener just to show how it can be used.
The idea is define a showing Time for the Dialog

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

Timer ends = application crash

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

Change onClickListener dynamically in handleMessage depending on Message

I have an Activity with Android.os.Handler, which is used for communication with an openGL thread.
I want to get messages from the opengl thread and draw some GUI in the activity depending on the message data, so I do:
Handler handle = new Handler(new Handler.Callback(){
public boolean handleMessage(Message msg){
// update GUI like
TextView v1 = (TextView) GamescreenActivity .this.findViewById(R.id.mytextview)
// then what I actually would like to do but it does not work:
Button b = (Button) GamescreenActivity.this.findViewById(R.id.mybutton);
b.setOnClickListener(null);
if (msg.what == MY_OWN_CONSTANT) {
b.setOnClickListener(getOnClickDoSomething(msg));
}
}
View.OnClickListener getOnClickDoSomething(final Message msg) {
return new View.OnClickListener() {
public void onClick(View v) {
makeDialog(msg);
}
};
}
private void makeDialog(Message msg) {
AlertDialog.Builder builder = new AlertDialog.Builder(GamescreenActivity.this);
builder.setMessage("yo")
.setTitle(""+ msg.what);
AlertDialog dialog = builder.create();
dialog.show();
}
I hope it is clear what i'm trying to achieve. What I get by now is msg being null in the makeDialog methode almost all the time.
What I get by now is msg being null in the makeDialog methode almost all the time.
I believe the Message has already been recycled when this happens. Let's create a local copy of msg and modify your code a little to make it more efficient. First create a new field variable:
Message message;
Next change your if-else block:
if (msg.what == MY_OWN_CONSTANT) {
message = Message.obtain(msg);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(GamescreenActivity.this);
builder.setMessage("yo")
.setTitle(""+ message.what)
.show();
message.recycle(); // Recycle our message when we're done
}
});
}
else {
b.setOnClickListener(null);
}

Categories

Resources