Set multiple Alarms with multiple dates from a ArrayList - java

In my Application i need to Start after Reboot all the Alarms that i have set befor by using the dates in my Arraylist class that i have saved by sharedprefs. But only the one is set by the Alarmmanager. I used a BroadcastReciver and a for loop.
ArrayList<DateList1> dateses;
Date dateFromLog;
#Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences = context.getSharedPreferences("The Selected date", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("Date0list", null);
Type type = new TypeToken<ArrayList<DateList1>>() {
}.getType();
dateses = gson.fromJson(json, type);
if (dateses == null) {
dateses = new ArrayList<>();
}
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent>();
Calendar calendar = Calendar.getInstance();
for (int i = 0; i<dateses.size(); i++){
calendar.setTime(dateses.get(i).getDate1());
Intent intent1 = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, i, intent1, PendingIntent.FLAG_ONE_SHOT);
alarmManager.setExact(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);
intentArray.add(pendingIntent);
}
}
}
And here is how i add the Date to the Arraylist
ArrayList<DateList1> Dates = new ArrayList<>();
#Override
protected void onCreate(Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
setContentView(R.layout.data_picker);
einfüGGen = (Button) findViewById(R.id.button3);
datums = (EditText) findViewById(R.id.datums);
fachs = (EditText) findViewById(R.id.fachs);
themens = (EditText) findViewById(R.id.themens);
GG = (TextView) findViewById((R.id.textView));
einfüGGen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent resultIntent = new Intent();
resultIntent.putExtra("datum", datums.getText().toString());
resultIntent.putExtra("fach", fachs.getText().toString());
resultIntent.putExtra("themen", themens.getText().toString());
setResult(RESULT_OK, resultIntent);
finish();
int y = Dates.size();
for (int i = 0; i<Dates.size(); i++){
Toast.makeText(EingabeFeld.this,"SOOOOSSS"+y,Toast.LENGTH_LONG).show();
}
}
});
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Toast.makeText(EingabeFeld.this, "Die Erinnerung wurde festgelegt für den "+dayOfMonth+"/"+month+"/"+year, Toast.LENGTH_SHORT).show();
Calendar c = Calendar.getInstance();
c.set(year,month,dayOfMonth);
c.set(Calendar.HOUR_OF_DAY,15);
c.set(Calendar.MINUTE,20);
c.set(Calendar.SECOND,0);
Date date = c.getTime();
Dates.add(1,new DateList1(date));
startAlarm(c);
saveData();
Here is the actual class for the arraylist
public Date date1;
public DateList1(Date date){
date1 = date;
}
public Date getDate1() {
return date1;
}
}
I Hope this is going to see Someone and Thanks in Advance

I have Solved it :D.
I did the adding to the ArrayList and the saving part in my MainActivity,and got the long by the startActivityForResult Method to my MainActivity from my SecondActivity.
Thanks for those who tried to help me,i really like you guys and have a nice day with errorless Code ;D

Related

How to set some alarms using AlarmManager?

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.

How to show Toast in Desired date with AlarmManager on Android

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

how to set alarm scheduling with notification in android?

I have a problem with my code. i first create an alarm with a notification,Then I set the alarm for the following times - 6AM, 12PM and 6PM. However when I run the application, the alarm is always on,and does not go on at 6AM, 12PM and 6PM. The notifications are also not on time. Im using toggle button.
My code :
AlarmFragmen.java`
public class AlarmFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private PendingIntent pendingIntent;
private TextView textViewEnamPagi, textViewDuabelas, textViewenamSore, textResult;
private ToggleButton toggleButtonEnamPagi, toggleButtonDuaBelas, toggleButtonEnamSore;
public AlarmFragment() {
}
public static AlarmFragment newInstance(String param1, String param2) {
AlarmFragment fragment = new AlarmFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_alarm, container, false);
toggleButtonEnamPagi = (ToggleButton) v.findViewById(R.id.toggleButton);
textViewEnamPagi = (TextView) v.findViewById(R.id.textViewEnamPagi);
textViewDuabelas = (TextView) v.findViewById(R.id.textView);
textViewenamSore = (TextView) v.findViewById(R.id.textEnamSore);
toggleButtonDuaBelas = (ToggleButton) v.findViewById(R.id.toggleButton2);
toggleButtonEnamSore = (ToggleButton) v.findViewById(R.id.toggleEnamSore);
textViewEnamPagi.setText("OFF Pukul 06.00 AM");
textViewDuabelas.setText("OFF Pukul 12.00 PM");
textViewenamSore.setText("OFF Pukul 18.00 PM");
startSix();
startDuaBelas();
startEnamSore();
toggleButtonEnamPagi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(toggleButtonEnamPagi.isChecked()){
textViewEnamPagi.setText("ON Pukul 06.00 AM");
SharedPreferences preferences = getActivity().getPreferences(1);
SharedPreferences.Editor edt = preferences.edit();
edt.putBoolean("tgEnam", true);
edt.commit();
}else {
textViewEnamPagi.setText("OFF Pukul 06.00 AM");
SharedPreferences preferences = getActivity().getPreferences(1);
SharedPreferences.Editor edt = preferences.edit();
edt.putBoolean("tgEnam", false);
edt.commit();
}
}
});
toggleButtonDuaBelas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(toggleButtonDuaBelas.isChecked()){
textViewDuabelas.setText("ON Pukul 12.00 PM");
SharedPreferences preferences = getActivity().getPreferences(0);
SharedPreferences.Editor edt = preferences.edit();
edt.putBoolean("tgDuabelas", true);
edt.commit();
}else{
textViewDuabelas.setText("OFF Pukul 12.00 PM");
SharedPreferences preferences = getActivity().getPreferences(0);
SharedPreferences.Editor edt = preferences.edit();
edt.putBoolean("tgDuabelas", false);
edt.commit();
}
}
});
toggleButtonEnamSore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(toggleButtonEnamSore.isChecked()){
SharedPreferences preferences = getActivity().getPreferences(0);
SharedPreferences.Editor edt = preferences.edit();
edt.putBoolean("tgEnamsore", true);
edt.commit();
}else{
SharedPreferences preferences = getActivity().getPreferences(0);
SharedPreferences.Editor edt = preferences.edit();
edt.putBoolean("tgEnamsore", false);
edt.commit();
}
}
});
return v;
}
public void startSix(){
SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean tgenam = preferences.getBoolean("tgEnam", true);
if(tgenam == true){
textViewEnamPagi.setText("ON Pukul 06.00 AM");
toggleButtonEnamPagi.setChecked(true);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 6);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date date = calendar.getTime();
Intent myIntent = new Intent(getActivity().getApplication(), MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getActivity().getApplication(), 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, date.getTime(), pendingIntent);
}
}
public void startDuaBelas() {
SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean tgduabelas = preferences.getBoolean("tgDuabelas", true);
if (tgduabelas == true) {
textViewDuabelas.setText("ON Pukul 12.00 PM");
toggleButtonDuaBelas.setChecked(true);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date date = calendar.getTime();
Intent myIntent = new Intent(getActivity().getApplication(), MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getActivity().getApplication(), 1, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, date.getTime(), pendingIntent);
}
}
public void startEnamSore() {
SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean tgenamsore = preferences.getBoolean("tgEnamsore", true);
if (tgenamsore == true) {
textViewenamSore.setText("ON Pukul 18.00 PM");
toggleButtonEnamSore.setChecked(true);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 18);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date date = calendar.getTime();
Intent myIntent = new Intent(getActivity().getApplication(), MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getActivity().getApplication(), 2, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, date.getTime(), pendingIntent);
}
}
And MyReceiver.java
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent service1 = new Intent(context, AlarmFragment.class);
service1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(service1);
Intent myIntent = new Intent(context, MyAlarmService.class);
context.startService(myIntent);
}
AlarmService.java
public class MyAlarmService extends Service{
NotificationManager manager;
Notification myNotication;
private NotificationManager mManager;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_CANCEL_CURRENT);
Notification.Builder builder = new Notification.Builder(MyAlarmService.this);
builder.getNotification().flags = Notification.FLAG_AUTO_CANCEL;
builder.setAutoCancel(true);
builder.setTicker("this is ticker text");
builder.setContentTitle("Alarm ON");
builder.setContentText("Wake UP");
builder.setSmallIcon(R.drawable.image);
builder.setContentIntent(pendingIntent);
//builder.setOngoing(true);
builder.setSubText("Time to code"); //API level 16
builder.setNumber(1);
builder.build();
builder.setVibrate(new long[]{1000,1000,1000,1000,1000});
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.song);
builder.setSound(uri);
myNotication = builder.getNotification();
manager.notify(0, myNotication);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
Please help me to solve my problem, thx

how to get date from datepicker to another activity in android

I'm very new to Android Studio and I am building a simple countdown timer app. I have 2 activities. The first activity(Login) the user picks a date through date picker, the second activity(Profile) shows a countdown timer. The countdown timer works perfectly when I set a date for it in the java class, but i'm having trouble trying to retrieve the date from the login activity. My code for both activities is below.
I know I have to alter the Date futureDate = dateFormat.parse("2016-8-10"); but I'm not sure how.
LOGIN.CLASS
public class Login extends AppCompatActivity implements DatePickerDialog.OnDateSetListener, OnClickListener {
//private SharedPreferences sp;
EditText enterusername;
Button continuetoprofile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
/*sp = getSharedPreferences("myPreference" , Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("myKey" , "I am data to store");
editor.commit();
Writing data to SharedPreferences*/
enterusername = (EditText) findViewById(R.id.enterusername);
continuetoprofile=(Button) findViewById(R.id.continuetoprofile);
continuetoprofile.setOnClickListener(this);
}
//SHARED PREFERENCES
/*public void saveInfo(View view){
SharedPreferences save = getSharedPreferences("name", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = save.edit();
editor.putString("username",enterusername.getText().toString());
editor.apply();
}*/
public void onClick (View v){
Intent intent = new Intent(this,Profile.class);
intent.putExtra("username", enterusername.getText().toString());
startActivity(intent);
}
public void datePicker(View view){
DatePickerFragment fragment = new DatePickerFragment();
fragment.show(getSupportFragmentManager(), "date");
}
private void setDate(final Calendar calendar) {
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
((TextView) findViewById(R.id.showDate)).setText(dateFormat.format(calendar.getTime()));
}
public void onDateSet(DatePicker view, int year, int month, int day) {
Calendar cal = new GregorianCalendar(year, month, day);
setDate(cal);
}
public static class DatePickerFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(),
(DatePickerDialog.OnDateSetListener)
getActivity(), year, month, day);
}
}
Intent intent = getIntent();
public void privPol(View view){
Intent intent = new Intent(this, PrivacyPolicy.class);
startActivity(intent);
}
public void TOU(View view){
Intent intent = new Intent(this, TermsOfUse.class);
startActivity(intent);
}
public void toProfile(View view){
Intent intent = new Intent(this, Profile.class);
startActivity(intent);
}
PROFILE.CLASS
public class Profile extends AppCompatActivity {
//private SharedPreferences spref;
//TextView nameofuser;
TextView nameofuser;
private TextView daystxt, hourstxt, minutestxt, secondstxt;
private Handler handler;
private Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
initUI();
countDownStart();
nameofuser = (TextView)findViewById(R.id.nameofuser);
Intent intent = getIntent();
String username = intent.getStringExtra("username");
nameofuser.setText("Welcome, " + username);
}
#SuppressLint("SimpleDateFormat")
private void initUI() {
daystxt = (TextView) findViewById(R.id.days);
hourstxt = (TextView) findViewById(R.id.hours);
minutestxt = (TextView) findViewById(R.id.minutes);
secondstxt = (TextView) findViewById(R.id.seconds);
}
public void countDownStart() {
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
handler.postDelayed(this, 1000);
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// Here Set your Event Date
Date futureDate = dateFormat.("2016-8-10");
Date currentDate = new Date();
if (!currentDate.after(futureDate)) {
long diff = futureDate.getTime()
- currentDate.getTime();
long days = diff / (24 * 60 * 60 * 1000);
diff -= days * (24 * 60 * 60 * 1000);
long hours = diff / (60 * 60 * 1000);
diff -= hours * (60 * 60 * 1000);
long minutes = diff / (60 * 1000);
diff -= minutes * (60 * 1000);
long seconds = diff / 1000;
daystxt.setText("" + String.format("%02d", days));
hourstxt.setText("" + String.format("%02d", hours));
minutestxt.setText("" + String.format("%02d", minutes));
secondstxt.setText("" + String.format("%02d", seconds));
} else {
handler.removeCallbacks(runnable);
// handler.removeMessages(0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
handler.postDelayed(runnable, 0);
}
Intent intent = getIntent();
public void toMenu(View view) {
Intent intent = new Intent(this, Menu.class);
startActivity(intent);
}
public void tostartdate(View view) {
Intent intent = new Intent(this, EditStartdate.class);
startActivity(intent);
}
//Get the date
Date buttonDate = SimpleDateFormat.getDateInstance().parse(mDate.getText().toString());
and
//Create a bundle to pass the date and send your date as Long
Bundle currentDate = new Bundle();
currentDate.putLong("setDate", buttonDate.getTime());
and
//Read the passed bundle from the next activity get Long and convert it to Date
Bundle setDate = this.getArguments();
Long currDate = setDate.getLong("setDate");
Note :
The Date constructor accepts the time as long in milliseconds, not seconds. You need to multiply it by 1000 and make sure that you supply it as long.
conversion
Date d = new Date(1220227200L * 1000);
Try using the putExtras() method to pass it through the Intent in a Bundle.
The following code will help out:
Sending Data through Bundle
Intent i = new Intent(this, ActivityTwo.class);
Bundle bundle = new Bundle();
bundle.putExtras("Date",YOUR_DATE);
i.putExtras(bundle);
startActivity(i);
Getting Data in new Activity
Bundle bundle = getIntent().getExtras();
String date = bundle.getString(“Date”);
This will help

How to pass the Alarm value to Alarm Receiver

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

Categories

Resources