So, I wanna build a scheduled message. But when I try to send more than one message, the other messages can't be delivered. I wonder how to do that.
onTimeSet method
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
DateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE)+1);
Log.d("Current time: ", formatter.format(calendar.getTime()));
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
if (c.getTimeInMillis() <= calendar.getTimeInMillis()){
Log.d("Tag: ", "Denied");
Toast.makeText(this, "You can't send it if it's too early!", Toast.LENGTH_SHORT).show();
} else {
Log.d("Tag: ", "Approved");
Toast.makeText(this, "Success!", Toast.LENGTH_SHORT).show();
startSchedule(c);
Intent intent = new Intent(MessageActivity.this, MessageActivity.class);
startActivity(intent);
finish();
}
}
startSchedule method
private void startSchedule(Calendar calendar) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlertReceiver.class);
intent.putExtra("number", number);
intent.putExtra("body", body);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
DateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm");
Log.d("Test: ", ""+calendar.getTimeInMillis());
Log.d("Date: ", ""+formatter.format(calendar.getTimeInMillis()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
}
AlertReceiver class
public class AlertReceiver extends BroadcastReceiver {
String number, body;
#Override
public void onReceive(Context context, Intent intent) {
Log.d("Test: ", "Worked");;
Bundle bd = intent.getExtras();
if(bd == null){
number = "";
body = "";
}else {
number = bd.getString("number");
body = bd.getString("body");
}
Log.d("Number: ", number +"\nBody: "+body);
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(number, null, body, null, null);
}
}
Please let me know if you guys know what I should do to make things right, thanks a lot!
Related
I am a bit new to android studio, and i am making an app where the user can select the date and time, and it will schedule and alarm to go off at that time. However, when i set the alarm it does not go off. Does anyone know where i went wrong? Or what it is i can change within my code.
CustomDialogClass
public Activity c;
public Dialog d;
public CircleButton CalendarBtn, TimeBtn;
public Button CancelBtn, ProceedBtn;
public TextView CalendarTxt, TimeTxt;
public EditText ReminderTxt;
//FOR CALENDAR
final Calendar myCalendar = Calendar.getInstance();
//FOR CALENDAR
private void updateLabel(TextView edittext) {
String myFormat = "dd/MM/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.UK);
edittext.setText(sdf.format(myCalendar.getTime()));
}
//FOR CALENDAR
DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel(CalendarTxt);
}
};
public CustomDialogClass(Activity a) {
super(a);
// TODO Auto-generated constructor stub
this.c = a;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_dialog);
CalendarTxt = (TextView) findViewById(R.id.CurrentDateSelect);
TimeTxt = (TextView) findViewById(R.id.CurrentTimeSelect);
CancelBtn = (Button) findViewById(R.id.CancelBtn);
ProceedBtn = (Button) findViewById(R.id.ProceedBtn);
CancelBtn.setOnClickListener(this);
ProceedBtn.setOnClickListener(this);
CalendarBtn = (CircleButton) findViewById(R.id.calendarBtn);
TimeBtn = (CircleButton) findViewById(R.id.timeBtn);
CalendarBtn.setOnClickListener(this);
TimeBtn.setOnClickListener(this);
ReminderTxt = (EditText) findViewById(R.id.ReminderTxt);
}
#Override
public void onClick(View v) {
//On click method for buttons
switch (v.getId()) {
case R.id.calendarBtn:
new DatePickerDialog(getContext(), date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
break;
case R.id.CancelBtn:
dismiss();
break;
case R.id.timeBtn:
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
String curTime = String.format("%02d:%02d", selectedHour, selectedMinute);
TimeTxt.setText(curTime);
}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
break;
case R.id.ProceedBtn:
String TimeVal = TimeTxt.getText().toString();
String DateVal = CalendarTxt.getText().toString();
String RemindVal = ReminderTxt.getText().toString();
if ((TimeVal + DateVal + RemindVal).isEmpty()) {
Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
} else if ((TimeVal + DateVal).isEmpty()) {
Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
} else if ((TimeVal + RemindVal).isEmpty()) {
Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
} else if ((DateVal + RemindVal).isEmpty()) {
Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
} else {
String FinalAlarmVal = DateVal + " " + " " + TimeVal;
String AlarmHour = TimeVal.substring(0, 2);
String AlarmMins = TimeVal.substring(3, 5);
String AlarmMonth = DateVal.substring(3, 5);
String AlarmDay = DateVal.substring(0, 2);
System.out.println("SEWISINGHVV- "+ Integer.parseInt(AlarmMonth));
AlarmScheduler.setReminder(getContext(), Integer.parseInt(AlarmHour), Integer.parseInt(AlarmMins), Integer.parseInt(AlarmDay), Integer.parseInt(AlarmMonth)); // Here mContext is Context of Activity. If you use this code in Activity then you can pass ActivityName.this and in Fragment you can do getActivity()
Intent AlarmName = new Intent(getContext(), AlarmReceiver.class);
AlarmName.putExtra("NameOfAlarm", RemindVal);
getContext().startService(AlarmName);
}
break;
default:
break;
}
//dismiss();
//Ends dialog when button is pressed
}
AlarmScheduler
public static final int DAILY_REMINDER_REQUEST_CODE = 100;
public static final String TAG = "AlarmScheduler";
public static void setReminder(Context context, int hour, int min, int day, int month) {
Calendar calendar = Calendar.getInstance();
Calendar setcalendar = Calendar.getInstance();
setcalendar.set(Calendar.MONTH, month);
setcalendar.set(Calendar.DAY_OF_MONTH, day);
setcalendar.set(Calendar.HOUR_OF_DAY, hour);
setcalendar.set(Calendar.MINUTE, min);
setcalendar.set(Calendar.SECOND, 0);
setcalendar.set(Calendar.MILLISECOND, 0);
// cancel already scheduled reminders
cancelReminder(context, AlarmReceiver.class);
if (setcalendar.before(calendar))
setcalendar.add(Calendar.DATE, 1);
// Enable a receiver
ComponentName receiver = new ComponentName(context, AlarmReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Intent intent1 = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, DAILY_REMINDER_REQUEST_CODE, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, setcalendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
public static void cancelReminder(Context context, Class<?> cls) {
// Disable a receiver
ComponentName receiver = new ComponentName(context, cls);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Intent intent1 = new Intent(context, cls);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, DAILY_REMINDER_REQUEST_CODE, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
am.cancel(pendingIntent);
pendingIntent.cancel();
}
AlarmReceiver
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
}
I want to send a notification with the alarm manager in my application. I am using the setRepeating method because it should be in intervals. but notifications always come delayed.
For example, I would like to receive a notification at 12:14. but notification is coming sometimes 12:17, sometimes 12:20
Thanks in advance
Note: doze mode off
For Example:
thatDay Sat Apr 25 16:30:00 GMT+03:00 2020
today Sat Apr 25 16:07:44 GMT+03:00 2020
thatDay.getTimeInMillis() = 1587821400000
#Override
protected void onStop() {
if (notification) {
Calendar thatDay = Calendar.getInstance();
Calendar today = Calendar.getInstance();
int today_month_day = today.get(Calendar.DAY_OF_MONTH);
int today_month = today.get(Calendar.MONTH);
int today_year = today.get(Calendar.YEAR);
thatDay.setTime(new Date(0));
thatDay.set(Calendar.DAY_OF_MONTH, today_month_day);
thatDay.set(Calendar.MONTH, today_month);
thatDay.set(Calendar.YEAR, today_year);
thatDay.set(Calendar.HOUR_OF_DAY, 8);
thatDay.set(Calendar.MINUTE, 0);
thatDay.set(Calendar.SECOND, 0);
thatDay.set(Calendar.MILLISECOND, 0);
Calendar calendar = Calendar.getInstance();
if (calendar.get(Calendar.HOUR_OF_DAY) < 23 && calendar.get(Calendar.HOUR_OF_DAY) > 7) {
if (calendar.get(Calendar.MINUTE) < 30) {
thatDay.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY));
thatDay.set(Calendar.MINUTE, 30);
} else {
thatDay.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + 1);
}
} else if (thatDay.getTimeInMillis() - today.getTimeInMillis() < 0) {
thatDay.set(Calendar.DAY_OF_MONTH, today_month_day + 1);
} else {
thatDay.set(Calendar.DAY_OF_MONTH, today_month_day);
}
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
intent.putExtra("NotificationID", 6);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 7, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Objects.requireNonNull(alarmManager).setRepeating(AlarmManager.RTC_WAKEUP, thatDay.getTimeInMillis(), waterList[waterCheck], pendingIntent);
super.onStop();
}
#SuppressLint("BatteryLife")
#RequiresApi(api = Build.VERSION_CODES.M)
private void requestBattery() {
Intent intent = new Intent();
String packageName = context.getPackageName();
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (!(Objects.requireNonNull(pm).isIgnoringBatteryOptimizations(packageName))) {
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
startActivityForResult(intent, BATTERY_PERMISSION);
}
}
This is because setRepeating is only fired, when something else is happening in the background. Mainly this is due to battery saving. The best way to set a repeating alarm is to use setExact and set another alarm once the first one was fired.
Alarmmanager:
public class AlarmManagerSetup {
public static Boolean alarmActivated;
public static Long milliSeconds;
public void startAlarm(Calendar c, Context context, Database database) {
android.app.AlarmManager alarmManager = (android.app.AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, intent, 0);
c.setTimeInMillis(milliSeconds);
//compares to the current time and only adds when it is later than now
if (c.before(Calendar.getInstance())) {
c.add(Calendar.DATE, 1);
}
if (Build.VERSION.SDK_INT >= 23) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
} else if (Build.VERSION.SDK_INT >= 19) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
}
}
And inside the Alert Receiver you do this:
public class AlertReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Context appContext = context.getApplicationContext();
CalendarSearch calendar = new CalendarSearch(context);
calendar.calendar();
NotificationHelper notificationHelper = new NotificationHelper(context);
NotificationCompat.Builder nb = notificationHelper.getChannelNotification(appContext);
notificationHelper.getManager().notify(1, nb.build());
AlarmManagerSetup alarmManager = new AlarmManagerSetup();
Calendar c = Calendar.getInstance();
c.setTimeInMillis(milliSeconds);
c.add(Calendar.DATE, 1);
milliSeconds = c.getTimeInMillis();
alarmManager.startAlarm(c, appContext, database);
}
I am having an Calendar Event with start date as (24hrs format) 27-Apr-2016 11:00:00 and end date as 29-Apr-2016 11:00:00. I am having three timings 10:45:00, 10:30:00 and 10:15:00 which are calculated for alerting the event prior to the actual set timings (i.e 15 mins, 30 mins and 45 mins early to the start date).
Also the alarm must repeat daily for the same prior timings till the end date is reached.
Here is how i tried to do it, How ever the below code does not invoke the alarm nor it repeats daily
In the MainActivity.java
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, Broadcast.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.set(2016,03,27,11,00,00);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()-(60000*15), pendingIntent); // subtract for 15 mins prior alarm time
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()-(60000*30), pendingIntent); // subtract for 30 mins prior alarm time
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()-(60000*45), pendingIntent); // subtract for 45 mins prior alarm time
In the Broadcast.java
Log.i("Alarm", "Alarm Manager is called");
Toast.makeText(context, new Date().toString(), Toast.LENGTH_SHORT).show();
How can I achieve this? Please help
Here is my sample code, Try this:
Modify the date and time as your need in the below code.
public static int REPEAT_NOTIFICATION1 = 201;
public static int REPEAT_NOTIFICATION2 = 202;
public static int REPEAT_NOTIFICATION3 = 203;
private void repeatNotification() {
final DateTime dateTime1 = DateTime.now();
dateTime1.hourOfDay().setCopy(7);
dateTime1.minuteOfHour().setCopy(30);
dateTime1.secondOfMinute().setCopy(00);
final Calendar calendarNotifiedTime1 = Calendar.getInstance();
calendarNotifiedTime1.set(Calendar.HOUR, dateTime1.getHourOfDay());
calendarNotifiedTime1.set(Calendar.MINUTE, dateTime1.getMinuteOfHour());
calendarNotifiedTime1.set(Calendar.SECOND, dateTime1.getSecondOfMinute());
calendarNotifiedTime1.set(Calendar.AM_PM, Calendar.AM);
final DateTime dateTime2 = DateTime.now();
dateTime2.hourOfDay().setCopy(12);
dateTime2.minuteOfHour().setCopy(30);
dateTime2.secondOfMinute().setCopy(00);
final Calendar calendarNotifiedTime2 = Calendar.getInstance();
calendarNotifiedTime2.set(Calendar.HOUR, dateTime2.getHourOfDay());
calendarNotifiedTime2.set(Calendar.MINUTE, dateTime2.getMinuteOfHour());
calendarNotifiedTime2.set(Calendar.SECOND, dateTime2.getSecondOfMinute());
calendarNotifiedTime2.set(Calendar.AM_PM, Calendar.PM);
final DateTime dateTime3 = DateTime.now();
dateTime3.hourOfDay().setCopy(6);
dateTime3.minuteOfHour().setCopy(30);
dateTime3.secondOfMinute().setCopy(00);
final Calendar calendarNotifiedTime3 = Calendar.getInstance();
calendarNotifiedTime3.set(Calendar.HOUR, dateTime3.getHourOfDay());
calendarNotifiedTime3.set(Calendar.MINUTE, dateTime3.getMinuteOfHour());
calendarNotifiedTime3.set(Calendar.SECOND, dateTime3.getSecondOfMinute());
calendarNotifiedTime3.set(Calendar.AM_PM, Calendar.PM);
Intent intent1 = new Intent(EmptyActivity.this, NotificationReceiver.class);
intent1.putExtra(NotificationReceiver.NOTIFICATION_MESSAGE, "Repeat " + dateTime1.getHourOfDay() + ":" + dateTime1.getMinuteOfHour() + ":" + dateTime1.getSecondOfMinute());
Intent intent2 = new Intent(EmptyActivity.this, NotificationReceiver.class);
intent2.putExtra(NotificationReceiver.NOTIFICATION_MESSAGE, "Repeat " + dateTime2.getHourOfDay() + ":" + dateTime2.getMinuteOfHour() + ":" + dateTime2.getSecondOfMinute());
Intent intent3 = new Intent(EmptyActivity.this, NotificationReceiver.class);
intent3.putExtra(NotificationReceiver.NOTIFICATION_MESSAGE, "Repeat " + dateTime3.getHourOfDay() + ":" + dateTime3.getMinuteOfHour() + ":" + dateTime3.getSecondOfMinute());
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(EmptyActivity.this, REPEAT_NOTIFICATION1, intent3, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(EmptyActivity.this, REPEAT_NOTIFICATION2, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntent3 = PendingIntent.getBroadcast(EmptyActivity.this, REPEAT_NOTIFICATION3, intent3, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
cancelNotification(REPEAT_NOTIFICATION1);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendarNotifiedTime1.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent1);
cancelNotification(REPEAT_NOTIFICATION2);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendarNotifiedTime2.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent2);
cancelNotification(REPEAT_NOTIFICATION3);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendarNotifiedTime3.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent3);
}
Cancel Notification:
public void cancelNotification(int requestCode) {
try {
Intent notificationIntent = new Intent(getApplicationContext(), NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), requestCode, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
BroadCast Receiver:
public class NotificationReceiver extends BroadcastReceiver {
public static String NOTIFICATION_MESSAGE = "notificationMessage";
public static int REPEAT_NOTIFICATION1 = 201;
public static int REPEAT_NOTIFICATION2 = 202;
public static int REPEAT_NOTIFICATION3 = 203;
Context context;
#Override
public void onReceive(Context context, Intent intent) {
this.context = context;
//Assume StartDate = yesterday.
DateTime startDate = DateTime.now().minusDays(1);
//Assume EndDate = tomorrow
DateTime endDate = startDate.plusDays(2);
DateTime today = DateTime.now();
if (today.isBefore(endDate) || today.isEqual(endDate)) {
String message = intent.getStringExtra(NOTIFICATION_MESSAGE);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//Define sound URI
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent notificationIntent = new Intent(context, EmptyActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
final DateTime dateTime = DateTime.now();
int color = 0xffffaa00;
// int color1 = context.getColor(R.color.notificatinBackgroundColor);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.drawable.festi_push_message_small);
builder.setContentIntent(pendingIntent);
builder.setContentTitle("Notification Sample");
builder.setAutoCancel(true);
builder.setContentText(message + ", Current Time : " + dateTime.getHourOfDay() + ":" + dateTime.getMinuteOfHour() + ":" + dateTime.getSecondOfMinute());
builder.setSound(soundUri);
builder.setLights(Color.RED, 1000, 1000);
builder.setColor(color);
Notification notification = builder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(102938, notification);
} else {
cancelNotification(REPEAT_NOTIFICATION1);
cancelNotification(REPEAT_NOTIFICATION2);
cancelNotification(REPEAT_NOTIFICATION3);
}
}
public void cancelNotification(int requestCode) {
try {
Intent notificationIntent = new Intent(context, NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Manifest.xml
<receiver android:name=".NotificationReceiver" />
I have a receiver inside a service and the receiver isnt working. I did not declare it inside the manifest as it is made it in the service. Here is the code
package com.todaysfuture.dynpin;
public class MyBroadcastReceiver extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
AlarmManager alarmMgr;
PendingIntent alarmIntent;
Calendar c = Calendar.getInstance();
int hour=c.get(Calendar.HOUR_OF_DAY);
int minute=c.get(Calendar.MINUTE);
Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
Context context=getApplicationContext();
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent1 = new Intent(context, MyBroadcastReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent1, 0);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 60, alarmIntent);
IntentFilter filter = new IntentFilter();
final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
{
MainActivity ii=new MainActivity();
ii.displayer();
String LOG_TAG="DevicePolicyAdmin";
Log.v(LOG_TAG, "Service Started");
Calendar c = Calendar.getInstance();
int hour=c.get(Calendar.HOUR_OF_DAY);
int minute=c.get(Calendar.MINUTE);
Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
String date = sdf.format(calendar.getTime());
String str=date.charAt(0)+""+date.charAt(1)+""+date.charAt(3)+""+date.charAt(4);
MainActivity.minochaDevicePolicyManager.resetPassword(str, 0);
}
}
};
registerReceiver(receiver, filter);
return null;
}
}
The Service has been declared in the manifest. Yet it isnt working. What could possibly be the issue?
EDIT---------------------------------------------------------------------
Here is the updated Service
public class MyBroadcastReceiver extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
Calendar c = Calendar.getInstance();
int hour=c.get(Calendar.HOUR_OF_DAY);
int minute=c.get(Calendar.MINUTE);
Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
MainActivity ii=new MainActivity();
ii.displayer();
String LOG_TAG="DevicePolicyAdmin";
Log.v(LOG_TAG, "Service Started");
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
String date = sdf.format(calendar.getTime());
String str=date.charAt(0)+""+date.charAt(1)+""+date.charAt(3)+""+date.charAt(4);
MainActivity.minochaDevicePolicyManager.resetPassword(str, 0);
return null;
}
}
It still isnt working
I want to send sms frequently like that in question; I am using spinner option with some option like that(daily,weekly,every 5 minutes),while i select any option in these spinner it has to go like that.
Alaramsms.java:
private String[] Time_CATEGORY = { "Once","Every hour","Every day", "Weekdays(Mon-Fri)", "Weekend", "Every month",
"Every year" };
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edittextSmsNumber = (EditText)findViewById(R.id.smsnumber);
edittextSmsText = (EditText)findViewById(R.id.smstext);
ImageButton get = (ImageButton)findViewById(R.id.getc);
spinnerTime = (Spinner) findViewById(R.id.spinnerstate);
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, Time_CATEGORY);
adapter_state
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Button buttonStart = (Button)findViewById(R.id.startalarm);
Button buttonCancel = (Button)findViewById(R.id.cancelalarm);
spinnerTime.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
spinnerTime.setSelection(position);
//spinnerCapital.setSelection(position);
String myPrayer = (String) spinnerTime.getSelectedItem();
}
public void onNothingSelected(AdapterView<?> parent) {
}});
get.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(AndroidAlarmSMS.this, ContactActivity.class);
startActivityForResult(i, ResultCode);
}
});
buttonStart.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
smsNumber = edittextSmsNumber.getText().toString();
smsText = edittextSmsText.getText().toString();
picker = new Dialog(AndroidAlarmSMS.this);
picker.setContentView(R.layout.picker_frag);
picker.setTitle("Select Date and Time");
datep = (DatePicker)picker.findViewById(R.id.datePicker);
timep = (TimePicker)picker.findViewById(R.id.timePicker1);
set = (Button)picker.findViewById(R.id.btnSet);
set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TextUtils.isEmpty(smsNumber))
{
finish();
}
else
{
String[] s =edittextSmsNumber.getText().toString().split(";");
for(int i=0 ;i<s.length;i++)
{
picker.dismiss();
Intent myIntent = new Intent(AndroidAlarmSMS.this, MyAlarmService.class);
Bundle bundle = new Bundle();
bundle.putCharSequence("extraSmsNumber", smsNumber);
bundle.putCharSequence("extraSmsText", smsText);
myIntent.putExtras(bundle);
pendingIntent = PendingIntent.getService(AndroidAlarmSMS.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(datep.getYear(), datep.getMonth(), datep.getDayOfMonth(),
timep.getCurrentHour(), timep.getCurrentMinute(), 0);
// long startTime = calendar.getTimeInMillis();
// Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(System.currentTimeMillis());
// calendar.add(Calendar.SECOND, 60);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(AndroidAlarmSMS.this,
"Start Alarm with \n" +
"smsNumber = " + smsNumber + "\n" +
"smsText = " + smsText,
Toast.LENGTH_LONG).show();
}
}
}
});
picker.show();
}});
buttonCancel.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
Toast.makeText(AndroidAlarmSMS.this, "Cancel!", Toast.LENGTH_LONG).show();
}});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ResultCode) {
if(resultCode == RESULT_OK){
sendlist =data.getStringArrayListExtra("name");
if(sendlist!=null)
{
for(int i=0;i<sendlist.size();i++)
{
edittextSmsNumber.append(sendlist.get(i).toString());
edittextSmsNumber.append(";");
}
}
if (resultCode == RESULT_CANCELED) {
}
}
}
}
Now I am sending sms using scheduling time; it is going now at what user select the time.But i want to send sms According to spinner selection.
You need to use setInexactRepeating method
For example, to set alarm "Every Day" :
alarmMgr0 .setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY,
AlarmManager.INTERVAL_DAY, intent);
This is your AndroidAlarmSMS.Java file.
private String[] Time_CATEGORY = { "Once", "Every 5 Minutes", "Every hour",
"Every day", "Weekly", "Weekdays(Mon-Fri)", "Weekend",
"Every month", "Every year" };
EditText edittextSmsNumber, edittextSmsText;
String smsNumber, smsText;
Dialog picker;
Button select;
Button set;
String mytime;
ImageButton get;
TimePicker timep;
DatePicker datep;
Integer hour, minute, month, day, year, week;
TextView time, date;
private PendingIntent pendingIntent;
static int ResultCode = 12;
ArrayList<String> sendlist = new ArrayList<String>();
Spinner spinnerTime;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edittextSmsNumber = (EditText) findViewById(R.id.smsnumber);
edittextSmsText = (EditText) findViewById(R.id.smstext);
ImageButton get = (ImageButton) findViewById(R.id.getc);
datep = (DatePicker) findViewById(R.id.datePicker);
timep = (TimePicker) findViewById(R.id.timePicker1);
Button buttonStart = (Button) findViewById(R.id.startalarm);
Button buttonCancel = (Button) findViewById(R.id.cancelalarm);
spinnerTime = (Spinner) findViewById(R.id.spinnerstate);
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, Time_CATEGORY);
adapter_state
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerTime.setAdapter(adapter_state);
spinnerTime.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
spinnerTime.setSelection(position);
// spinnerCapital.setSelection(position);
mytime = (String) spinnerTime.getSelectedItem();
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
get.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(AndroidAlarmSMS.this,
ContactActivity.class);
startActivityForResult(i, ResultCode);
}
});
buttonStart.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
smsNumber = edittextSmsNumber.getText().toString();
smsText = edittextSmsText.getText().toString();
// picker = new Dialog(AndroidAlarmSMS.this);
// picker.setContentView(R.layout.picker_frag);
// picker.setTitle("Select Date and Time");
// set = (Button)picker.findViewById(R.id.btnSet);
// set.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
if (TextUtils.isEmpty(smsNumber)) {
finish();
}
else {
String[] s = edittextSmsNumber.getText().toString()
.split(";");
for (int i = 0; i < s.length; i++) {
// picker.dismiss();
Intent myIntent = new Intent(AndroidAlarmSMS.this,
MyAlarmService.class);
Bundle bundle = new Bundle();
bundle.putCharSequence("extraSmsNumber", smsNumber);
bundle.putCharSequence("extraSmsText", smsText);
myIntent.putExtras(bundle);
pendingIntent = PendingIntent.getService(
AndroidAlarmSMS.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
// long startTime = calendar.getTimeInMillis();
// Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(System.currentTimeMillis());
// calendar.add(Calendar.SECOND, 60);
if (mytime.equals("Once")) {
Calendar calendar = Calendar.getInstance();
calendar.set(datep.getYear(), datep.getMonth(),
datep.getDayOfMonth(),
timep.getCurrentHour(),
timep.getCurrentMinute(), 0);
alarmManager.set(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), pendingIntent);
} else if (mytime.equals("Every 5 Minutes")) {
Calendar calendar = Calendar.getInstance();
calendar.set(datep.getYear(), datep.getMonth(),
datep.getDayOfMonth(),
timep.getCurrentHour(),
timep.getCurrentMinute(), 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 1000 * 60 * 5,
pendingIntent); // Millisec * Second *
// Minute
} else if (mytime.equals("Every hour")) {
Calendar calendar = Calendar.getInstance();
calendar.set(datep.getYear(), datep.getMonth(),
datep.getDayOfMonth(),
timep.getCurrentHour(),
timep.getCurrentMinute(), 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 1000 * 60 * 60,
pendingIntent); // Millisec * Second *
// Minute
} else if (mytime.equals("Every day")) {
Calendar calendar = Calendar.getInstance();
calendar.set(datep.getYear(), datep.getMonth(),
datep.getDayOfMonth(),
timep.getCurrentHour(),
timep.getCurrentMinute(), 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
24 * 60 * 60 * 1000, pendingIntent);
} else if (mytime.equals("Weekly")) {
Calendar calendar = Calendar.getInstance();
calendar.set(datep.getYear(), datep.getMonth(),
datep.getDayOfMonth(),
timep.getCurrentHour(),
timep.getCurrentMinute(), 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 7 * 24 * 60
* 60 * 1000, pendingIntent);
} else if (mytime.equals("Weekdays(Mon-Fri)")) {
forWeekdays();
} else if (mytime.equals("Weekend")) {
forWeekend();
} else if (mytime.equals("Every month")) {
Calendar calendar = Calendar.getInstance();
calendar.set(datep.getYear(), datep.getMonth(),
datep.getDayOfMonth(),
timep.getCurrentHour(),
timep.getCurrentMinute(), 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 30 * 24 * 60
* 60 * 1000, pendingIntent);
} else {
Calendar calendar = Calendar.getInstance();
calendar.set(datep.getYear(), datep.getMonth(),
datep.getDayOfMonth(),
timep.getCurrentHour(),
timep.getCurrentMinute(), 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 365 * 24 * 60
* 60 * 1000, pendingIntent);
}
Toast.makeText(
AndroidAlarmSMS.this,
"Start Alarm with \n" + "smsNumber = "
+ smsNumber + "\n" + "smsText = "
+ smsText, Toast.LENGTH_LONG).show();
}
}
}
});
// picker.show();
// }});
buttonCancel.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
Toast.makeText(AndroidAlarmSMS.this, "Cancel!",
Toast.LENGTH_LONG).show();
}
});
}
public void forWeekdays() {
Calendar calendar2 = Calendar.getInstance();
calendar2.set(datep.getYear(), datep.getMonth(), datep.getDayOfMonth(),
timep.getCurrentHour(), timep.getCurrentMinute(), 0);
int day = calendar2.get(Calendar.DAY_OF_WEEK);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
if (day == 2 || day == 3 || day == 4 || day == 5 || day == 6) {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar2.getTimeInMillis(), 24 * 60 * 60 * 1000,
pendingIntent);
}
}
public void forWeekend() {
Calendar calendar2 = Calendar.getInstance();
calendar2.set(datep.getYear(), datep.getMonth(), datep.getDayOfMonth(),
timep.getCurrentHour(), timep.getCurrentMinute(), 0);
int day = calendar2.get(Calendar.DAY_OF_WEEK);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
if (day == 1 || day == 7) {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar2.getTimeInMillis(), 24 * 60 * 60 * 1000,
pendingIntent);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ResultCode) {
if (resultCode == RESULT_OK) {
sendlist = data.getStringArrayListExtra("name");
if (sendlist != null) {
for (int i = 0; i < sendlist.size(); i++) {
edittextSmsNumber.append(sendlist.get(i).toString());
edittextSmsNumber.append(";");
}
}
if (resultCode == RESULT_CANCELED) {
}
}
}
instead of using alarmManager.set(), you can use alarmManager.setRepeating() to repeat the task..
You have to use setRepeating() mmethod of AlarmManager to have this achieved.
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), repeat_interval, pendingIntent);
In the above piece of code you've to replace the value of 'repeat_interval' as per your selection i.e., daily,weekly,every 5 minutes. It denotes the interval at which the alarm repeats. But you've to pass those values in milliseconds.