In my application I want show Toast in Desired date. For this I know I should use AlarmManager.
And for this AlarmManager I find source code from internet.
In this source give time from user with time picker but I want get time static.
I want show Toast in below date :
Date : 2017-10-26
Time : 06:49:59
MainActivity codes:
public class MainActivity extends AppCompatActivity {
//the timepicker object
TimePicker timePicker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getting the timepicker object
timePicker = (TimePicker) findViewById(R.id.timePicker);
//attaching clicklistener on button
findViewById(R.id.buttonAlarm).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//We need a calendar object to get the specified time in millis
//as the alarm manager method takes time in millis to setup the alarm
Calendar calendar = Calendar.getInstance();
if (android.os.Build.VERSION.SDK_INT >= 23) {
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH),
timePicker.getHour(), timePicker.getMinute(), 0);
} else {
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH),
timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0);
}
setAlarm(calendar.getTimeInMillis());
}
});
}
private void setAlarm(long time) {
//getting the alarm manager
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//creating a new intent specifying the broadcast receiver
Intent i = new Intent(this, MyAlarm.class);
//creating a pending intent using the intent
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
//setting the repeating alarm that will be fired every day
am.setRepeating(AlarmManager.RTC, time, AlarmManager.INTERVAL_DAY, pi);
Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show();
}
}
Broadcast codes:
public class MyAlarm extends BroadcastReceiver {
//the method will be fired when the alarm is triggerred
#Override
public void onReceive(Context context, Intent intent) {
//you can check the log that it is fired
//Here we are actually not doing anything
//but you can do any task here that you want to be done at a specific time everyday
Toast.makeText(context, "Alarm just fired", Toast.LENGTH_SHORT).show();
}
}
How can I it? I am amateur, please help me <3
Create a date with your choice and pass it to your method setAlarm()
findViewById(R.id.buttonAlarm).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
String dateInString = "26-10-2017 06:49:59";
long alarmDate = 0L;
try {
Date d = sdf.parse(dateInString);
alarmDate = d.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
}
Try this code
new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minutes) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minutes);
setAlarm(calendar.getTimeInMillis());
}
}, hr1, min1, false).show();
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar calendar = new GregorianCalendar(2017, 10, 26, 6, 49, 59);
setAlarm(calendar.getTimeInMillis());
}
private void setAlarm(long time) {
//getting the alarm manager
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//creating a new intent specifying the broadcast receiver
Intent i = new Intent(this, MyAlarm.class);
//creating a pending intent using the intent
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
//setting the alarm that will be fired once
am.set(AlarmManager.RTC, time, pi);
Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show();
}
}
See GregorianCalendar
Related
I have an alarm aplication, where i want an int to be passed to the Alarm Receiver with an intent, but for some Reason, the AlarmReceiver class does not get the intent. The int gets Enterd by an EditText
here the Variables were created in MainActivity
private int intToPass;
public static final String MyPREFERENCES = "MyPrefs";
private static long intervall = 500;
private String myEnteredText;
private AlarmManager am;
private Intent intent;
private PendingIntent pendingIntent;
here is the code for the set alarm button in MainActivity:
mStartBtn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//Variables
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
long time;
intent = new Intent(MainActivity.this, AlarmReceiverActivity.class);
pendingIntent = PendingIntent.getActivity(MainActivity.this, 2, intent, PendingIntent.FLAG_CANCEL_CURRENT);
am = (AlarmManager) getSystemService(ALARM_SERVICE);
//Save
SharedPreferences prefs = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
myEnteredText = scoreEnter.getText().toString();
SharedPreferences.Editor editor = prefs.edit();
editor.putString("sharedPrefKey", myEnteredText);
editor.apply();
if (((ToggleButton) view).isChecked()) {
try {
intToPass = Integer.parseInt(scoreEnter.getText().toString());
//Calendar
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, timePicker1.getCurrentHour());
calendar.set(Calendar.MINUTE, timePicker1.getCurrentMinute());
//Extra
intent.putExtra("Test", intToPass);
//hour format
time = (calendar.getTimeInMillis() - (calendar.getTimeInMillis() % 60000));
if (System.currentTimeMillis() > time) {
if (calendar.AM_PM == 0)
time = time + (1000 * 60 * 60 * 12);
else
time = time + (1000 * 60 * 60 * 24);
}
//Set alarm
am.setRepeating(AlarmManager.RTC_WAKEUP, time, intervall, pendingIntent);
if (mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(getApplicationContext(), "Alarm Set", Toast.LENGTH_LONG);
mToast.show();
} catch (NumberFormatException nfe) {
mToast = Toast.makeText(MainActivity.this, "Enter number", Toast.LENGTH_LONG);
mToast.show();
((ToggleButton) view).setChecked(false);
}
} else {
if (am!=null){
repam.cancel(pendingIntent);
Toast.makeText(MainActivity.this, "ALARM OFF", Toast.LENGTH_SHORT).show();
}
}
}
});
This is the AlarmReceiver class
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakelock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "wecker:myWakeLog");
mWakelock.acquire();
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON,
WindowManager.LayoutParams.FLAG_FULLSCREEN |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
Intent intent = getIntent();
intToReceive = intent.getIntExtra("Test", 30);
setContentView(alarmView);
}
Thanks for helping.
To send data
intent = new Intent(FROM, TO).putExtras("key","value");
To receive value
String value= getIntent().getStringExtra("key");
please try like this :
startActivity(your intent) when you want to change your activity
I have alarm manager . when user click on add button , user select time , date and fill title and other ... and after this . I save this into database and show this values into recycle view .
I get values and save them into database like this :
saveAlarm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String mTitle = title.getText().toString();
final String mDate = date;
final String mTime = time;
final String mRepeat = getrepeat.getText().toString();
final String mReport = single_choice_selected_report_as;
if (isAnyStringNullOrEmpty(mTitle, mDate, mTime, mRepeat, mReport)) {
Snackbar snackbar = Snackbar.make(mainLayout, "", Snackbar.LENGTH_LONG);
Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) snackbar.getView();
TextView textView = (TextView) layout.findViewById(com.google.android.material.R.id.snackbar_text);
textView.setVisibility(View.INVISIBLE);
View snackView = LayoutInflater.from(SetAlarmActivity.this).inflate(R.layout.custom_toast, null, false);
TextView txtNoticToExit = (TextView) snackView.findViewById(R.id.txtCustomToast);
txtNoticToExit.setText(getResources().getString(R.string.fill_field));
txtNoticToExit.setTypeface(Apps.font);
layout.setPadding(0, 0, 0, 0);
layout.addView(snackView, 0);
snackbar.show();
} else {
if (editMode) {
Alarm alarm = new Alarm(id, mTitle, mDate, mTime, mRepeat, mReport, active);
mDatabase.updateAlarm(alarm);
} else {
Alarm alarm = new Alarm(mTitle, mDate, mTime, mRepeat, mReport, 0);
mDatabase.addAlarm(alarm);
}
Intent intent = new Intent(SetAlarmActivity.this, AlarmActivity.class);
startActivity(intent);
SetAlarmActivity.this.finish();
}
}
In row of my recycle view I have a button to active this item to alarm base on the time .
holder.toggleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int test = alarm.getActive();
state = !state;
if (test == 0) {
holder.toggleButton.setBackgroundResource(R.drawable.on);
holder.row.setBackgroundResource(R.drawable.purple_row);
holder.reminderCalenderRow.setTextColor(context.getResources().getColor(R.color.white));
holder.reminderTitleRow.setTextColor(context.getResources().getColor(R.color.white));
holder.showCalenderRow.setTextColor(context.getResources().getColor(R.color.white));
holder.showTimeRow.setTextColor(context.getResources().getColor(R.color.white));
holder.reminderCalenderRow.setTextColor(context.getResources().getColor(R.color.white));
holder.reminderTimeRow.setTextColor(context.getResources().getColor(R.color.white));
Drawable myDrawable = context.getResources().getDrawable(R.drawable.menu_icon);
holder.popUp_menu.setBackground(myDrawable);
alarm.setActive(1);
String strTime = alarm.getTime();
String[] timeRemoveSpace = strTime.split(" ");
String[] splitTime = timeRemoveSpace[0].split(":");
hour = getHour(strTime);
mintue = Integer.parseInt(splitTime[1]);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, mintue);
calendar.set(Calendar.SECOND, 00);
Long date = calendar.getTimeInMillis();
StartAlarm(alarm.getId(), alarm, date);
} else {
holder.row.setBackgroundResource(R.drawable.white_row);
holder.reminderTitleRow.setTextColor(context.getResources().getColor(R.color.colorBlack));
holder.showCalenderRow.setTextColor(context.getResources().getColor(R.color.colorBlack));
holder.showTimeRow.setTextColor(context.getResources().getColor(R.color.colorBlack));
holder.reminderCalenderRow.setTextColor(context.getResources().getColor(R.color.colorBlack));
holder.reminderTimeRow.setTextColor(context.getResources().getColor(R.color.colorBlack));
Drawable myDrawable = context.getResources().getDrawable(R.drawable.menu_icon_black);
holder.popUp_menu.setBackground(myDrawable);
alarm.setActive(0);
}
mDatabase.updateActive(state, alarm.getId());
notifyDataSetChanged();
}
});
and send intent into broatcast :
public void StartAlarm(int id, Alarm alarm, Long time) {
Intent intent = new Intent(context, MyReceiver.class);
intent.setAction("com.nooshindroid.yastashir");
Bundle bundle = new Bundle();
bundle.putString(EXTRA_TITLE, alarm.getTitle());
bundle.putString(EXTRA_ALARM_DATE, alarm.getDate());
bundle.putString(EXTRA_REPORT, alarm.getReport());
bundle.putString(EXTRA_REPEAT, alarm.getRepeat());
intent.putExtras(bundle);
pendingIntent = PendingIntent.getBroadcast(context, id, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
if ("بدون تکرار".equals(alarm.getRepeat())) {
Log.i("ShowMeTime", "111111");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent);
Toast.makeText(context, "Alarm>kitkat", Toast.LENGTH_SHORT).show();
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
Toast.makeText(context, "Alarm<kitkat", Toast.LENGTH_SHORT).show();
}
} else {
Log.i("ShowMeTime", "222222");
switch (alarm.getRepeat()) {
case "هر ساعت":
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_HOUR, pendingIntent);
break;
case "هر روز":
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_DAY, pendingIntent);
break;
case "هر هفته":
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_DAY * 7, pendingIntent);
break;
case "هر ماه":
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_DAY * 30, pendingIntent);
break;
}
}
}
all thins is ok until I want to edit , Once I edit my values and all these repeat , broad cast show the old values .
this my Receiver :
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//and doing something
if (intent.getAction().equals("com.nooshindroid.yastashir")) {
String title = intent.getExtras().getString(EXTRA_TITLE);
Toast.makeText(context, "Its time!!!", Toast.LENGTH_SHORT).show();
Log.i("khhhhhhhhhhhhhhh", "Started >>>>>>>"+title);
}
}
}
Why this happen ? any help?
Android Target: O and above
I want to create a notification reminder for my application, which will remind the user of the expenses he had done today. I just made a test code to check if the application is giving notification or not but unfortunately its not.
NotifyService Class
public class NotifyService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate(){
Toast.makeText(NotifyService.this, "Startttttttttttttttttttttttttt Alarm", Toast.LENGTH_LONG).show();
NotificationManager mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(), MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent1, 0);
Notification mNotify = new Notification.Builder(this)
.setContentTitle("Log Steps!")
.setContentText("Log your steps for today")
.setSmallIcon(R.drawable.notification_icon)
.setContentIntent(pIntent)
.build();
mNM.notify(1, mNotify);
}
}
NewAccountClass.java
public class NewAccount extends AppCompatActivity {
private DataBaseHelper db = new DataBaseHelper(this);
private EditText user_name, pass_word, re_password;
private TextView submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_account2);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
int i = preferences.getInt("numberoflaunches", 1);
if (i < 2){
alarmMethod();
i++;
editor.putInt("numberoflaunches", i);
editor.commit();
}
initialize();
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pass_word.getText().toString().equals(re_password.getText().toString())) {
DataBaseHelper.writeNewAccountData(db.getWritableDatabase(), user_name.getText().toString(), pass_word.getText().toString());
Toast.makeText(getApplicationContext(), "Account Details Saved !", Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(getApplicationContext(), "Password Doesn't Match", Toast.LENGTH_LONG).show();
//displayNotification(getApplicationContext());
//alarmMethod();
//new NotifyService().onCreate();
}
}
});
}
private void alarmMethod(){
Intent myIntent = new Intent(this , NotifyService.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
calendar.add(Calendar.DAY_OF_MONTH, 1);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 60 * 24, pendingIntent);
Toast.makeText(NewAccount.this, "Start Alarm", Toast.LENGTH_LONG).show();
}
private void initialize() {
user_name = findViewById(R.id.User_Name_New_Account);
pass_word = findViewById(R.id.Password_New_Account);
re_password = findViewById(R.id.Re_Password_New_Account);
submit = findViewById(R.id.Submit_New_Account);
}
}
When I set my time to 11:59 pm I m not getting any notification and also my Toast.makeText(NotifyService.this, "Startttttttttttttttttttttttttt Alarm"..) in notifyservice to create function isn't getting executed only. Any reasons why?
I'm making Alarm Application for Android. I wanna set more alarms using AlarmManager. How can I do it? As far as I know, I need to use PendingIntent with different request code to set some alarms. I was trying to increment a static variable and I did it but if user reload the application the variable has request code as zero. How can I set some alarms even after a reloading my application?
I have one activity
public class NewAlarmActivity extends AppCompatActivity {
private Calendar calendar;
private static int REQUEST_CODE_ALARM = 0;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_alarm);
showTimePickerDialog();
FloatingActionButton floatingActionButton = findViewById(R.id.fb_save_alarm);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveAlarm();
}
});
}
// set time for an alarm
private void showTimePickerDialog() {
calendar = Calendar.getInstance();
TimePickerDialog timePickerDialog = new TimePickerDialog(NewAlarmActivity.this, AlertDialog.THEME_DEVICE_DEFAULT_DARK, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
}
}, Calendar.HOUR_OF_DAY, Calendar.MINUTE, true);
timePickerDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
finish();
}
});
timePickerDialog.show();
}
// get full time like a '05:45'
private String getFullTime(int hour, int minute) {
String h = String.valueOf(hour);
String m = String.valueOf(minute);
if (hour < 10) h = "0" + hour;
if (minute < 10) m = "0" + minute;
return h + ":" + m;
}
private void saveAlarm() {
setAlarm();
insertIntoSQLite();
finish();
}
private void setAlarm() {
Intent intent = new Intent(NewAlarmActivity.this, AlarmReceiver.class);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), ++REQUEST_CODE_ALARM, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
if (alarmManager != null) {
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
}
private void insertIntoSQLite() {
DBHelper dbHelper = new DBHelper(NewAlarmActivity.this);
SQLiteDatabase database = dbHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("time", getFullTime(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE)));
contentValues.put("description", et_description.getText().toString());
database.insert("alarm", null, contentValues);
dbHelper.close();
}
}
You can save small data to sharedPreference.
To save your REQUEST_CODE_ALARM value do this
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putInt("Request_code", REQUEST_CODE_ALARM);
editor.apply()
To retrieve it
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
int Request_code = prefs.getInt("REQUEST_CODE_ALARM", 0); //0 is the default value.
I dont suggest you to use SQL database for this purpose because SharedPreferences are useful for storing user preferences, where there are just a handful of variables that need storing. SQLite on the other hand would be better for storing data where there is a large set of items, such as song titles in a music library which need to be searched through.
Alarm manager will not be exact above api 19.
Try using Workmanager.
I tried to develop a sample Alarm Application. I was searched Google and SC, most of the examples confusing me. I have done with my code, but why it failed to pass the alarm value to the Alarm receiver.
Please help me. Thank you for your concern.
Here is my code.
public class ReminderFragment extends Fragment {
Button buttonstartSetDialog;
TextView txt_time;
Context ctx;
final static int RQS_1 = 1;
public ReminderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_reminder, container, false);
txt_time = (TextView) v.findViewById(R.id.txt_time);
buttonstartSetDialog = (Button) v.findViewById(R.id.startSetDialog);
buttonstartSetDialog.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// textAlarmPrompt.setText("");
showTimePicker();
}
});
return v;
}
private void showTimePicker() {
// DatePickerFragment date = new DatePickerFragment();
TimePickerFragment time = new TimePickerFragment();
Calendar calendar = Calendar.getInstance();
Calendar calSet = (Calendar) calendar.clone();
Bundle args = new Bundle();
args.putInt("hour", calendar.HOUR_OF_DAY);
args.putInt("month", calendar.get(Calendar.MONTH));
args.putInt("minute", calendar.get(Calendar.MINUTE));
time.setArguments(args);
time.setCallBack(ontime);
time.show(getFragmentManager(), "Time Picker");
}
OnTimeSetListener ontime = new OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub
txt_time.setText(String.valueOf(hourOfDay) + ":" + String.valueOf(minute));
Intent intent = new Intent(getActivity(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, txt_time.getTimeInMillis(), pendingIntent);
}
};
}
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
private MediaPlayer mMediaPlayer;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Time is up!!!!.", Toast.LENGTH_LONG).show();
// Vibrate the mobile phone
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
}
}
TimePickerFragment.java
public class TimePickerFragment extends DialogFragment {
OnTimeSetListener onTimeSet;
public TimePickerFragment() {
}
public void setCallBack(OnTimeSetListener ontime) {
onTimeSet = ontime;
}
#SuppressLint("NewApi")
private int hour, minute;
public void setArguments(Bundle args) {
super.setArguments(args);
hour = args.getInt("hour");
minute = args.getInt("minute");
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new TimePickerDialog(getActivity(), onTimeSet, hour, minute, false);
}
}
Pass the values by
intent .putExtra("test", "ValueReceived");
and then in onReceive() get the value by
intent.getStringExtra("test")
Try with
OnTimeSetListener ontime = new OnTimeSetListener()
{
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub
txt_time.setText(String.valueOf(hourOfDay) + ":" + String.valueOf(minute));
Intent intent = new Intent(getActivity(), AlarmReceiver.class);
intent.putExtra("time_value",String.valueOf(hourOfDay) + " : " + String.valueOf(minute));
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager)ctx.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, txt_time.getTimeInMillis(), pendingIntent);
}
};
You need to convert the selected time in long value (milliseconds)
use the below code to do this.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.AM_PM, Calendar.PM); // set AM or PM
long timeInMillis = calendar.getTimeInMillis();
and then pass this value timeInMillis in
alarmManager.set(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);