Android Studio: how to use putExtra - java

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

Related

Broadcast Receivers can not get new values from new intent and show the previous values

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?

No reminder notification

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?

Android Alarm firing instantly when I set alarm on earlier hour or after midnight [duplicate]

This question already has an answer here:
android prevent immediate trigger of alarm service if alarm time has passed for the day
(1 answer)
Closed 4 years ago.
Im creating my first app in Android Studio. My Alarm Clock is working almost well, but when I will set Alarm to hour earlier than current or after midnight my alarm is firing instantly. For example, current time is 17:00, when I set alarm for 17:05 everything is fine, but when alarm is for 16:00 or 00:05 alarm is firing instantly. I will be thankful for all your advices. Here is my code:
Alarm.java
public class Alarm extends AppCompatActivity {
private TimePicker timePicker;
private Button vibrationButton;
private Button soundButton;
private Button noteButton;
private Button saveButton;
private Button cancelButton;
private CheckBox wifiCheckBox;
private CheckBox soundCheckBox;
private CheckBox bluetoothCheckBox;
private TextView textView;
private BluetoothAdapter mBluetoothAdapter;
private WifiManager wiFi;
private AudioManager audioManager;
private AlarmManager alarmManager;
private PendingIntent pendingIntent;
private NotificationManager notificationManager;
private Intent intent;
private int hour;
private int minute;
private String minuteString;
private String hourString;
private void turnOnWifi() {
if (wifiCheckBox.isChecked())
wiFi.setWifiEnabled(true);
}
private void turnOnBluetooth() {
if (bluetoothCheckBox.isChecked())
mBluetoothAdapter.enable();
}
private void turnOnSound() {
if (soundCheckBox.isChecked())
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
private void notification() {
Intent intentNotification = new Intent(this.getApplicationContext(),Alarm.class);
PendingIntent pendingIntentNotification = PendingIntent.getActivity(this, 0, intentNotification, 0);
Notification notification = new Notification.Builder(this)
.setContentTitle("Alarm")
.setContentText("Next alarm: " + hourString + ":" + minuteString)
.setContentIntent(pendingIntentNotification)
.setAutoCancel(false)
.setSmallIcon(R.mipmap.ic_launcher)
.build();
notificationManager.notify(0, notification);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
timePicker = findViewById(R.id.timePicker);
vibrationButton = findViewById(R.id.vibrationButton);
soundButton = findViewById(R.id.soundButton);
noteButton = findViewById(R.id.noteButton);
saveButton = findViewById(R.id.saveButton);
cancelButton = findViewById(R.id.cancelButton);
wifiCheckBox = findViewById(R.id.wifiCheckBox);
soundCheckBox = findViewById(R.id.soundCheckBox);
bluetoothCheckBox = findViewById(R.id.bluetoothCheckBox);
textView = findViewById(R.id.textView);
wiFi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
intent = new Intent(this, AlarmReceiver.class);
timePicker.setIs24HourView(true);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
if (calendar.before(Calendar.getInstance()))
calendar.add(Calendar.DATE, 1);
if (Build.VERSION.SDK_INT >= 23) {
calendar.set(Calendar.HOUR_OF_DAY, timePicker.getHour());
calendar.set(Calendar.MINUTE, timePicker.getMinute());
calendar.set(Calendar.SECOND, 0);
hour = timePicker.getHour();
minute = timePicker.getMinute();
} else {
calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());
calendar.set(Calendar.SECOND, 0);
hour = timePicker.getCurrentHour();
minute = timePicker.getCurrentMinute();
}
hourString = String.valueOf(hour);
minuteString = String.valueOf(minute);
if (hour == 0)
hourString = "0" + hourString;
if (minute < 10)
minuteString = "0" + minuteString;
textView.setText("Next alarm: " + hourString + ":" + minuteString);
intent.putExtra("extra", "on");
setAlarm(calendar.getTimeInMillis());
// notification();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText("Alarm off!");
alarmManager.cancel(pendingIntent);
intent.putExtra("extra", "off");
sendBroadcast(intent);
// notificationManager.cancel(0);
}
});
}
private void setAlarm(long timeInMillis) {
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);
}
}
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.e("test","test123");
String getState = intent.getExtras().getString("extra");
Log.e("Key is: ", getState);
Intent intentService = new Intent(context, RingtoneService.class);
intentService.putExtra("extra", getState);
context.startService(intentService);
}
}
RingtoneService.java
public class RingtoneService extends Service {
private MediaPlayer mediaPlayer;
boolean isRunning;
int startId;
#Override
public void onDestroy() {
Toast.makeText(this, "on destroy", Toast.LENGTH_SHORT).show();
this.isRunning = false;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
String state = intent.getExtras().getString("extra");
assert state != null;
switch (state) {
case "on":
startId = 1;
break;
case "off":
startId = 0;
break;
default:
startId = 0;
break;
}
if (!this.isRunning && startId == 1){
mediaPlayer = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
mediaPlayer.start();
this.isRunning = true;
this.startId = 0;
}
else if (this.isRunning && startId == 0){
mediaPlayer.stop();
mediaPlayer.reset();
this.isRunning = false;
this.startId = 0;
}
else if (!this.isRunning && startId == 0){
this.isRunning = false;
this.startId = 0;
}
else if (this.isRunning && startId == 1){
this.isRunning = true;
this.startId = 1;
}
return START_NOT_STICKY;
}
}
Of course it does... It's meant to work so.
Android recognizes that the time is past, so it will fire the alarm, even if it's late.
You can make sure that the time set for the alarm is after the current time. Just calculate this difference:
int diff = Calendar.getInstance().getTimeInMilis() - targetCal.getTimeInMillis();
If diff is greater than 0, then add a day to your calendar (targetCal)
Now, your device's time will be earlier (instead of being later) than the next scheduled alarm time.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
if(calendar.before(Calendar.getInstance())) {
calendar.add(Calendar.DATE, 1);
}
alarmManager.set(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), pendingDinnerIntent);

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

Categories

Resources