AlarmScheduler not working/setting off alarm in Android Studio - java

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

Related

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.Calendar.before(java.lang.Object)' on a null object reference

The user can press three buttons: One will bring up a clock to select the time, another will bring up a calendar to select the date. The third button is to be pressed last, and is meant to send out a notification.
When I press on the last button, I get the error:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.Calendar.before(java.lang.Object)' on a null object reference
at com.example.meeldetuletuserakendus.MeeldetuletusActivity.startAlarm(MeeldetuletusActivity.java:105)
Something goes wrong when trying to do the method startAlarm(c).
I know for certain that everything worked perfectly when the code only had a choice to choose a time, but something broke when I coded the date picking part of the code. So the problem probably has something to do with the date.
MeeldetuletusActivity.java:
public class MeeldetuletusActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener, DatePickerDialog.OnDateSetListener {
String timeText;
TextView textTime;
Button nupp_vali, nupp_katkesta, nupp_kuupaev, nupp_alarm;
Calendar c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meeldetuletus);
nupp_vali = findViewById(R.id.button2);
nupp_katkesta = findViewById(R.id.nupp_katkesta);
nupp_kuupaev = findViewById(R.id.button);
nupp_alarm = findViewById(R.id.button3);
nupp_alarm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startAlarm(c);
}
});
nupp_vali.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogFragment timePicker = new TimePickerFragment();
timePicker.show(getSupportFragmentManager(), "time picker");
}
});
nupp_kuupaev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogFragment kuupaevaValija = new KuupaevaFragment();
kuupaevaValija.show(getSupportFragmentManager(), "date picker");
}
});
nupp_katkesta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
katkestaAlarm();
Toast.makeText(MeeldetuletusActivity.this, "Meeldetuletus unustatud", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
}
public void onDateSet (DatePicker view, int aasta, int kuu, int paev) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, aasta);
c.set(Calendar.MONTH, kuu);
c.set(Calendar.DAY_OF_MONTH, paev);
}
private void startAlarm(Calendar c) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, NotificationPublisher.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
if (c.before(Calendar.getInstance())) {
c.add(Calendar.DATE, 1);
}
Objects.requireNonNull(alarmManager).setExact(AlarmManager.RTC_WAKEUP,
c.getTimeInMillis(), pendingIntent);
}
private void katkestaAlarm() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent myIntent = new Intent(getApplicationContext(), NotificationPublisher.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getApplicationContext(), 1, myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(pendingIntent);
}
}
Row 105 is:
if (c.before(Calendar.getInstance())) {
KuupaevaFragment.java:
public class KuupaevaFragment extends DialogFragment {
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int aasta = c.get(Calendar.YEAR);
int kuu = c.get(Calendar.MONTH);
int paev = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) getActivity(),
aasta, kuu, paev);
}
}
TimePickerFragment.java: (This worked perfectly before, I'm only putting this here so you can see what KuupaevaFragment.java is meant to do aswell)
public class TimePickerFragment extends DialogFragment {
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(getActivity(), (TimePickerDialog.OnTimeSetListener) getActivity(),
hour, minute, DateFormat.is24HourFormat(getActivity()));
}
}
NotificationPublisher.java:
public class NotificationPublisher extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationHelper notificationHelper = new NotificationHelper(context);
NotificationCompat.Builder nb = notificationHelper.getChannelNotification();
notificationHelper.getManager().notify(1, nb.build());
Notification notification = nb.build();
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_SOUND;
}
}
NotificationHelper.Java:
class NotificationHelper extends ContextWrapper {
public static final String channelID = "channelID";
public static final String channelName = "Channel Name";
private NotificationManager notificationManager;
public NotificationHelper(Context base) {
super(base);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannel();
}
}
#TargetApi(Build.VERSION_CODES.O)
private void createChannel() {
NotificationChannel channel = new NotificationChannel(channelID, channelName,
NotificationManager.IMPORTANCE_HIGH);
getManager().createNotificationChannel(channel);
}
public NotificationManager getManager() {
if (notificationManager == null) {
notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
}
return notificationManager;
}
public NotificationCompat.Builder getChannelNotification() {
return new NotificationCompat.Builder(getApplicationContext(), channelID)
.setContentTitle("Meeldetuletus")
.setContentText("Teie valitud aeg on käes")
.setSmallIcon(R.drawable.ic_baseline_notifications_active_24);
}
}
Try to reference to the Activity's field c in onTimeSet and onDateSet:
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
}
public void onDateSet(DatePicker view, int aasta, int kuu, int paev) {
c = Calendar.getInstance();
c.set(Calendar.YEAR, aasta);
c.set(Calendar.MONTH, kuu);
c.set(Calendar.DAY_OF_MONTH, paev);
}
So instead of Calendar c = Calendar.getInstance(); write c = Calendar.getInstance(); like in the code above.
Or you can try to initialize c property in Activity:
Calendar c = Calendar.getInstance();
and use it to change Calendar's properties, for example in onTimeSet method:
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
}

Send multiple messages in different times Android Java

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!

Passing data from Activity to Service

I have a problem while passing String to a Service from Activity. What I am trying to do is to pass different Strings each time I call Service. I use Intent (putExtra() method each time). The problem is that each time it shows the first String that I passed. Is there a way to implement that?
Here is my Activity, Broadcast Receiver, Service
public class MainActivity extends Activity implements View.OnClickListener{
private PendingIntent pendingIntent;
private EditText event;
private Button submit, date, time;
private static final int DIALOG_DATE = 1;
private static final int DIALOG_TIME = 2;
private int myYear = 2014;
private int myMonth = 8;
private int myDay = 16;
private int myHour = 6;
private int myMinute = 30;
private List<String> events;
private List<Calendar> dateTimes;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
event = (EditText)findViewById(R.id.event);
submit = (Button)findViewById(R.id.submit);
submit.setOnClickListener(this);
date = (Button)findViewById(R.id.date);
date.setOnClickListener(this);
time = (Button)findViewById(R.id.time);
time.setOnClickListener(this);
events = new ArrayList<String>();
dateTimes = new ArrayList<Calendar>();
//List<Calendar> events = new ArrayList<Calendar>();
}
#Override
protected Dialog onCreateDialog(int id) {
if(id == DIALOG_DATE) {
DatePickerDialog datePickerDialog = new DatePickerDialog(this, myCallBack, myYear, myMonth, myDay);
return datePickerDialog;
}else {
TimePickerDialog timePickerDialog = new TimePickerDialog(this, myCallBack1, myHour, myMinute, true);
return timePickerDialog;
}
}
DatePickerDialog.OnDateSetListener myCallBack = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
myYear = year;
myMonth = month;
myDay = day;
}
};
TimePickerDialog.OnTimeSetListener myCallBack1 = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hour, int minute) {
myHour = hour;
myMinute = minute;
}
};
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.date:
showDialog(DIALOG_DATE);
break;
case R.id.time:
showDialog(DIALOG_TIME);
break;
case R.id.submit:
String eventS = event.getText().toString();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, myMonth);
calendar.set(Calendar.YEAR, myYear);
calendar.set(Calendar.DAY_OF_MONTH, myDay);
calendar.set(Calendar.HOUR_OF_DAY, myHour);
calendar.set(Calendar.MINUTE, myMinute);
calendar.set(Calendar.SECOND, 0);
// calendar.set(Calendar.AM_PM, Calendar.PM);
Intent myIntent = new Intent(MainActivity.this, BR.class);
myIntent.putExtra("event", eventS);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
event.setText("");
break;
}
}
public class BR extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, MyService.class);
intent.getExtras().getString("event");
myIntent.putExtra("event", intent.getStringExtra("event"));
context.startService(myIntent);
Log.i("myLogs", "BR started");
}
}
public class MyService extends Service {
private NotificationManager mManager;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
String event = intent.getExtras().getString("event");
Notification notification = new Notification(R.drawable.ic_launcher, "This is a test message!", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(), event, event, pendingNotificationIntent);
mManager.notify(0, notification);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
A service can't be stopped until it's finish. You have to wait that your current service finish to send other data. You can collect all your strings and send them all together or wait until your background service finish

How to send sms frequently like these(daily, weekly, every 5 minutes, every hour)

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.

SMS scheduling not sending sms

i am trying to send Message at a scheduled time in my app
here is my activty
public class Lenditem extends Activity {
Context mContext;
private int mHour;
private int mMin;
private int mYear;
private int mMonth;
private int mDay;
Button b1, b2, b3;
EditText et1, et2,et3;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//Full screen code
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.lenditem);
b1 = (Button)findViewById(R.id.bselectcontactlenditem);
b3 = (Button)findViewById(R.id.bcancellenditem);
et1 = (EditText)findViewById(R.id.etdesclenditem);
et2 = (EditText)findViewById(R.id.etamountlenditem);
et3 = (EditText)findViewById(R.id.lietentercontact);
Button dateSet=(Button) findViewById(R.id.limyDatePickerButton);
Button timeSet=(Button) findViewById(R.id.limyTimePickerButton);
b3.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
boolean diditWork = true;
try {
String Desc1 = et1.getText().toString();
String Amt1 = et2.getText().toString();
Databaselentitem entry = new Databaselentitem(Lenditem.this);
entry.open();
entry.createEntry1(Desc1, Amt1);
entry.close();
} catch (Exception e) {
diditWork = false;
Toast.makeText(getApplicationContext(), "Something's Wrong.!!", Toast.LENGTH_LONG).show();
} finally {
if (diditWork) {
Toast.makeText(getApplicationContext(), "Reminder saved successfully.!!", Toast.LENGTH_LONG).show();
}
}
}
});
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// user BoD suggests using Intent.ACTION_PICK instead of
// .ACTION_GET_CONTENT to avoid the chooser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
}
});
dateSet.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent localIntent1 = new Intent();
localIntent1.setClass(Lenditem.this.mContext, TimePickerActivity.class);
Lenditem.this.startActivityForResult(localIntent1, 0);
return;
/* DatePickerDialog.OnDateSetListener d=new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthofyear, int dayofmonth) {
// TODO Auto-generated method stub
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
mMonth=monthofyear;
mYear=year;
mDay=dayofmonth;
Toast.makeText(getBaseContext(), "Date Set is :"+mDay+"/"+(mMonth+1)+"/"+mYear, Toast.LENGTH_SHORT).show();
}
};
// TODO Auto-generated method stub
new DatePickerDialog(Lenditem.this,d,Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_MONTH).show();
*/ }
});
timeSet.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
TimePickerDialog.OnTimeSetListener t = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view2, int hour, int min) {
// TODO Auto-generated method stub
mHour = hour;
mMin = min;
if (mHour >= 12)
mHour = mHour - 12;
Log.d("MYAPP", "hh:" + mHour + "\nmm:" + mMin);
Toast.makeText(getBaseContext(),
"Time Set is:" + mHour + ":" + mMin + ":00",
Toast.LENGTH_SHORT).show();
}
};
Calendar cal = Calendar.getInstance();
new TimePickerDialog(Lenditem.this, t, cal
.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE),
true).show();
}
});
Button saveAndClearBtn = (Button) findViewById(R.id.bSubmitlenditem);
saveAndClearBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Calendar myCal = Calendar.getInstance();
long timeToTrigger;
myCal.set(Calendar.YEAR, mYear);
myCal.set(Calendar.MONTH, mMonth);
myCal.set(Calendar.DAY_OF_MONTH, mDay);
myCal.set(Calendar.HOUR, mHour);
myCal.set(Calendar.MINUTE, mMin);
myCal.set(Calendar.SECOND, 0);
long setTime = myCal.getTimeInMillis();
if (setTime > System.currentTimeMillis()) {
timeToTrigger = setTime - System.currentTimeMillis();
EditText edt1 = (EditText) findViewById(R.id.bselectcontactlenditem);
EditText edt2 = (EditText) findViewById(R.id.litxtMessage);
String msg = edt2.getText().toString();
String telno = edt1.getText().toString();
int count = 0;
SQLiteDatabase db = openOrCreateDatabase("MYDBli",
MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS mySmsSchedulerli(SlNo VARCHAR,Number VARCHAR,Msg VARCHAR);");
String s = "INSERT INTO mySmsSchedulerli VALUES ('" + count
+ "','" + telno + "','" + msg + "');";
db.execSQL(s);
Log.d("MYREC", "Insertion of data successfull");
db.close();
edt1.setText("");
edt2.setText("");
Intent intent = new Intent();
intent.setClass(Lenditem.this, MyBroadcastRecieverli.class);
Bundle b = new Bundle();
b.putString("index", Integer.toString(count));
intent.putExtras(b);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
Lenditem.this, (int) Math.random(), intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + timeToTrigger,
pendingIntent);
count++;
Toast.makeText(
getBaseContext(),
"Sms Scheduled after:" + (timeToTrigger / (1000*60*60))+" Hours "+(timeToTrigger/(1000*60))+" Minutes "
+(timeToTrigger/1000)+ " sec.", Toast.LENGTH_SHORT).show();
Log.d("MYAPP", "Set Time:" + (setTime / 1000) + "Sec. \n"
+ "Cur time:" + System.currentTimeMillis() / 1000);
Log.d("MYAPP", "Time to trigger:" + (timeToTrigger / 1000)
+ "sec.");
} else {
Toast.makeText(getBaseContext(),
"Please Enter a valid time", Toast.LENGTH_SHORT)
.show();
Calendar calendar = Calendar.getInstance();
int h = calendar.get(Calendar.HOUR);
int m = calendar.get(Calendar.MINUTE);
Log.d("MYAPP", "cur HH:" + h + "\ncur MM:" + m);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
et3.setText(number);
}
}
this is broadcast class
public class MyBroadcastRecieverli extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
int myCount;
String cnt=intent.getStringExtra("index");
if(cnt==null)
Log.d("MYAPP","Data not received");
Log.d("MYAPP", "Count:"+cnt);
myCount=Integer.parseInt(cnt);
Log.d("MYAPP","Broadcast receiver called...");
SQLiteDatabase db=arg0.openOrCreateDatabase("MYDB",Context.MODE_PRIVATE, null);
Cursor c=db.rawQuery("SELECT Number, Msg FROM mySmsSchedulerli WHERE SlNo=="+myCount, null);
Log.d("MYAPP", "Cursor reference obtained...");
if(c!=null)
{
c.moveToFirst();
}
else
Log.d("MYAPP", "cursor is null");
/* c.moveToFirst();*/
String num=c.getString(c.getColumnIndex("Number"));
String myMsg=c.getString(c.getColumnIndex("Msg"));
Log.d("MYAPP", "number:"+num+"\nMsg:"+myMsg);
SmsManager sm = SmsManager.getDefault();
sm.sendTextMessage(num, null, myMsg, null, null);
Log.d("MYAPP", "Message Sent");
Toast.makeText(arg0, "Msg sent successfully", Toast.LENGTH_LONG).show();
String table="mySmsSchedulerli";
String whereClause = "SlNo = ?";
String[] whereArgs = new String[] { Integer.toString(Sms.count) };
db.delete(table, whereClause, whereArgs);
db.close();
Log.d("MYAPP", "Entry deleted..");
}
}
it is showing the toast that your msg will be send after xxxx seconds but not sending msg at scheduled time.
can anybody help me plzzz
Try to use Broadcast Receive first and then start a service.
Something like that:
create a function:
public static void setRecurringAlarm(Context context, Class<?> cls, int time, int minute) {
Calendar updateTime = Calendar.getInstance();
updateTime.setTimeZone(TimeZone.getDefault());
updateTime.set(Calendar.HOUR_OF_DAY, time);
updateTime.set(Calendar.MINUTE, minute);
Intent alarm = new Intent(context, cls);
PendingIntent recurringAlarm = PendingIntent.getBroadcast(context, 654789, alarm, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarms = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarms.setRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, recurringAlarm);
}
If you don't want to set a recurring alarm, just change setRepeating to set.
In your code, you need to call:
// to start the receiver at 9:00am
setRecurringAlarm(this, AlarmManagerReceiver.class, 9, 0);
So, you need to create the AlarmManagerReceiver.java:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmManagerReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent alarmService = new Intent(context, AlarmManagerService.class);
context.startService(alarmService);
}
}
And now, you need the service:
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.preference.PreferenceManager;
public class AlarmManagerService extends Service {
private Context context;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
context = this.getApplicationContext();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
// Do what you need to do.
stopSelf();
}
}
In manifest:
<receiver android:name=".AlarmManagerReceiver" >
<intent-filter>
<action android:name=".AlarmManagerReceiver" />
</intent-filter>
</receiver>
<service
android:name=".AlarmManagerService"
android:enabled="true" >
<intent-filter>
<action android:name=".AlarmManagerService" />
</intent-filter>
</service>

Categories