Can I display a toast message based on user's current time?
I need to make an app, Where when I open the screen from 1:00 am to 11:00 am it will display the toast message "Good morning" whereas if I open the screen at 6:00 pm to 11:00 pm it will display the toast "good night"
public class ToastDisplay extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)){
Toast.makeText(context,"Good Morning",Toast.LENGTH_SHORT).show();
}
}
}
What you can do i use Calendar class to get the current time. Check the time and display the toast accordingly.
Calendar currentTime = Calender.getInstance();
int hour = currentTime.get(Calendar.HOUR_OF_DAY);
if(Use your condition here) {
Display toast
} else if(Use your other condition) {
Display toast
}
Just a note, your hour would be in 24 hour format so you need to check keeping that in mind.
int toastDurationInMilliSeconds = 10000;
Toast.LENGTH_SHORT is int, so you have to declare new int
Related
I have an app how to make some notification when reaching specific time ...
I would to show some pop-up or custom layout when my app is onStop or onDestroy.
I would like this photo.
(click to enlarge)
If you just want to give a message then Toast is enough and easy.
#override
public void onStop() {
Toast.MakeText(context, "Your message here", Toast.LENGTH_LONG).show();
}
#override
public void onDestroy() {
Toast.MakeText(context, "Your message here", Toast.LENGTH_LONG).show();
}
EDIT: I won't recommend you to write long messages in Toast and show it for longer durations, instead consider a Statusbar Notification. Status Bar Notifications can be programmatically canceled when they are no longer relevant.
BUT If you still want to increase the duration of Toast message then here is a workaround.
private Toast mToastToShow;
public void showToast(View view) {
// Set the toast and duration
int toastDurationInMilliSeconds = 10000;
mToastToShow = Toast.makeText(this, "Hello world, I am a toast.", Toast.LENGTH_LONG);
// Set the countdown to display the toast
CountDownTimer toastCountDown;
toastCountDown = new CountDownTimer(toastDurationInMilliSeconds, 1000 /*Tick duration*/) {
public void onTick(long millisUntilFinished) {
mToastToShow.show();
}
public void onFinish() {
mToastToShow.cancel();
}
};
// Show the toast and starts the countdown
mToastToShow.show();
toastCountDown.start();
}
Here is how it works: the countdown has a notification time shorter than the duration for which the toast is displayed according to the flag, so the toast can be shown again if the countdown is not finished. If the toast is shown again while it is still on screen, it will stay there for the whole duration without blinking. When the countdown is finished, the toast is canceled to hide it even if its display duration is not over.
Simplest way would be to use a Toast (easy and immediate). More complex way is that you've to grant 2 special permissions "draw over other apps" and "app with usage access" (which are special permissions, so you need to create your own page to prompt the user to grant it), after which you can add your custom view directly to the windows manager of the system. Last but not least, you should seriously think if there's any benefit for the user to be notified on main screen about something after your main page has been stopped or destroyed, because that goes against the system design quite a lot.
I am trying to build an android app and have come across a situation where I want a user to navigate between Dates by clicking Previous (Month) and Next (Month) buttons. I however do not want the user to go to a month after the current month. I would like the App to prompt a dialog letting the user know that they cant select a month after the current. Below is my code snippet - I am getting an error on two portions
01. if(formattedDate.before(currentMonth) || formattedDate.equals(currentMonth)){
On the above I am getting an error saying
The method before(Calendar) is undefined for the type String
02. new AlertDialog.Builder(HomeFragment.this)
and on the above I am getting an error saying
The constructor AlertDialog.Builder(HomeFragment) is undefined
Below is my full code for the on-click listener
NextPicker.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(formattedDate.before(currentMonth) || formattedDate.equals(currentMonth)){
c.add(Calendar.MONTH, 1);
formattedDate = df.format(c.getTime());
Log.v("NEXT DATE : ", formattedDate);
DatePicker.setText(formattedDate);
}
else{
new AlertDialog.Builder(HomeFragment.this)
.setTitle("Wrong Date Selection!")
.setMessage("The Month Selected must be before or equal to current month")
.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
}
});
Your first problem is that formattedDate is a String. It needs to be a java.util.Date.
Your second problem comes from the fact that the AlertDialog.Builder constructor requires a Context sub-class. Fragment is not a Context sub-class, but Activity is. Try something like
new AlertDialog.Builder(HomeFragment.this.getActivity());
I want the functionality of Google Now app, like when it's day time, the header is a sunny image, when it becomes noon or sundown, the image changes to a sundown image, when it's night the image changes to a night image, and same for the morning one.
I'm trying to implement my background which does this very same thing, how must I go about implementing this? I've searched up on this but the answers are for html and website development.
And most of the others are based on time interval and I think that's what I should use but I would like something like this. Written in non-tech language
01:00/1am - Morning - Image changes to Morning.png on the imageview (R.id.view).
09:00/9am - Normal - Image changes to Daytime.png on the imageview (R.id.view).
12:00/12pm - Noon - Image changes to Noon.png on the imageview (R.id.view).
19:00/7pm - Night - Image changes to Noon.png on the imageview (R.id.view).
How I can achieve something similar to this?
Well the best candidate for this job is an AlarmManager!
Lets assume you only need to change the background when your Activity is running.
You can set up your alarm when you Create your Activity:
private PendingIntent pi=null;
private AlarmManager mgr=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mgr=(AlarmManager)getSystemService(ALARM_SERVICE);
pi=createPendingResult(ALARM_ID, new Intent(), 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + PERIOD, PERIOD, pi);
}
PERIOD (ms) is how often we want to get control (onActivityResult). The createPendingResult(ALARM_ID, new Intent(), 0); line creates an Intent that can be caught in your Activities onActivityResult method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ALARM_ID) {
// This is where you check the time and change your background!
}
}
You also need to cancel your alarm in onDestroy:
#Override
public void onDestroy() {
mgr.cancel(pi);
super.onDestroy();
}
To check if a Date is in a specific interval you can use:
boolean isWithinRange(Date testDate) {
return testDate.getTime() >= startDate.getTime() &&
testDate.getTime() <= endDate.getTime();
}
I advice you write a class which has a listen method. This listen method which checks time and raises a custom event (you can use interface here) on Activity level must be called periodically. You can use Timer and TimerTask or CountdownTimer to call.
In my app, I've got a procedure that can last between 2 and 15 seconds more or less. What I want is to set a kind of toast that when the procedure starts shows:
Loading values. Wait...
Just now, I've setted the toast duration to SHORT, because if the procedure lasts about 5 or less seconds, a LONG will be just that, very long. But having setted the duration to SHORT, when it lasts more than 10 seconds the toast dissapears and there is no message showing that the app is still processing so the user can start touching things.
What I want is to set something like a toast but that I can programmatically cancel when the procedure is finished. Any ideas?
I would recommend that you simply set the Toast duration to the maximum possible time and then use the Toast object returned from Toast.makeText(...) to cancel it when your process is finished.
Toast t = Toast.makeText(....., YERY_LONG_TOAST_TIME);
t.show();
public void onYourTaskFinished() {
t.cancel();
}
Something like that.
I personally would recommend using a ProgressDialog btw: http://developer.android.com/reference/android/app/ProgressDialog.html
Here's an example:
final Toast toast = Toast.makeText(ctx, "This message will disappear in 1 second", Toast.LENGTH_SHORT);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
toast.cancel();
}
}, 1000); //specify delay here that is shorter than Toast.LENGTH_SHORT
final Toast toast = Toast.makeText(ctx, "hello android", Toast.LENGTH_SHORT);
Handler h= new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
toast.show();
}
}, 1000);
h.postDelayed(new Runnable() {
#Override
public void run() {
toast.cancel();
}
}, 3000);
You can have a handler of the Toast when you create it, pass it to you job and call the show() method when the job starts and call the cancel() method when the job finish.
However, from your description, toast message might not be your best choice. Toast is more like a hint which has little impact if the user misses it. With little background infomation about your app, I think you might need a ProgressDialog if you do not want the user to touch anything while you are loading data, or a ProgressBar if you just want the user to know your job's progress.
Do not use Toast for this purpose. You should use progress dialog or you can add progress indicator to notification bar. So user will be able to see progress even not being inside your app.
I just recently started to mess with the alarm manager, and I figured out most of it, but right now its starting to be a bit annoying. So, right now I have it set up with a date and time picker, you type in the date and time and it will pop up a toast message when that times comes, but it seems like it will only take one alarm and any other ones I set get destroyed. Is this something the alarm manager does by itself, or is there something I am missing. Here is my code for my main class, the other is just a broadcast receiver with a toast message in it, so I won't post it.
public class TextScheduler extends ListActivity {
protected Toast mToast;
TimePicker time;
DatePicker date;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(setTime);
time = (TimePicker) this.findViewById(R.id.timePicker1);
date = (DatePicker) this.findViewById(R.id.datePicker1);
}
private OnClickListener setTime = new OnClickListener() {
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
cal.set(date.getYear(), date.getMonth(), date.getDayOfMonth(), time.getCurrentHour(), time.getCurrentMinute());
Intent intent = new Intent(TextScheduler.this, AReceiver.class);
intent.putExtra("caldata", "hooray!!");
PendingIntent sender = PendingIntent.getBroadcast(TextScheduler.this, 1234567, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
}
};
}
Let me know if you need any more info, thanks in advance!
WWaldo
AlarmManager compares PendingIntents to see if it already exits. Just change the ID (in your case 1234567), and it will allow you to create additional alarms: one per ID.