Notification like Toast but with longer duration

298 views Asked by At

I have to create a notification like an android toast notification but I need to throw it from a service and I need to close it when I want. standard toast notification would be perfect, but it's too much short.

I tried with a DialogFragment, but it takes the focus (not like toast) and I could not throw it from a service, but only from a FragmentActivity.

Thanks!!

2

There are 2 answers

0
Naveen Tamrakar On BEST ANSWER
            Toast toast = new Toast(this);
            TextView textView=new TextView(this);
            textView.setTextColor(Color.BLUE);
            textView.setBackgroundColor(Color.TRANSPARENT);
            textView.setTextSize(20);
            textView.setText("My Toast For Long Time");
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);

            toast.setView(textView);

          timer =new CountDownTimer(20000, 1000)
            {
                public void onTick(long millisUntilFinished)
                {
                    toast.show();
                }
                public void onFinish()
                {
                    toast.cancel();
                }

            }.start();
0
Simas On

From a quick search in SO, you can find the Toast durations:

private static final int LONG_DELAY = 3500; // 3.5 seconds
private static final int SHORT_DELAY = 2000; // 2 seconds

Now you can display multiple Toasts one after the other to look like it has a longer duration:

final String msg = "Some text";
Runnable delayedToast = new Runnable() {
    @Override
    public void run() {
        Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show();
    }
};

Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show(); 
mHandler.postDelayed(delayedToast, 3000);
mHandler.postDelayed(delayedToast, 6000);

Where ctx is your activity/application context and mHandler is a handler on the UI Thread. The duration should be around 3000+3000+3500.