I created a handler with runnable etc to delay some notifications, very simple.
The first notification has a delay of 1 hour en the second 2 hours etc. But, when the users turns off his the device when the first has fired already, the second one won't be fired anymore... I really need the second and following notifications to be fired, although the user has turned off his device between those times..
How to do this?
My code for the notifications, do I have to add something?:
final Switch mySwitch = (Switch) findViewById(R.id.theswitch);
mySwitch.setChecked(myPrefs.getBoolean("switch", false));
//attach a listener to check for changes in state
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
final boolean isChecked) {
editor.putBoolean("switch", isChecked);
editor.commit();
if (isChecked) {
//switch has been switched ON
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+1:00"));
Date currentLocalTime = cal.getTime();
DateFormat date = new SimpleDateFormat("HH:mm");
// you can get seconds by adding "...:ss" to it
date.setTimeZone(TimeZone.getTimeZone("GMT+1:00"));
String localTime = date.format(currentLocalTime);
Log.w(localTime, "1");
if (localTime.equals("08:50") || localTime.equals("08:51") || localTime.equals("08:52") || localTime.equals("08:53") || localTime.equals("08:54") || localTime.equals("08:55") || localTime.equals("08:56")
|| localTime.equals("08:57") || localTime.equals("08:58") || localTime.equals("08:59") || localTime.equals("09:00") || localTime.equals("09:01") || localTime.equals("09:02") || localTime.equals("09:03")
|| localTime.equals("09:04") || localTime.equals("09:05") || localTime.equals("09:06") || localTime.equals("09:07") || localTime.equals("09:08") || localTime.equals("09:09") || localTime.equals("09:10")
|| localTime.equals("09:11") || localTime.equals("09:12") || localTime.equals("09:13") || localTime.equals("09:14") || localTime.equals("09:15") || localTime.equals("09:16") || localTime.equals("09:17")
|| localTime.equals("09:18") || localTime.equals("09:19") || localTime.equals("09:20") || localTime.equals("09:21") || localTime.equals("09:22") || localTime.equals("09:23") || localTime.equals("09:24")
|| localTime.equals("09:25") || localTime.equals("09:26") || localTime.equals("09:27") || localTime.equals("09:28") || localTime.equals("09:29") || localTime.equals("09:30") || localTime.equals("09:31")
|| localTime.equals("09:32") || localTime.equals("09:33") || localTime.equals("09:34") || localTime.equals("09:35") || localTime.equals("09:36") || localTime.equals("09:37") || localTime.equals("09:38")
|| localTime.equals("09:39") || localTime.equals("09:40") || localTime.equals("09:41") || localTime.equals("09:42") || localTime.equals("09:43") || localTime.equals("09:44") || localTime.equals("09:45")
|| localTime.equals("09:46") || localTime.equals("09:47") || localTime.equals("09:48") || localTime.equals("09:49") || localTime.equals("09:50") || localTime.equals("09:51") || localTime.equals("09:52")
|| localTime.equals("09:53") || localTime.equals("09:54") || localTime.equals("09:55") || localTime.equals("09:56") || localTime.equals("09:57") || localTime.equals("09:58") || localTime.equals("09:59")
|| localTime.equals("10:00") || localTime.equals("10:01") || localTime.equals("10:02") || localTime.equals("10:03") || localTime.equals("10:04") || localTime.equals("10:05") || localTime.equals("10:06")
|| localTime.equals("10:07") || localTime.equals("10:08") || localTime.equals("10:09") || localTime.equals("10:10") || localTime.equals("15:07")) {
Log.w("It is between", "those times");
boolean beenfired2 = myPrefs.getBoolean("beenfired", false);
if (beenfired2 != true) {
Log.w("yes", "it is not equal to true");
// day 1
mHandler.postDelayed(mClickRunnable, 3600000);
mHandler.postDelayed(mClickRunnable, 7200000);
mHandler.postDelayed(mClickRunnable, 7200000);
mHandler.postDelayed(mClickRunnable, 14400000);
mHandler.postDelayed(mClickRunnable, 18000000);
mHandler.postDelayed(mClickRunnable, 21600000);
mHandler.postDelayed(mClickRunnable, 25200000);
mHandler.postDelayed(mClickRunnable, 28800000);
mHandler.postDelayed(mClickRunnable, 32400000);
mHandler.postDelayed(mClickRunnable, 36000000);
mHandler.postDelayed(mClickRunnable, 39600000);
// day 2
mHandler.postDelayed(mClickRunnable, 90000000);
mHandler.postDelayed(mClickRunnable, 97200000);
mHandler.postDelayed(mClickRunnable, 104400000);
mHandler.postDelayed(mClickRunnable, 111600000);
mHandler.postDelayed(mClickRunnable, 118800000);
mHandler.postDelayed(mClickRunnable, 126000000);
// day 3
mHandler.postDelayed(mClickRunnable, 180000000);
mHandler.postDelayed(mClickRunnable, 190800000);
mHandler.postDelayed(mClickRunnable, 201600000);
mHandler.postDelayed(mClickRunnable, 212400000);
mHandler.postDelayed(mClickRunnable, 212400000);
// day 4
mHandler.postDelayed(mClickRunnable, 270000000);
mHandler.postDelayed(mClickRunnable, 284400000);
mHandler.postDelayed(mClickRunnable, 298800000);
// day 5
mHandler.postDelayed(mClickRunnable, 367200000);
mHandler.postDelayed(mClickRunnable, 388800000);
// day 6
mHandler.postDelayed(mClickRunnable, 460800000);
mHandler.postDelayed(mClickRunnable, 475200000);
// day 7
mHandler.postDelayed(mClickRunnable, 554400000);
// day 8
mHandler.postDelayed(mClickRunnable, 648000000);
beenfired = true;
editor.putBoolean("beenfired", beenfired);
editor.commit();
} else {
Log.w("else", "else");
}
} else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Inlopen.this);
// set title
alertDialogBuilder.setTitle("Alarm kan niet worden ingeschakeld");
// set dialog message
alertDialogBuilder
.setMessage("U kunt het alarm alleen inschakelen tussen 9:00 en 10:00 's ochtends.")
.setCancelable(false)
.setNegativeButton("Oke", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
mySwitch.setChecked(false);
editor.putBoolean("switch", false);
editor.commit();
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
} else {
//switch has been switched OFF
beenfired = false;
mHandler.removeCallbacks(mClickRunnable);
mHandler.removeMessages(0);
editor.putBoolean("beenfired", beenfired);
editor.commit();
editor.putBoolean("switch", false);
editor.commit();
}
}
});
}
private Handler mHandler = new Handler();
private Runnable mClickRunnable = new Runnable() {
#Override
public void run() {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(Inlopen.this)
.setSmallIcon(R.drawable.iconsmall)
.setContentTitle("DM Voet App")
.setContentText("Uw moet uw voeten controleren!");
mBuilder.setAutoCancel(true);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, mBuilder.build());
}
};
Use Alarm Manager
From the Document:
"The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running."
Related
I made a code to show the amount of times a vowel is used. A, E, I, O, U. The code is counting but it is not conunting correctly.
#Override
public void onClick(View v) {
int letter1 = 0;
int letter2 = 0;
String enter1 = str1.getText().toString();
String enter2 = str2.getText().toString();
for (int i = 0; i < str1.length(); i++) {
if (enter1.charAt(i) == 'a' || enter1.charAt(i) == 'e' || enter1.charAt(i) == 'i' || enter1.charAt(i) == 'o' ||
enter1.charAt(i) == 'u')
{
letter1++;
}
for(int j = 0; j < str2.length(); j ++){
if(enter2.charAt(j) == 'a' || enter2.charAt(j) == 'e' || enter2.charAt(j) == 'i' || enter2.charAt(j) == 'o' ||
enter2.charAt(j) == 'u')
{
letter2++;
}
}
display3.setText("The amount of vowels are :"+ letter1 + " & " + letter2);
}
}
});
My output for Hello World is 2 and 5. 2 for Hello is correct but 5 for World is not. What am I missing?
If we reformat the code slightly, the problem is more apparent:
for (int i = 0; i < str1.length(); i++) {
if (enter1.charAt(i) == 'a' || enter1.charAt(i) == 'e' || enter1.charAt(i) == 'i' || enter1.charAt(i) == 'o' ||
enter1.charAt(i) == 'u') {
letter1++;
}
for (int j = 0; j < str2.length(); j++) {
if (enter2.charAt(j) == 'a' || enter2.charAt(j) == 'e' || enter2.charAt(j) == 'i' || enter2.charAt(j) == 'o' ||
enter2.charAt(j) == 'u') {
letter2++;
}
}
display3.setText("The amount of vowels are :" + letter1 + " & " + letter2);
}
As you can see, the second for loop is inside the first one. That means the second number will be N times larger than it should be, where N is the length of the first word. This matches what's happening: there is only 1 vowel in "world" but there are 5 letters in "hello".
The display3.setText(...) part will also be executed N times, but since it overwrites the previous value you won't be able to notice that, and you'll just see the final value.
To fix, just close the first for loop earlier:
for (int i = 0; i < str1.length(); i++) {
if (enter1.charAt(i) == 'a' || enter1.charAt(i) == 'e' || enter1.charAt(i) == 'i' || enter1.charAt(i) == 'o' ||
enter1.charAt(i) == 'u') {
letter1++;
}
}
for (int j = 0; j < str2.length(); j++) {
if (enter2.charAt(j) == 'a' || enter2.charAt(j) == 'e' || enter2.charAt(j) == 'i' || enter2.charAt(j) == 'o' ||
enter2.charAt(j) == 'u') {
letter2++;
}
}
display3.setText("The amount of vowels are :" + letter1 + " & " + letter2);
Something problem with the brackets
#Override
public void onClick(View v) {
for(Loop){
if(condition){
}
}//first loop
for(Loop){
if(condition){
}
}//second loop
//display here
});//end for onClick
For android Room, i need a type converter to save Location objects. Converting Locations to String is rather simple, e.g.:
public static String locationStringFromLocation(final Location location) {
if (location==null) return "Location was null";
return Location.convert(location.getLatitude(), Location.FORMAT_DEGREES) + " " + Location.convert(location.getLongitude(), Location.FORMAT_DEGREES);
}
But the other way around seems less obvious. I could append all the properties and separate them with a delimiter, but that seems not quite elegant. Any ideas would be appreciated.
My current workaround is to just save latitude and longitude, but I'd prefer to have the object.
public static Location locationFromString(String location){
if (location != null && (location.contains(","))) {
Location result = new Location("Generated_location");
String[] locationStrings = location.split(",");
if (locationStrings.length == 2) {
result.setLatitude(Double.parseDouble(locationStrings[0]));
result.setLongitude((Double.parseDouble(locationStrings[1])));
return result;
} else { return null; }
} else return null;
}
static Location parseLocationString(String locString){
if(locString != null && locString.contains("Location")) {
Location location = new Location("");
String rep = locString.replace("Location", "")
.replace("[", "")
.replace("]", "");
String[] k = rep.split(" ");
for (int part = 0; part < k.length; part++) {
String string = k[part];
if(part == 0)location.setProvider(string);
else if (part == 1){
String[] latlng = string.split(",");
if(latlng.length > 1){
location.setLatitude(Double.parseDouble(latlng[0]));
location.setLongitude(Double.parseDouble(latlng[1]));
}
}
else if (part > 1){
String[] locationDetails = string.split("=");
if (locationDetails.length > 1){
String locationKey = locationDetails[0];
String locationValue = locationDetails[1];
if (locationKey.contains("hAcc")) {
if (!locationValue.contains("?"))
location.setAccuracy((float)Float.parseFloat(locationValue));
}else if (locationKey.contains("et")){
if( !locationValue.contains("?") )
if(Build.VERSION.SDK_INT >= 17) {
if(locationValue.contains("+")) {
long days = 0, hours, min, sec, mill;
//separate string value
String nmbr = locationValue.split("\\+")[1];
String[] hr;
//isolate each value
String[] d = nmbr.split("d");
if(d.length > 1){
days = Long.parseLong(d[0]);
}
if(d.length > 1)
hr = d[1].split("h");
else
hr = nmbr.split("h");
if(hr.length > 1) {
hours = Long.parseLong(hr[0]);
}else hours = 0;
if(days > 0)
hours += 24*days;
String[] m;
if(hr.length > 1)
m = hr[1].split("m");
else
m = hr[0].split("m");
if(m.length > 1) {
if(m[0].length() > 0)
try {
min = Long.parseLong(m[0]);
}catch(NumberFormatException e){
min = 0;
}
else min = 0;
} else min= 0;
String[] s = m[0].split("s");
if(s.length > 1) {
sec = Long.parseLong(s[0]);
}else sec = 0;
if(min != 0 || hours != 0) {
String[] ms = s[0].split("ms");
if (ms.length >= 0 && !ms[0].contains("s")) {
mill = Long.parseLong(ms[0]);
} else mill = 0;
}else{
String ms = s[1];
if (ms.length() >= 0 && !ms.contains("s")) {
mill = Long.parseLong(ms);
} else mill = 0;
}
long millInNano = 1000000;
long nano = mill * millInNano;
nano += (sec * 1000) * millInNano;
nano += ((min * 60) * 1000) * millInNano;
nano += (((hours * 60) * 60) * 1000) * millInNano;
location.setElapsedRealtimeNanos(nano);
}
}
}else if (locationKey.contains("vel")) {
if (!locationValue.contains("?"))
location.setSpeed(Float.parseFloat(locationValue));
}else if (locationKey.contains("vAcc")) {
if (!locationValue.contains("?"))
if(Build.VERSION.SDK_INT >= 26)
location.setVerticalAccuracyMeters(Float.parseFloat(locationValue));
}else if (locationKey.contains("sAcc")) {
if (!locationValue.contains("?"))
if(Build.VERSION.SDK_INT >= 26)
location.setSpeedAccuracyMetersPerSecond(Float.parseFloat(locationValue));
}else if (locationKey.contains("bAcc")) {
if (!locationValue.contains("?"))
if(Build.VERSION.SDK_INT >= 26)
location.setBearingAccuracyDegrees(Float.parseFloat(locationValue));
}
}
}
}
return location;
}else{
return null;
}
}
I have a activity which contains 3 different CheckBox. Now I want to validate that at least 2 CheckBox must be selected but I am not able to achieve this. Please help.
Code:
Boolean checkPC = chkProtectMoney.isChecked();
Boolean checkGM = chkGrow_my_money.isChecked();
Boolean checkMN = chkMedicalNeeds.isChecked();
if(!(checkPC && checkGM == true) || !(checkGM && checkMN == true) || !(checkPC && checkMN == true) || !(checkPC && checkGM && checkPC == true)){
Toast.makeText(getActivity(),R.string.two_expertise_caution,Toast.LENGTH_SHORT).show();
}
private boolean checkIfAnyTwoAreChecked() {
int sum = 0;
if(checkbox1.isChecked()){ sum++; }
if(checkbox2.isChecked()){ sum++; }
if(checkbox3.isChecked()){ sum++; }
return sum >= 2;
}
You can Use a int count .
private int getCheckedCount() {
int count = 0;
if (checkBox1.isChecked())
count++;
if (checkBox2.isChecked())
count++;
if (checkBox3.isChecked())
count++;
return count;
}
if(getCheckedCount()>=2){
// Do your stuff
}
OR
if(checkBox1.isChecked() && checkBox2.isChecked()
|| checkBox1.isChecked() && checkBox3.isChecked()
|| checkBox2.isChecked() && checkBox3.isChecked()){
// Do stuff
}
Add checkedChangeListener for all checkboxes and update count based on check as in
int checkedCount = 0;
chkProtectMoney.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
checkedCount++;
}else{
checkedCount--;
}
if(checkedCount >= 2){
// voila
}else{
//alert to check atleast two
}
}
});
//add for other two same logic then
Change your conditional statement to this
if((checkPC && checkGM) || (checkGM && checkMN) || (checkPC && checkMN)) {
// YOUR CODE
}
How can I use if statement of a spinner when the selected value = 0?
if( wilayat.setSelection(0) || city.setSelection(0) ||
station.setSelection(0) || distnation.setSelection(0)) {
message = "Select the 4 fields, please..";
Toast.makeText(BusArrivalTime.this, message, Toast.LENGTH_SHORT).show();
}
Try this.
if (wilayat.getSelectedItemPosition() == 0 || city.getSelectedItemPosition() == 0 || station.getSelectedItemPosition() == 0 || distnation.getSelectedItemPosition() == 0) {
message = "Select the 4 fields, please..";
Toast.makeText(BusArrivalTime.this, message, Toast.LENGTH_SHORT).show();
}
Just use getSelectedItemPosition() method.
You make sure that wilayat、city and so on were Spinner.
Add judgement
if (wilayat != null || city != null || station != null || distnation != null) {
// do something
}
I made a simpel app that notifies users when they have to check something.
I managed to get the notifications sent with the right delay, but I also want the user to be able to turn off the notification 'bunch' (via a Switch) somewhere between the delays..
I wanted to do this with Handler.removeCallBacks, but it didn't do the job.
final Switch mySwitch = (Switch) findViewById(R.id.theswitch);
mySwitch.setChecked(myPrefs.getBoolean("switch", false));
//attach a listener to check for changes in state
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
final boolean isChecked) {
editor.putBoolean("switch", isChecked);
editor.commit();
if (isChecked) {
//switch has been switched ON
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+1:00"));
Date currentLocalTime = cal.getTime();
DateFormat date = new SimpleDateFormat("HH:mm");
// you can get seconds by adding "...:ss" to it
date.setTimeZone(TimeZone.getTimeZone("GMT+1:00"));
String localTime = date.format(currentLocalTime);
Log.w(localTime, "1");
if (localTime.equals("08:50") || localTime.equals("08:51") || localTime.equals("08:52") || localTime.equals("08:53") || localTime.equals("08:54") || localTime.equals("08:55") || localTime.equals("08:56")
|| localTime.equals("08:57") || localTime.equals("08:58") || localTime.equals("08:59") || localTime.equals("09:00") || localTime.equals("09:01") || localTime.equals("09:02") || localTime.equals("09:03")
|| localTime.equals("09:04") || localTime.equals("09:05") || localTime.equals("09:06") || localTime.equals("09:07") || localTime.equals("09:08") || localTime.equals("09:09") || localTime.equals("09:10")
|| localTime.equals("09:11") || localTime.equals("09:12") || localTime.equals("09:13") || localTime.equals("09:14") || localTime.equals("09:15") || localTime.equals("09:16") || localTime.equals("09:17")
|| localTime.equals("09:18") || localTime.equals("09:19") || localTime.equals("09:20") || localTime.equals("09:21") || localTime.equals("09:22") || localTime.equals("09:23") || localTime.equals("09:24")
|| localTime.equals("09:25") || localTime.equals("09:26") || localTime.equals("09:27") || localTime.equals("09:28") || localTime.equals("09:29") || localTime.equals("09:30") || localTime.equals("09:31")
|| localTime.equals("09:32") || localTime.equals("09:33") || localTime.equals("09:34") || localTime.equals("09:35") || localTime.equals("09:36") || localTime.equals("09:37") || localTime.equals("09:38")
|| localTime.equals("09:39") || localTime.equals("09:40") || localTime.equals("09:41") || localTime.equals("09:42") || localTime.equals("09:43") || localTime.equals("09:44") || localTime.equals("09:45")
|| localTime.equals("09:46") || localTime.equals("09:47") || localTime.equals("09:48") || localTime.equals("09:49") || localTime.equals("09:50") || localTime.equals("09:51") || localTime.equals("09:52")
|| localTime.equals("09:53") || localTime.equals("09:54") || localTime.equals("09:55") || localTime.equals("09:56") || localTime.equals("09:57") || localTime.equals("09:58") || localTime.equals("09:59")
|| localTime.equals("10:00") || localTime.equals("10:01") || localTime.equals("10:02") || localTime.equals("10:03") || localTime.equals("10:04") || localTime.equals("10:05") || localTime.equals("10:06")
|| localTime.equals("10:07") || localTime.equals("10:08") || localTime.equals("10:09") || localTime.equals("10:10") || localTime.equals("14:16")) {
Log.w("It is between", "those times");
boolean beenfired2 = myPrefs.getBoolean("beenfired", false);
if (beenfired2 != true) {
Log.w("yes", "it is not equal to true");
// day 1
mHandler.postDelayed(mClickRunnable, 36000);
mHandler.postDelayed(mClickRunnable, 72000);
beenfired = true;
editor.putBoolean("beenfired", beenfired);
editor.commit();
} else {
Log.w("else", "else");
}
} else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Inlopen.this);
// set title
alertDialogBuilder.setTitle("Alarm kan niet worden ingeschakeld");
// set dialog message
alertDialogBuilder
.setMessage("U kunt het alarm alleen inschakelen tussen 9:00 en 10:00 's ochtends.")
.setCancelable(false)
.setNegativeButton("Oke", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
mySwitch.setChecked(false);
editor.putBoolean("switch", false);
editor.commit();
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
} else {
//switch has been switched OFF
beenfired = false;
mHandler.removeCallbacks(mClickRunnable);
editor.putBoolean("beenfired", beenfired);
editor.commit();
editor.putBoolean("switch", false);
editor.commit();
}
}
});
}
private Handler mHandler = new Handler();
private Runnable mClickRunnable = new Runnable() {
#Override
public void run() {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(Inlopen.this)
.setSmallIcon(R.drawable.iconsmall)
.setContentTitle("DM Voet App")
.setContentText("Uw moet uw voeten controleren!");
mBuilder.setAutoCancel(true);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, mBuilder.build());
}
};
I always combine those two methods when stopping a handler :
mHandler.removeCallbacks(mClickRunnable);
mHandler.removeMessages(0);
To be honest, i dont really understand what is the difference between them, but its work for me. (and it will not work if i remove either one of them)