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?
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?
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
I set an alarm and i want to disable the ongoing alarm using notification action button without opening the activity.
I have attached my whole code below.
When user set alarm it call the broadcast receiver and from them i call my ringtone service to start ringtone. and it will fire a notification. in that notification it will have a disable button. i have done all the resource i had found on internet. but
disable button on notification didn't work. where is my fault
onToggled button to start alarm from main activity
public void OnToggleClicked(View view) {
long time;
if (((ToggleButton) view).isChecked()) {
Toast.makeText(MainActivity.this, "ALARM ON", Toast.LENGTH_SHORT).show();
Calendar calendar = Calendar.getInstance();
if (Build.VERSION.SDK_INT >= 23) {
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getMinute());
} else {
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
}
intent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
// setRepeating() lets you specify a precise custom interval--in this case,
// 1 minutes.
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60, pendingIntent);
} else {
alarmManager.cancel(pendingIntent);
Toast.makeText(MainActivity.this, "ALARM OFF", Toast.LENGTH_SHORT).show();
}
}
My broadcast receiver class
public class AlarmReceiver extends BroadcastReceiver {
public static Ringtone ringtone;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm! Wake up! Wake up!", Toast.LENGTH_LONG).show();
// using service class
Intent i = new Intent(context, RingtonePlayingService.class);
context.startService(i);
createNotification(context);
}
public void createNotification(Context context) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(android.R.drawable.ic_dialog_alert)
.setContentTitle("It is prayer time")
.setContentText("Prayer")
.setSmallIcon(R.mipmap.ic_launcher)
.setSubText("Tab to cancel the ringtone")
.setPriority(NotificationCompat.PRIORITY_HIGH);
//To add a dismiss button
Intent dismissIntent = new Intent(context, RingtonePlayingService.class);
dismissIntent.setAction(RingtonePlayingService.ACTION_DISMISS);
PendingIntent pendingIntent = PendingIntent.getService(context,
123, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action action = new NotificationCompat.Action
(android.R.drawable.ic_lock_idle_alarm, "DISMISS", pendingIntent);
builder.addAction(action);
// end of setting action button to notification
Intent intent1 = new Intent(context, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 123, intent1,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pIntent);
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(NOTIFICATION_SERVICE);
Notification notification = builder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(123, notification);
}
My ringtoneplaying service class
public class RingtonePlayingService extends Service{
private static final String TAG = RingtonePlayingService.class.getSimpleName();
private static final String URI_BASE = RingtonePlayingService.class.getName() + ".";
public static final String ACTION_DISMISS = URI_BASE + "ACTION_DISMISS";
private Ringtone ringtone;
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.d(TAG, "onStartCommand");
if(intent == null) {
Log.d(TAG, "The intent is null.");
return START_REDELIVER_INTENT;
}
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
ringtone = RingtoneManager.getRingtone(this, alarmUri);
ringtone.play();
String action = intent.getAction();
if(ACTION_DISMISS.equals(action))
dismissRingtone();
return START_NOT_STICKY;
}
public void dismissRingtone() {
Intent i = new Intent(this, RingtonePlayingService.class);
stopService(i);
}
#Override
public void onDestroy() {
ringtone.stop();
}
That was my fault
When i click on disable on notification it again call the receiver class that's why ringtone keeps playing. So i keep some modifying and it works fine.
public class RingtonePlayingService extends Service {
private static final String TAG = RingtonePlayingService.class.getSimpleName();
private static final String URI_BASE = RingtonePlayingService.class.getName() + ".";
public static final String ACTION_DISMISS = URI_BASE + "ACTION_DISMISS";
private Ringtone ringtone;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand");
if (intent == null) {
Log.d(TAG, "The intent is null.");
return START_REDELIVER_INTENT;
}
String action = intent.getAction();
if (ACTION_DISMISS.equals(action))
dismissRingtone();
else {
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
ringtone = RingtoneManager.getRingtone(this, alarmUri);
ringtone.play();
}
return START_NOT_STICKY;
}
public void dismissRingtone() {
// stop the alarm rigntone
Intent i = new Intent(this, RingtonePlayingService.class);
stopService(i);
// also dismiss the alarm to ring again or trigger again
AlarmManager aManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
aManager.cancel(pendingIntent);
// Canceling the current notification
NotificationManager notificationManager =
(NotificationManager)getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
notificationManager.cancel(321);
}
#Override
public void onDestroy() {
ringtone.stop();
}}
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