The first time I worked on broadcast part and run this app, it worked (the alarm went off).
But second time I added cancelAlarm() part and ran it again. It didn't even go off. So I was guessing the previous alarm I had set wasn't removed so the app cant get new input(Alarm) by user.
However I'm not sure. I will really appreciate your feedback. Here's what I have right now.
public class MainActivity extends AppCompatActivity {
Calendar calendar = Calendar.getInstance();
TextView dp0;
AlarmManager alarmManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dp0 = (TextView) findViewById(R.id.tv);
Button sButton = (Button)findViewById(R.id.btn);
sButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new TimePickerDialog(MainActivity.this,android.R.style.Theme_Holo_Light_Dialog,onTimeSetListener,
calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE),true).show();
}
});
}
TimePickerDialog.OnTimeSetListener onTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Toast.makeText(getApplicationContext(), "Set", Toast.LENGTH_SHORT).show();
setAlarm(calendar.getTimeInMillis());
dp0.setText(hourOfDay + ":" + minute);
final Button sButton1 = (Button) findViewById(R.id.cancelbtn);
sButton1.setVisibility(View.VISIBLE);
sButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dp0.setText("");
sButton1.setVisibility(View.INVISIBLE);
cancelAlarm();
}
});
}
};
public void setAlarm(long timeInMillis) {
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this,MyAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,0);
alarmManager.set(AlarmManager.RTC_WAKEUP,timeInMillis,pendingIntent);
}
public void cancelAlarm() {
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent("Myalarm");
PendingIntent sender = PendingIntent.getBroadcast(this,0,intent,0);
alarmManager.cancel(sender);
sender.cancel();
Toast.makeText(getApplicationContext(),"Canceled",Toast.LENGTH_SHORT).show();
}
}
And the BroadcastReceiver:
public class MyAlarm extends BroadcastReceiver {
MediaPlayer mediaPlayer;
#Override
public void onReceive(Context context, Intent intent) {
mediaPlayer = MediaPlayer.create(context, Settings.System.DEFAULT_RINGTONE_URI);
mediaPlayer.start();
}
}
I think you need to use PendingIntent.FLAG_UPDATE_CURRENT. Moreover, I would like to recommend some changes in your code.
For setting the alarm change your function setAlarm() like this.
public void setAlarm(long timeInMillis) {
Intent myIntent = new Intent(getApplicationContext(), MyAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getApplicationContext(), 1, myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, timeInMillis, pendingIntent);
}
And for cancelling, the cancelAlarm() should look like.
public void cancelAlarm() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent myIntent = new Intent(getApplicationContext(), MyAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getApplicationContext(), 1, myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(pendingIntent);
}
You might consider taking the onClickListener of sButton1 out of the function onTimeSet. Move the click listener to onCreate function.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dp0 = (TextView) findViewById(R.id.tv);
Button sButton = (Button)findViewById(R.id.btn);
Button sButton1 = (Button)findViewById(R.id.cancelbtn);
sButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new TimePickerDialog(MainActivity.this,android.R.style.Theme_Holo_Light_Dialog,onTimeSetListener,
calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE),true).show();
}
});
sButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dp0.setText("");
sButton1.setVisibility(View.INVISIBLE);
cancelAlarm();
}
});
}
TimePickerDialog.OnTimeSetListener onTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Toast.makeText(getApplicationContext(), "Set", Toast.LENGTH_SHORT).show();
setAlarm(calendar.getTimeInMillis());
dp0.setText(hourOfDay + ":" + minute);
sButton1.setVisibility(View.VISIBLE);
}
};
Related
I am working on alarm with android and broadcast receiver. Setting up and playing an alarm works but I cannot turn off the alarm. I have two button for set alarm and stop alarm .My codes is here;
public class MainActivity extends AppCompatActivity {
Button btn;
private Button startAlarmBtn;
private TimePickerDialog timePickerDialog;
final static int REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button cancel;
startAlarmBtn = (Button) findViewById(R.id.startAlarmBtn);
startAlarmBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openPickerDialog(false);
}
});
cancel=(Button)findViewById(R.id.cancel);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopAlarm();
}
});
}
private void openPickerDialog(boolean is24hour) {
Calendar calendar = Calendar.getInstance();
timePickerDialog = new TimePickerDialog(
MainActivity.this,
onTimeSetListener,
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
is24hour);
timePickerDialog.setTitle("Alarm Ayarla");
timePickerDialog.show();
}
TimePickerDialog.OnTimeSetListener onTimeSetListener
= new TimePickerDialog.OnTimeSetListener(){
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar calNow = Calendar.getInstance();
Calendar calSet = (Calendar) calNow.clone();
calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
calSet.set(Calendar.MINUTE, minute);
calSet.set(Calendar.SECOND, 0);
calSet.set(Calendar.MILLISECOND, 0);
if(calSet.compareTo(calNow) <= 0){
calSet.add(Calendar.DATE, 1);
}
setAlarm(calSet);
}};
private void setAlarm(Calendar alarmCalender){
Toast.makeText(getApplicationContext(),"Alarm OK!",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), REQUEST_CODE, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, alarmCalender.getTimeInMillis(), pendingIntent);
}
private void stopAlarm(){
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), REQUEST_CODE,
new Intent(getApplicationContext(), AlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
pendingIntent.cancel();
}
}
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null)
{
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
}
}
How do I turn off the alarm?
My other question is, is it appropriate to have them in the main thread?
Should I use AsyncTask or multi-threading?
Thank you.
The alarm is not stopping because you don't have a handle to the ringtone instance you are playing.
I suggest you add a timer to auto stop the ringtone, or you create a global instance of the ringtone, which on second thought might be a bad idea, because if you forget to clean up, it may leak and cause other problems.
A simple approach to timing this is as shown below:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null)
{
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
new CountDownTimer(30000, 1000) { // a timer for 30 seconds, that updates approximately every second
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
// stop your ringtone here, or do other necessary stuff here
// you might want to check if the ringtone was not stopped before this method
}
}.start();
}
}
In response to your second question, you could as well use a thread with a handler or runnable to manage the ringtone accordingly. An AsyncTask may be too much work for something relatively simple.
I'm making an alarm app that goes off at exact given time by user.
Since Doze mode has come out, I heard I need to use setExactAndAllowWhileIdle() on
API 23 or higher.(I'm targeting on API 26).
But the problem is Whenever I set the alarm, it goes off(only toast message at this moment) 3 seconds later no matter what. I have no idea why.
Any type of feedback will be greatly appreciated.
Note: I already registered BroadcastReceiver on Manifest.xml
public class MainActivity extends AppCompatActivity {
static final String CP ="checkpi";
MediaPlayer mp;
Calendar c= Calendar.getInstance();
TimePickerDialog.OnTimeSetListener otsl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = (TextView)findViewById(R.id.tv);
Button testbtn = (Button)findViewById(R.id.test);
testbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new TimePickerDialog(MainActivity.this,android.R.style.Theme_Holo_Light_Dialog,otsl,
c.get(Calendar.HOUR_OF_DAY),c.get(Calendar.MINUTE),true).show();
}
});
otsl = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
textView.setText(hourOfDay+":"+minute);
//c.set(Calendar.HOUR_OF_DAY,hourOfDay);
//c.set(Calendar.MINUTE,minute);
setAlarm(c.getTimeInMillis());
}
};
Button canceltestbtn = (Button)findViewById(R.id.canceltest);
canceltestbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!textView.equals("")){
textView.setText("");
}
cancelAlarm();
}
});
}
public void setAlarm(long timeinmils) {
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent i = new Intent(MainActivity.this,Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);
am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,timeinmils,pi);
}
public void cancelAlarm() {
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent i = new Intent(MainActivity.this,Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);
am.cancel(pi);
pi.cancel();
if(pi==null){
Log.v(CP,"Pendingintent==null");
}
else{
Log.v(CP,"Pendingintent!=null");
}
}
}
// ---------------------------------------------
public class Alarm extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"Wake up!!",Toast.LENGTH_SHORT).show();
}
}
Explanation:
I had created a calendar in my application.Which provides the functionality like add and delete event on the particular day of the month.
This event is saved in my SQLite database and display from the db.Whatever, i explained almost things i did.
What i want?
Suppose, i added an event of birthday of my friend on 14th dec in 2016.So, this event will fired at the time when my friend birthday will arrive.
I want to fired that event on particular day like alarm.
Here is my calendar code
public class CalendarFragment extends Fragment{
View rootView;
String str_date="";
String month="";
String year="";
ListView event_list;
String parts[];
String monthYear="";
String monthAyear="";
private SimpleDateFormat dateFormatForMonth = new SimpleDateFormat("MMM - yyyy", Locale.getDefault());
EventAdapter adapter=null;
DatabaseHandler db=null;
List<Event> list_data;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView=inflater.inflate(R.layout.fragment_calendar, container, false);
event_list=(ListView)rootView.findViewById(R.id.event_listview);
final ImageButton showPreviousMonthBut = (ImageButton) rootView.findViewById(R.id.prev_button);
final ImageButton showNextMonthBut = (ImageButton) rootView.findViewById(R.id.next_button);
db=new DatabaseHandler(getContext());
final TextView year_name=(TextView)rootView.findViewById(R.id.year_name);
final CompactCalendarView compactCalendarView = (CompactCalendarView) rootView.findViewById(R.id.compactcalendar_view);
compactCalendarView.drawSmallIndicatorForEvents(true);
compactCalendarView.setCurrentDayBackgroundColor(getResources().getColor(R.color.black));
compactCalendarView.setCurrentSelectedDayBackgroundColor(getResources().getColor(R.color.dark_red));
compactCalendarView.invalidate();
year_name.setText(dateFormatForMonth.format(compactCalendarView.getFirstDayOfCurrentMonth()));
monthYear=dateFormatForMonth.format(compactCalendarView.getFirstDayOfCurrentMonth());
parts=monthYear.split("-");
month=parts[0].replace(" ","");
year=parts[1].replace(" ","");
monthAyear=month+"-"+year;
list_data=db.getAllEvents();
showData(monthAyear);
compactCalendarView.setListener(new CompactCalendarView.CompactCalendarViewListener() {
#Override
public void onDayClick(Date dateClicked) {
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd-MMM-yyyy");
str_date=simpleDateFormat.format(dateClicked);
dialogShow();
}
#Override
public void onMonthScroll(Date firstDayOfNewMonth) {
monthYear=dateFormatForMonth.format(firstDayOfNewMonth);
parts=monthYear.split("-");
month=parts[0].replace(" ","");
year=parts[1].replace(" ","");
monthAyear=month+"-"+year;
showData(monthAyear);
year_name.setText(dateFormatForMonth.format(firstDayOfNewMonth));
}
});
showPreviousMonthBut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
compactCalendarView.showPreviousMonth();
}
});
showNextMonthBut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
compactCalendarView.showNextMonth();
}
});
//
return rootView;
}
public void dialogShow(){
final Dialog dialog=new Dialog(getContext());
dialog.setContentView(R.layout.dialog_layout);
dialog.setTitle("Add Event");
final TextView event_name=(TextView)dialog.findViewById(R.id.event_name);
final TextView event_desc=(TextView)dialog.findViewById(R.id.event_description);
final TextView event_date=(TextView)dialog.findViewById(R.id.event_date);
event_date.setText(str_date);
Button btn_save=(Button)dialog.findViewById(R.id.btn_save);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.addEvent(new Event(event_name.getText().toString(),event_desc.getText().toString(),event_date.getText().toString(),monthAyear));
dialog.hide();
Toast.makeText(getContext(), "Event added successfully....", Toast.LENGTH_SHORT).show();
showData(monthAyear);
}
});
dialog.show();
}
public void showData(String monthWyear){
List<Event> list_data=db.getEvent(monthWyear);
adapter=new EventAdapter(getActivity(),list_data);
event_list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.findItem(R.id.spinner).setVisible(false);
super.onCreateOptionsMenu(menu, inflater);
}
}
Please, help me What will i do?
You need to use the AlarmManager Class to notify the user through Push Notifications:
So, to get this working, you need to pass the time in milliseconds which represents your target date e.g : 24 Dec 2016 -> Convert to milliseconds and pass it to the AlaramManager
private Calendar calendar;
calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.DAY_OF_MONTH, day);
delay = calendar.getTimeInMillis();
public class SetUpNotification {
public void setAlarm(long delay, String taskName, String taskDetails, Context context)
{
Intent alertIntent = new Intent(context, AlertReceiver.class);
alertIntent.putExtra("TaskName", taskName);
alertIntent.putExtra("TaskDetails", taskDetails);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
final int _id = (int) System.currentTimeMillis();
Log.d("Delay", delay+"");
Log.d("ID", _id+"");
alarmManager.set(AlarmManager.RTC_WAKEUP, delay,
PendingIntent.getBroadcast(context, _id, alertIntent,
PendingIntent.FLAG_UPDATE_CURRENT));
}
}
public class AlertReceiver extends BroadcastReceiver {
static int x = 0;
#Override
public void onReceive(Context context, Intent intent) {
String taskName = intent.getStringExtra("TaskName");
String taskDetails = intent.getStringExtra("TaskDetails");
Log.d("BroadcastReceiver", "OnRecieve");
createNotification(context, taskName , taskDetails, "EatThatFrog");
x++;
Log.d("X", x+"");
}
public void createNotification(Context context, String msg, String msgText, String msgAlert){
PendingIntent notificIntent = PendingIntent.getActivity(context, 0,
new Intent(context, DashboardActivity.class), 0);
NotificationCompat.Builder mBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(msg)
.setTicker(msgAlert)
.setContentText(msgText);
mBuilder.setContentIntent(notificIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1 + x, mBuilder.build());
}
}
You can alarm manager class and put your broadcast receiver to handle that event and for showing event in dialog you can make dialog as an activity which shows your event detail from database
For putting alarm
public void setAlarm(View v){
Intent intent = new Intent(this,AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+ Delay,pendingIntent);
}
in broad cast receiver
public void onReceive(Context ctxt, Intent intent) {
Intent i=new Intent(ctxt, EventActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctxt.startActivity(i);
}
I am trying to make a simple android alarm app that basically take the time from the user and set an alarm every day in that time
i am using alarmmanger , the app runs fine with no errors but the alarm doesn't work !!
here is the where the user set the time
buttonSet.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("syso","1");
String sTime = eReminderTimeAM.getText().toString();
String aTime[] = sTime.split(":");
Log.i("syso","2");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(aTime[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt(aTime[1]));
Log.i("syso",aTime[1]);
alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent( getBaseContext(), Alarm.class);
alarmIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
Log.i("syso","3");
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
}
});
and here is the other activity that should run
MediaPlayer mp=null ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_alarm);
Button stopAlarm = (Button) findViewById(R.id.stopAlarm);
mp = MediaPlayer.create(getBaseContext(),R.raw.toha);
stopAlarm.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
mp.stop();
finish();
return false;
}
});
playSound(this, getAlarmUri());
}
private void playSound(final Context context, Uri alert) {
Thread background = new Thread(new Runnable() {
public void run() {
try {
mp.start();
} catch (Throwable t) {
Log.i("Animation", "Thread exception "+t);
}
}
});
background.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
mp.stop();
}
Is "Alarm.class" a "BroadcastReceiver"? else please create a "BroadcastReceiver" and onReceive method of "BroadcastReceiver" call activity
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
}
}
Don't forget to add receiver to your Manifest
You have to add the receive class
public class Alarm extends BroadcastReceiver {
private Context context;
#Override
public void onReceive(Context context1, Intent intent) {
context = context1;
}
}
in android manifest also declare the receiver
<receiver android:name="Alarm" >
it was a silly mistake at the end ..
just had to replace PendingIntent.getBroadcast to PendingIntent.getActivity and it worked fine
Hi want to play alarm in my app,so i tried using below code using services when i click start button alarm is playing..but what i want is,same activity i have two editexts in first i have give time 9,and second edittext i have given time 10,so i have to show notification only in 9 and 10 pm only...any one give me some idea.
public class DonnsAlarm extends Activity {
/** Called when the activity is first created. */
EditText e1,e2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
e1=(EditText)findViewById(R.id.editText1);
e2=(EditText)findViewById(R.id.editText2);
// click listener for the button to start service
Button btnStart = (Button) findViewById(R.id.button1);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s1=e1.getText().toString();
String s2=e2.getText().toString();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(s1));
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(DonnsAlarm.this, Service_class.class);
PendingIntent pintent = PendingIntent.getService(DonnsAlarm.this, 0, intent,
0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
36000 * 1000, pintent);
PendingIntent pintent1 = PendingIntent.getService(DonnsAlarm.this, 1, intent,
0);
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(s2));
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
36000 * 1000, pintent1);
}
});
// click listener for the button to stop service
Button btnStop = (Button) findViewById(R.id.button2);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), Service_class.class));
}
});
}
}
public class Service_class extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
Intent notifyIntent = new Intent(Intent.ACTION_MAIN);
notifyIntent.setClass(getApplicationContext(), DonnsAlarm.class);
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from ="It's Time to Play VocCards!";
CharSequence message = "It's Time to Play VocCards!";
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notifyIntent, 0);
Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show();
Notification notif = new Notification(R.drawable.ic_launcher,
"It's Time to Play VocCards!", System.currentTimeMillis());
notif.setLatestEventInfo(this, from, message, contentIntent);
nm.notify(1, notif);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
}
I see your problem is giving the values of EditTexts to service so service knows which hours to play the alarm. You can put the values of EditText to a bundle (or intent's extras) and start the service using that intent which contains data about the hours.
In your Activity use:
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s1=e1.getText().toString();
String s2=e2.getText().toString();
Intent intent = new Intent(getBaseContext(), Service_class.class);
intent.putExtra("value1", s1);
intent.putExtra("value2", s2);
startService(intent);
}
});
Than in your Service's onStartCommand method use this:
String val1 = intent.getExtra("value1");
String val2 = intent.getExtra("value2");
And now you have the values in your service!
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s1=e1.getText().toString();
String s2=e2.getText().toString();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(s1));
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(DonnsAlarm.this, Service_class.class);
PendingIntent pintent = PendingIntent.getService(DonnsAlarm.this, 0, intent,
0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
36000 * 1000, pintent);
PendingIntent pintent1 = PendingIntent.getService(DonnsAlarm.this, 1, intent,
0);
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(s2));
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
36000 * 1000, pintent1);
}
});
The above code sets the two alarm one according to the value in 1st edittext and one according to the other