Here i have a code to set the date and time by the user.When the time arrives the notification will pop up.
The problem is that the user have to set the time manually.I want to set it programatically to a specific date, lets say 23 January 2016.So that the user have to just click the set button and forget about other things.
java file of the AlarmReceiiver:-
package com.defcomdevs.invento16;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v7.app.NotificationCompat;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
int notifyId=1;
#Override
public void onReceive(Context context, Intent intent) {
//Toast.makeText(context,"Alarm has been set",Toast.LENGTH_SHORT).show();
/*Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(context, notification);
r.play();*/
NotificationCompat.Builder mNotify=new NotificationCompat.Builder(context);
mNotify.setSmallIcon(R.drawable.index);
mNotify.setContentTitle("Coding");
mNotify.setContentText("INVENTO: Coding competition is going to be conducted today.");
Intent resultIntent=new Intent(context,Coding.class);
TaskStackBuilder stackBuilder=TaskStackBuilder.create(context);
stackBuilder.addParentStack(Coding.class); //add the to-be-displayed activity to the top of stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mNotify.setContentIntent(resultPendingIntent);
NotificationManager notificationManager=(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notifyId,mNotify.build());
}
}
AlarmActivity.java :-
package com.defcomdevs.invento16;
import android.os.Bundle;
import java.util.Calendar;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
public class AlarmActivity extends AppCompatActivity {
private TextView t1,t2,info;
private DatePicker dp;
private TimePicker tp;
private View v1,v2;
private Button b1;
final static int req1=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
b1= (Button) findViewById(R.id.submitalarm);
t1= (TextView) findViewById(R.id.setdate);
t2= (TextView) findViewById(R.id.settime);
tp= (TimePicker) findViewById(R.id.timePicker);
info= (TextView) findViewById(R.id.alarminfo);
dp= (DatePicker) findViewById(R.id.datepicker);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
Calendar now=Calendar.getInstance(); //initialize calendar variable
dp.init(
now.get(Calendar.YEAR),
now.get(Calendar.MONTH),
now.get(Calendar.DAY_OF_MONTH),
null
); //read current day,month & year
//now is a variable,it doesn't mean 'now'
tp.setCurrentHour(now.get(Calendar.HOUR_OF_DAY)); //set current hour
tp.setCurrentMinute(now.get(Calendar.MINUTE)); //set current minute
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Calendar current = Calendar.getInstance(); //initialize an instance of Calendar
Calendar cal = Calendar.getInstance();
cal.set(dp.getYear(),
dp.getMonth(),
dp.getDayOfMonth(),
tp.getCurrentHour(),
tp.getCurrentMinute(),
00); //get current time and date
if (cal.compareTo(current) <= 0) {
Toast.makeText(getApplicationContext(),"Invalid Date/Time.Please Re-enter",Toast.LENGTH_LONG).show();
}
else{
setAlarm(cal);
}
}
});
}
private void setAlarm(Calendar target){
info.setText("\n\n***\n"
+ "Alarm is set# " + target.getTime() + "\n"
+ "***\n");
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), req1, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, target.getTimeInMillis(), pendingIntent);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if(id==android.R.id.home){
Intent intent=new Intent(this,MainActivity.class);
startActivity(intent);
this.finish();
}
return super.onOptionsItemSelected(item);
}
}
How could i do this?please help.Thanks.
This code will set the alarm to 23 January, 2016, 18:05:00. So you don't need TimePicker and DatePicker. See doc here: Calendar
Calendar cal = Calendar.getInstance();
cal.set(2016, 0, 23, 18, 5, 0);
setAlarm(cal);
here is my contribution what i did i haven't tested this but the concept is correct just try it out ...
Calendar calendar = Calendar.getInstance();
calendar.set(2016,MonthSelect("May"),DaySelect("Monday"));
if (SDK_INT < Build.VERSION_CODES.KITKAT) {
alarmMgr.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
}else if (Build.VERSION_CODES.KITKAT <= SDK_INT && SDK_INT < Build.VERSION_CODES.M) {
alarmMgr.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
}
else if (SDK_INT >= Build.VERSION_CODES.M) {
alarmMgr.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
}
.......... then the other functions called..
private int MonthSelect(String mMonth){
if(mMonth=="January"){
return 0;
}else if(mMonth.equalsIgnoreCase("February")){
return 1;
}else if(mMonth.equalsIgnoreCase("March")){
return 2;
}else if(mMonth.equalsIgnoreCase("April")){
return 3;
}else if(mMonth.equalsIgnoreCase("May")){
return 4;
}else if(mMonth.equalsIgnoreCase("June")){
return 5;
}else if(mMonth.equalsIgnoreCase("July")){
return 6;
}else if(mMonth.equalsIgnoreCase("August")){
return 7;
}else if(mMonth.equalsIgnoreCase("September")){
return 8;
}else if(mMonth.equalsIgnoreCase("October")){
return 9;
}else if(mMonth.equalsIgnoreCase("Novermber")){
return 10;
}else {
return 11;
}
}
private int DaySelect(String mDay){
if(mDay.equalsIgnoreCase("Monday")){
return Calendar.MONDAY;
}else if (mDay.equalsIgnoreCase("Tuesday")){
return Calendar.TUESDAY;
}else if (mDay.equalsIgnoreCase("Wednesday")){
return Calendar.WEDNESDAY;
}else if (mDay.equalsIgnoreCase("Thursday")){
return Calendar.THURSDAY;
}else if (mDay.equalsIgnoreCase("Friday")){
return Calendar.FRIDAY;
}else if (mDay.equalsIgnoreCase("Saturday")){
return Calendar.SATURDAY;
}else{
return Calendar.SUNDAY;
}
}
Related
Hi i am currently working on application of reminder in android and using Firebase as database. My reminder is getting set properly without any issue but when i retrieve data from Firebase, i'am getting data of particular date but don't know how to ring it on time that user had entered.
This is my code :
Miscelleneous.java
package com.example.dell.reminder;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.sql.Time;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class Miscelleneous extends Activity {
private static Button setting,resetting;
private EditText text;
private TextView rem1,date1,time1;
private FirebaseDatabase fdb;
private DatabaseReference db5;
private Button btn1,btn2;
private DatePickerDialog.OnDateSetListener dateSetListener;
private TimePickerDialog.OnTimeSetListener timeSetListener;
String strDate;
String timeString = "";
public static final String REM_KEY = "com.example.dell.reminder.REM_KEY";
public static final String DATE_KEY = "com.example.dell.reminder.DATE_KEY";
public static final String TIME_KEY = "com.example.dell.reminder.TIME_KEY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.miscelleneous);
setting = (Button)findViewById(R.id.remset);
Toolbar tool = (Toolbar)findViewById(R.id.setreminder);
text = (EditText)findViewById(R.id.editText);
btn1 = (Button)findViewById(R.id.selectdate);
btn2 = (Button)findViewById(R.id.selecttime);
rem1 = (TextView)findViewById(R.id.rem1);
date1 = (TextView)findViewById(R.id.date1);
time1 = (TextView)findViewById(R.id.time11);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(Miscelleneous.this,
android.R.style.Theme_DeviceDefault_Dialog_MinWidth,dateSetListener,year,month,day);
//dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000);
dialog.show();
}
});
dateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
// Log.d("Miscelleneous","OnDateSet: mm/dd/yyyy" +month + "/" + day + "/" + year);
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
month = month - 1;
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
strDate = format.format(calendar.getTime());
// date = day + "/" + month + "/" + year;
btn1.setText(strDate);
}
};
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar cal = Calendar.getInstance();
int hours = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
//int second = cal.get(Calendar.SECOND);
TimePickerDialog tdialog = new TimePickerDialog(Miscelleneous.this,
android.R.style.Theme_Holo_Light_Dialog,timeSetListener,hours,minute,false);
tdialog.show();
}
});
timeSetListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hours_x, int minute_x) {
//String timeString = "";
if (hours_x == 0) {
timeString = "12:"+minute_x+" "+"a.m.";
btn2.setText(timeString);
} else if (hours_x < 12) {
timeString = hours_x + ":" + minute_x +" "+ "a.m.";
btn2.setText(timeString);
} else if (hours_x == 12) {
timeString = hours_x+":"+minute_x+" "+"p.m.";
btn2.setText(timeString);
} else {
timeString = hours_x-12+ ":" + minute_x +" "+"p.m.";
btn2.setText(timeString);
}
}
};
db5 = FirebaseDatabase.getInstance().getReference().child("user1");
setting.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(text.getText().toString().isEmpty())
Toast.makeText(getApplicationContext(),"Please write something",Toast.LENGTH_LONG).show();
else if(btn1.getText().toString().isEmpty() && btn2.getText().toString().isEmpty()) {
Toast.makeText(getApplicationContext(),"Please select date and time",Toast.LENGTH_LONG).show();
}
else if(btn1.getText().toString().isEmpty()){
Toast.makeText(getApplicationContext(),"Please select date",Toast.LENGTH_LONG).show();
}
else if(btn2.getText().toString().isEmpty()){
Toast.makeText(getApplicationContext(),"Please select time",Toast.LENGTH_LONG).show();
}
else{
final HashMap<String,String> adddata = new HashMap<String, String>();
adddata.put("Reminder",text.getText().toString());
adddata.put("Date",btn1.getText().toString());
adddata.put("Time",btn2.getText().toString());
db5.child("Users Own").setValue(adddata).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),
"Reminder has been set successfully!!!",Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(getApplicationContext(),
"Problem in reminder setting !!",Toast.LENGTH_LONG).show();
}
}
});
retrive();
/*Intent intent = new Intent(Miscelleneous.this,History.class);
intent.putExtra(REM_KEY,validate1);
intent.putExtra(DATE_KEY,validate2);
intent.putExtra(TIME_KEY,validate3);
startActivity(intent);*/
//send();
}
}
});
}
/*private void send(){
final ArrayList<String> arrayList = new ArrayList<>();
arrayList.add(validate1);
arrayList.add(validate2);
arrayList.add(validate3);
Intent i = new Intent(Miscelleneous.this,History.class);
i.putExtra(REM_KEY,arrayList);
startActivity(i);
}*/
private void retrive(){
long current_date = System.currentTimeMillis();
long current_time = System.currentTimeMillis();
// String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat sdf1 = new SimpleDateFormat("hh:mm a");
String System_Date = sdf.format(current_date);
final String System_Time = sdf1.format(current_time);
String usrdate = btn1.getText().toString().trim();
final String usrtime = btn2.getText().toString().toLowerCase().trim();
// Log.d("Miscelleneous",usrtime);
// Log.d("Miscelleneous",usrdate);
if( System_Date.equals(usrdate)){
db5.child("Users Own").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String tim="",date="",remind="";
for (DataSnapshot cdata:dataSnapshot.getChildren()) {
remind = cdata.getValue(String.class).toString();
date = cdata.getValue(String.class).toString();
tim = cdata.getValue(String.class).toString();
}
if(usrtime.equals(System_Time)){
Log.d("Miscelleneous","actual reminder");
Log.d("Miscelleneous","Date:"+remind);
Log.d("Miscelleneous","Reminder:"+date);
Log.d("Miscelleneous","Time:"+tim);
rem1.setText("Reminder : "+remind);
date1.setText("Date : "+date);
time1.setText("Time : "+tim);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Toast.makeText(this,"User date matches with System date",Toast.LENGTH_SHORT).show();
}
else {
//Toast.makeText(this,"User date doesn't matches with System date",Toast.LENGTH_SHORT).show();
}
}
}
Can anyone give me a solution please,
Thanks
you can use AlarmManager to ringing or notify user at particular time.
private AlarmManager alarmManager;
private static Intent alarmIntent;
private static PendingIntent pendingAlarmIntent;
public void setTimings(){
private Calender alarmCalender = Calendar.getInstance();
alarmCalender.setTimeInMillis(System.currentTimeMillis());
alarmCalender.set(Calendar.HOUR_OF_DAY, "hour"); // hour=07
alarmCalender.set(Calendar.MINUTE, "minute"); // minute=01
alarmCalender.set(Calendar.SECOND, "second"); // second=0
alarmCalender.set(Calendar.MILLISECOND, "millisecond");//millisecond=0
setAlarm(AlarmManager.RTC_WAKEUP, alarmCalender, AlarmManager.INTERVAL_DAY);
}
public void setAlarm(int type, Calendar calendar, long timeInMillis){
alarmIntent = new Intent(context, yourBroadcastReciever.class);
pendingAlarmIntent = PendingIntent.getBroadcast(context, Constant.ALARM_REQUEST_CODE, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(type, calendar.getTimeInMillis(), timeInMillis, pendingAlarmIntent);
}
To handle the alarm at particular time you create the Reciever
yourBroadcastReciever.class
#Override
public void onReceive(Context context, Intent intent) {
// here you handle the task when alarm ringing
}
[Note: Intent and Pending Intent is compulsory for create an Alarm]
use a broadcast receiver and set the time which you are getting.
I want to fire a local notification every 24 hours at a specific time say evening 6 o clock
i have refered this code
here
and
here
This is the code i am trying
package com.banane.alarm;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String TAG = "BANANEALARM";
public AlarmManager alarmManager;
Intent alarmIntent;
PendingIntent pendingIntent;
Button bananaButton;
TextView notificationCount;
TextView notificationCountLabel;
int mNotificationCount;
static final String NOTIFICATION_COUNT = "notificationCount";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
// Restore value of members from saved state
mNotificationCount = savedInstanceState.getInt(NOTIFICATION_COUNT);
}
setContentView(R.layout.activity_main);
bananaButton = (Button)findViewById(R.id.bananaButton);
notificationCount = (TextView)findViewById(R.id.notificationCount);
notificationCountLabel = (TextView)findViewById(R.id.notificationCountLabel);
}
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(NOTIFICATION_COUNT, mNotificationCount);
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onNewIntent( Intent intent ) {
Log.i( TAG, "onNewIntent(), intent = " + intent );
if (intent.getExtras() != null)
{
Log.i(TAG, "in onNewIntent = " + intent.getExtras().getString("test"));
}
super.onNewIntent( intent );
setIntent( intent );
}
public void triggerAlarm(View v){
setAlarm();
bananaButton.setVisibility(View.GONE);
notificationCountLabel.setVisibility(View.VISIBLE);
notificationCount.setVisibility(View.VISIBLE);
notificationCount.setText("0");
}
public void setAlarm(){
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast( MainActivity.this, 0, alarmIntent, 0);
Calendar alarmStartTime = Calendar.getInstance();
alarmStartTime.set(Calendar.HOUR, 18); // At the hour you wanna fire
alarmStartTime.set(Calendar.MINUTE, 00); // Particular minute
alarmStartTime.set(Calendar.SECOND, 0);
// alarmStartTime.add(Calendar.MINUTE, 2);
alarmManager.setRepeating(AlarmManager.RTC, alarmStartTime.getTimeInMillis(), getInterval(), pendingIntent);
//Log.i(TAG,"Alarms set every two minutes.");
}
private int getInterval(){
int seconds = 60;
int milliseconds = 1000;
int repeatMS = seconds * 1440 * milliseconds;
return repeatMS;
}
#Override
protected void onStart(){
super.onStart();
updateUI();
}
public void cancelNotifications(){
Log.i(TAG,"All notifications cancelled.");
}
public void updateUI(){
MyAlarm app = (MyAlarm)getApplicationContext();
mNotificationCount = app.getNotificationCount();
notificationCount.setText(Integer.toString(mNotificationCount));
}
#Override
protected void onResume(){
super.onResume();
if(this.getIntent().getExtras() != null){
Log.i(TAG,"extras: " + this.getIntent().getExtras());
updateUI();
}
}
}
when try the code given in the example it works perfectly hwoever when i try to fire a notification i just wont show up what error
I'm making an app in which i need to turn my phone into the vibration mode at the scheduled time.
The problem is that only the second pending intent is executed.
How can I start multiple pending intents?
My code:
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.CheckBox;
import android.widget.Toast;
public class GetSlots extends Activity {
private Calendar mCalendar;
private Calendar nCalendar;
private CheckBox a1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slots);
addenable();
a1 = (CheckBox)findViewById(R.id.checkBox2);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void addenable() {
}
public void getdata(View V) {
mCalendar= Calendar.getInstance();
mCalendar.set(Calendar.HOUR_OF_DAY, 16 );
mCalendar.set(Calendar.MINUTE, 27);
mCalendar.set(Calendar.SECOND, 0);
nCalendar= Calendar.getInstance();
nCalendar.set(Calendar.HOUR_OF_DAY, 16 );
nCalendar.set(Calendar.MINUTE, 29);
nCalendar.set(Calendar.SECOND, 0);
Intent intentAlarm = new Intent();
intentAlarm.setClass(this, AlarmReciever.class);
PendingIntent i = PendingIntent.getBroadcast(this, 0, intentAlarm,
PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent j = PendingIntent.getBroadcast(this, 0, intentAlarm,
PendingIntent.FLAG_UPDATE_CURRENT);
// create the object
AlarmManager mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
if(a1.isChecked()) {
mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(),500*1000, i);
Toast.makeText(this, "Alarm Scheduled", Toast.LENGTH_LONG).show();
mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, nCalendar.getTimeInMillis(), 1000*1000, j);
Toast.makeText(this, "Alarm Scheduled", Toast.LENGTH_LONG).show();
}
if(!a1.isChecked()) {
PendingIntent.getBroadcast(this, 0, intentAlarm,
PendingIntent.FLAG_UPDATE_CURRENT).cancel();
}
}
}
I am new to alarm functionality. I am developing a application of alarm. In which i am able to set the alarm. And when the alarm rings the customize note comes on the pop up window.
My code is :
Main.java
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
public class AlarmMainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.YEAR, 2013);
cal.set(Calendar.DAY_OF_MONTH, 31);
cal.set(Calendar.HOUR_OF_DAY, 17);
cal.set(Calendar.MINUTE, 40);
//Create a new PendingIntent and add it to the AlarmManager
Intent intent = new Intent(this, AlarmReceiverActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,12345, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),pendingIntent);
finish();
}
}
AlarmRecieverActivity.java
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
public class AlarmReceiverActivity extends Activity {
private MediaPlayer mMediaPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alarm);
callStop();
playSound(this, getAlarmUri());
}
private void playSound(Context context, Uri alert) {
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(context, alert);
final AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
} catch (IOException e) {
System.out.println("OOPS");
}
}
//Get an alarm sound. Try for an alarm. If none set, try notification,
//Otherwise, ringtone.
private Uri getAlarmUri() {
Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alert == null) {
alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (alert == null) {
alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
}
return alert;
}
private void callStop(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Medicine Alert");
alertDialogBuilder.setMessage("ABC");
alertDialogBuilder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mMediaPlayer.stop();
finish();
} //end onClick.
}); // end alertDialog.setButton.
alertDialogBuilder.show();
}
}
And the requirement is that: Now i want to set multiple alarms.
The alarm should set for the next 5 to 6 days as the parameter passed.
User can edit alarm, delete alarm and delete all alarms at once.
What changes should i do in code and what should i add more. Please suggest.
Thank you.
Take a look at AlarmManager.setRepeating.
I am trying to update a service from an activity. The Activity saves data to the sql lite database on the phone when the user clicks on a button. What I would like to do here, is when this button is clicked, the service is refreshed and uses the new data.
I was using start/stopservice on the button, but the app crashes and skips around to different activities.
I thought my question was similar to Android: Update / Refresh a running service and
Broadcast Receiver within a Service
However, I'm not updating a widget or another android native component. The service is a custom class.
Please note that a Broadcast receiver starts this service on Boot of the phone.
Also, Logcat window dosen't scroll the readouts. It jerks up and down. So I don't have an error log to show you.
How do I create a function that would allow the service to update when the user clicks on the button in an activity?
Here is my activity (button is at the bottom):
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.joda.time.DateTime;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.google.android.gcm.demo.app.R;
import com.google.android.gcm.demo.app.EventList.DataView;
import com.google.android.gcm.demo.app.EventList.EventDetails;
import com.google.android.gcm.demo.app.sqllite.DatabaseSqlite;
public class AlertDetails extends Activity {
Integer id;
String name;
String date;
String startTime;
String endTime;
String location;
int alertState;
Bundle bundle;
String alertTime;
String s;
private TextView mTitleDisplay;
private TextView mDateDisplay;
private TextView mTimeDisplay;
private TextView mTimeEndDisplay;
private TextView mLocationDisplay;
private TextView mAlertDisplay;
private String update_alarmTime;
String eventYear;
String eventDay;
String eventMonth;
String eventdate;
Context context;
Intent alarmServiceControl;
DatabaseSqlite entry = new DatabaseSqlite(AlertDetails.this);
// Intent startServiceIntent = new Intent(context, AlarmsService.class);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alertview);
bundle = getIntent().getExtras();
id = bundle.getInt("id");
name = bundle.getString("eventName");
date = bundle.getString("date");
startTime = bundle.getString("startTime");
endTime = bundle.getString("endTime");
location = bundle.getString("location");
alertState = bundle.getInt("alertState");
alertTime = bundle.getString("alertTime");
alertTime = "10:00:00";// need to be hooked up correctly to get the right
// capture our View elements
mTitleDisplay = (TextView) findViewById(R.id.titleDisplay);
mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
mTimeEndDisplay = (TextView) findViewById(R.id.timeEndDisplay);
mLocationDisplay = (TextView) findViewById(R.id.locationDisplay);
mAlertDisplay = (TextView) findViewById(R.id.alertDisplay);
// set start
mTimeDisplay.setText(startTime);
mTimeEndDisplay.setText(endTime);
// set title
mTitleDisplay.setText(name);
// set Date
eventYear = date.substring(0, 4);
eventDay = date.substring(5, 7);
eventMonth = date.substring(8, 10);
mDateDisplay.setText(eventDay + "-" + eventMonth + "-" + eventYear);
eventdate = eventDay + "/" + eventMonth + "/" + eventYear;
// set location
mLocationDisplay.setText(location);
if (alertState == 0) {
entry.open();
mAlertDisplay.setText("Alert is ON and Set to " +entry.getAlert(id));
entry.close();
}
if (alertState == 1) {
mAlertDisplay.setText("Alert is OFF");
}
Button button1 = (Button) findViewById(R.id.btnSetAlert);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (alertState == 0) {
alertState++;
mAlertDisplay.setText("Alert is OFF");
entry.open();
entry.updateAlertState(id, alertState);
entry.close();
} else {
//turn alarm on
entry.open();
mAlertDisplay.setText("Alert is ON and Set to " +entry.getAlert(id));
alertState = 0;
entry.updateAlertState(id, alertState);
entry.close();
}
// TODO check if service is running
stopService(new Intent(AlertDetails.this,
AlarmsService.class));
startService(new Intent(AlertDetails.this,
AlarmsService.class));
Intent intent = new Intent(AlertDetails.this,
AlertView.class);
startActivity(intent);
}
});
}
}
Here is the service I'd like to update:
package com.google.android.gcm.demo.app.Alerts;
import java.util.Calendar;
import java.util.List;
import com.google.android.gcm.demo.app.sqllite.DatabaseSqlite;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class AlarmsService extends Service {
DatabaseSqlite db = new DatabaseSqlite(this);
List<Alerts> listAlerts;
PendingIntent pendingIntent;
String tag = "alerttService";
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Created from Alerts service ...",
Toast.LENGTH_LONG).show();
Log.i(tag, "Service created...");
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("TAG", "started onstart command Created from Alerts service .");
return super.onStartCommand(intent, flags, startId);// START_STICKY;
}
#Override
public void onStart(final Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this, "Created from Alerts service started...",
Toast.LENGTH_LONG).show();
Log.i(tag, "Service started. ..");
// for looops
Thread thread = new Thread() {
#Override
public void run() {
Boolean x = true;
while (x) {
db.open();
listAlerts = db.getAlarmsForService();
db.close();
int alerts=listAlerts.size();
for (int i = 0; i < alerts; i++) {
Alerts item = listAlerts.get(i);
item.getRowId();
item.getRemoteServerId();
String alertInMills = item.getAlertDateInMills();
String alertDuration = item.getAlertDurationInMinutes();
String eventName = item.getEventName();
// intent.putExtra("eventState", item.getEventState());
// intent.putExtra("startTime", item.getStartTime());
// intent.putExtra("alertState", item.getAlertState());
// intent.putExtra("eventName", item.getEventName());
// intent.putExtra("location", item.getLocation());
// intent.putExtra("alertTime", item.getAlertTime());
// intent.putExtra("date", item.getDate());
long longAlertInMills = Long.parseLong(alertInMills);
pendingIntent = PendingIntent.getService(AlarmsService.this, 0,intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
// go to data base for time in mills
calendar.setTimeInMillis(longAlertInMills);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
pendingIntent);
//
System.out.println(calendar.toString());
}
//
System.out.println("thread");
x = false;
}
}
};
thread.start();
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
BroadCast Receiver:
package com.google.android.gcm.demo.app.Alerts;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class AlarmsBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "BootReceiver";
Intent startServiceIntent;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
startServiceIntent = new Intent(context, AlarmsService.class);
context.startService(startServiceIntent);
Log.d("TAG", "alarmBroadcastReceiver");
System.out.println("alarm broadcast ...");
}
}
}