I am new to android and working on Notification Alarm Manager to show notification. I am on API 23.
The code I posted below is working perfectly but I cannot filgure why it is not notifying me?
Can Any one help me what is the error in it?
Thanks.
MainActivity
public class MainActivity extends AppCompatActivity {
Button b;
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) this.findViewById(R.id.btn);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, 11);
calendar.set(Calendar.YEAR, 2015);
calendar.set(Calendar.DAY_OF_MONTH, 30);
calendar.set(Calendar.HOUR_OF_DAY, 15);
calendar.set(Calendar.MINUTE, 34);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM,Calendar.PM);
Intent myIntent = new Intent(MainActivity.this, AlarmBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
}
AlarmBroadcastReceiver
public class AlarmBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent startIntent = new Intent(context, AlarmService.class);
context.startService(startIntent);
}
}
AlarmService
public class AlarmService extends Service{
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
generarNotificacion();
return Service.START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void generarNotificacion(){
Intent resultIntent = new Intent(this.getApplicationContext(), MainActivity.class);
android.support.v4.app.NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.heart1)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(getResources().getString(R.string.text));
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
// Sets an ID for the notification
int mNotificationId = 001;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}
Android Manifest
<uses-permission-sdk-23 android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<service android:name=".AlarmService"
android:enabled="true" />
<receiver android:name=".AlarmBroadcastReceiver"/>
It appears that you're trying to set an alarm for today, shortly in the future. However, months are zero-based, so a value of 11 is actually December. If you want November, the corresponding value is 10. A better option, though, is to use the class constant: Calendar.NOVEMBER.
Related
I've tried a bunch of things in order to notification worked well, but nothing is working properly... This is my NotificationPublisher class
public class NotificationPublisher extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate(){
Intent intent = new Intent(this,CreateNewPvpFragment.class);
long[] pattern = {0,300,0};
PendingIntent pi = PendingIntent.getActivity(this,01234,intent,0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_home_black_24dp)
.setContentTitle("PVP")
.setContentText("Verify your PVP")
.setVibrate(pattern)
.setAutoCancel(true);
mBuilder.setContentIntent(pi);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(01234,mBuilder.build());
}
}
And here my NotificationReceiver class:
public class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context,NotificationPublisher.class);
context.startService(service);
}
}
And finally my method in my Fragment
public void addReminder (int mYear, int mMonth, int mDay){
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR,mYear);
c.set(Calendar.MONTH,mMonth);
c.set(Calendar.DAY_OF_MONTH,mDay);
c.set(Calendar.HOUR_OF_DAY,15);
c.set(Calendar.MINUTE,30);
c.set(Calendar.SECOND,0);
c.set(Calendar.AM_PM,Calendar.PM);
int alarmId = 001;
alarmId = Integer.parseInt(mDay+""+mMonth+"");
Intent intent = new Intent(getActivity(), NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(),alarmId,intent, 0);
AlarmManager am = (AlarmManager) getActivity().getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(), pendingIntent);
}
This method its receiving values from the Datepicker dialog, according to user input.
Before, it was working only with the current day, but now neither with that
Hi guys i am trying to create the push notification using the alarm manager where push notification must come at morning 8AM everything is good but notification is also coming but after 8AM notification is completed the notification coming when ever i open the App or clear from recents or for every one hour notification is coming please help me out facing this problem from last 1 Week
MainActivity.class
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent notificationintent = new Intent(this, Notify.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 100, notificationintent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationintent.setData((Uri.parse("custom://"+System.currentTimeMillis())));
Calendar calnotify = Calendar.getInstance();
Calendar now=Calendar.getInstance();
//Time Alaram manager
calnotify.set(Calendar.HOUR_OF_DAY, 10);
calnotify.set(Calendar.MINUTE, 00);
calnotify.set(Calendar.SECOND, 0);
if (now.after(calnotify)){
calnotify.add(Calendar.DATE,1);
}
am.setRepeating(AlarmManager.RTC_WAKEUP, calnotify.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
Notify.class
//BroadCastReceiver class
public class Notify extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent pushservice=new Intent(context,PushNotification.class);
pushservice.setData((Uri.parse("custom://"+System.currentTimeMillis())));
context.startService(pushservice);
}
}
PushNotification.class
public class PushNotification extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Resources resources = getResources();
getnotify(resources);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Resources resources = getResources();
getnotify(resources);
/*Notify notify=new Notify();
notify.abortBroadcast();*/
}
private void getnotify(Resources resources) {
Bitmap icon = BitmapFactory.decodeResource(resources,
R.drawable.sr_notification_icon);
PugNotification.with(this)
.load()
.title(getResources().getString(R.string.app_name))
.message("Latest Chitka")
.bigTextStyle(getResources().getString(R.string.app_name))
.smallIcon(getNotificationIcon())
.largeIcon(icon)
.flags(android.app.Notification.DEFAULT_ALL).autoCancel(true).click(MyCalendarActivity.class)
.simple()
.build();
}
private int getNotificationIcon() {
boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
return useWhiteIcon ? R.drawable.sr_icon : R.drawable.sr_notification_icon;
}
}
Looks like the code for setting alarm is executing multiple times as it is called from the main Activity of the application. You should set a flag that gets set to true once the alarm is set. Next time skip the alarm setting based on this flag.
I want to create notifications on multiple specific dates & time, which are stored in database. I can get Notifications on correct date and time, but what i noticed later is, that i also got notifications randomly on the next day. They keep cropping up whenever i restart the emulator.
So, it seems that i can't stop the Alarm manager or Broadcast receiver. I've tried with providing pendingIntent to alarmmanager's cancel method to no avail. I also use toggle button to enable/disable notification, but it has no effect
Below is my code.
MainActivity.java
PendingIntent pendingIntent;
AlarmManager alarmManager;
Button set, cancel;
MTPAdapter db;
ArrayList<TourPlan> arrDates;
ToggleButton toggle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
toggle = (ToggleButton) findViewById(R.id.toggleButton1);
// This function fetched data from DB
fetchDates();
set = (Button) findViewById(R.id.the_button);
cancel = (Button) findViewById(R.id.the_button_cancel);
cancel.setEnabled(false);
toggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
Toast.makeText(getApplicationContext(), "Set",
Toast.LENGTH_SHORT).show();
setEvent();
} else {
alarmManager.cancel(pendingIntent);
MyReceiver.stopService(getApplicationContext());
}
}
});
} // end onCreate
public void setEvent() {
for (int i = 0; i < arrDates.size(); i++) {
// int id = arrDates.get().getId();
int year = Integer.parseInt(arrDates.get(i).getYear());
int month = Integer.parseInt(arrDates.get(i).getMonth());
int date = Integer.parseInt(arrDates.get(i).getDate());
int hour = Integer
.parseInt(firstStringer(arrDates.get(i).getTime()));
Log.v("Hour : ", "" + hour);
int minute = Integer.parseInt(stringer(arrDates.get(i).getTime()));
Log.v("minute : ", "" + minute);
int second = 00;
startAlarm(i, year, month, date, hour, minute, second);
}
}
public void startAlarm(int id, int year, int month, int date, int hour,
int minute, int second) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.DAY_OF_MONTH, date);
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
// calendar.set(Calendar.AM_PM, Calendar.PM);
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, id,
myIntent, 0);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(),
pendingIntent);
}
}
MyAlarmService.java
public class MyAlarmService extends Service {
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("ISFA")
.setStyle(
new NotificationCompat.BigTextStyle()
.bigText("Tour Planned for the Day"))
.setContentText("You have planned a tour for today")
.setAutoCancel(true);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
MyReceiver.java (Broadcast receiver) :
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);
}
public static void stopService(Context context) {
Intent stopServiceIntent = new Intent(context, MyAlarmService.class);
context.stopService(stopServiceIntent);
}
}
Manifest file:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
In Application tags,
<service
android:name="com.example.brodcastalarm.MyAlarmService"
android:enabled="true" />
<!-- THE BROADCAST RECIEVER WHICH MANAGES THE BROADCAST FOR NOTIFICATION -->
<receiver android:name="com.example.brodcastalarm.MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
This is the Database structure.
I use subString methods to get hour and minutes.
Alarm manager needs to be manually disabled, so for doing so use code below, it will disable the alarm.
AlarmManager aManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(getBaseContext(), YourScheduleClass.class);
PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
aManager.cancel(pIntent);
I have app which in specific time start notification in status bar.But when that time elapsed, every time when I launch the app he start the notification again.
Thanks in advance.
Here is the code:
Activity: MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//notifications with solve problem
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar.set(Calendar.HOUR_OF_DAY, 17);
calendar.set(Calendar.MINUTE, 30 );
calendar.set(Calendar.SECOND, 0);
calendar.getTimeInMillis();
long current_time = System.currentTimeMillis();
long limit_time = calendar.getTimeInMillis();
if (current_time > limit_time) {
//nothing
} else {
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
}
}
}
Activity: MyReceiver
public class MyReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent)
{
Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);
}
}
Activity: MyAlarmService
public class MyAlarmService extends Service{
private NotificationManager mManager;
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
Notification notification = new Notification(R.drawable.ic_launcher,"Run this app", System.currentTimeMillis() );
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(), "Horoscope", "Run this app", pendingNotificationIntent);
mManager.notify(0, notification);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
I solve the problem with this post - Notification at specific time
use
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), SYNC_REPEAT_MILLSECONDS, pendingIntent);
instead of
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
When binding onClick in activity_main.xml to setAlarm to one button and unsetAlarm to another button in the same activity, the following code will not let you unset the alarm when clicking the button linked to the unsetAlarm method.
...package name and includes ommitted...
public class MainActivity extends Activity {
private AlarmManager alarmManager;
private PendingIntent notifyIntent;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
}
public void setAlarm(View v) {
Intent myIntent = new Intent(MainActivity.this,
NotificationService.class);
notifyIntent = PendingIntent.getService(MainActivity.this, 0,
myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, 1);
Log.v(TAG, "time for alarm trigger:" + calendar.getTime().toString());
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 1 * 60 * 1000, notifyIntent);
}
public void unsetAlarm(View v) {
alarmManager.cancel(notifyIntent);
Log.v(TAG, "cancelling notification");
}
}
The solution was to (as I was provided in Notifications and AlarmManager - cancelling the alarm I set) recreate the pendingIntent in the unsetAlarm method:
public void unsetAlarm(View v) {
Intent myIntent = new Intent(MainActivity.this,
NotificationService.class);
notifyIntent = PendingIntent.getService(MainActivity.this, 0,
myIntent, 0); // recreate it here before calling cancel
alarmManager.cancel(notifyIntent);
Log.v(TAG, "cancelling notification");
}
My question is: Why can I not reuse the PendingIntent, stored in the field "notifyIntent" in the first code snippet? Why do I have to recreate it to cancel it? I have set the of MainActivity to have the attribute android:launchMode="singleInstance" so I should believe it was using the same instance when I click the notification created in the NotificationService (I have ommitted it but it just shows a notification).