Android local notification does not work properly after rebooting [duplicate] - android

This question already has answers here:
Notification run after reboot once
(1 answer)
Alarm Manager isn't repeating after reboot
(1 answer)
Closed 5 years ago.
I have a local notification that should show daily, it works very good but after system rebooting it shows only once and then it never shows again,
This is my code in the Activity
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, min);
if (Calendar.getInstance().after(cal)) {
cal.add(Calendar.DAY_OF_MONTH, 1);
}
Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
And this is my Broadcast receiver:
public class AlarmReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager;
notificationManager = (NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
Intent mainIntent=new Intent(context, ReadingQuranActivity.class);
mainIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mainIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
PendingIntent pendingIntent=PendingIntent.getActivity(context,100,mainIntent,PendingIntent.FLAG_UPDATE_CURRENT);
android.support.v4.app.NotificationCompat.Builder builder=new android.support.v4.app.NotificationCompat.Builder(context).setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.read)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.read))
.setContentTitle(context.getResources().getString(R.string.app_name))
.setContentText(context.getResources().getString(R.string.notification_werd)).setAutoCancel(true);
notificationManager.notify(100,builder.build());
}
And here is my permissions and intent filters in the Android Manifest :
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<receiver
android:name=".recivers.AlarmReceiver"
android:enabled="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.media.action.DISPLAY_NOTIFICATION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>

Related

Daily notification cannot start after installing

I'm developing an android application that have daily notification. I have a solution but not enough. My code working after restarting the phone. Users will not restart their devices unless they are required. My notifications will not appear until this time. How can I solve?
BootReceiver.java
public class BootReceiver extends BroadcastReceiver {
private AlarmManager alarmManager;
private PendingIntent pendingIntent;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Device Booted", Toast.LENGTH_SHORT).show();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 19);
calendar.set(Calendar.MINUTE, 20);
calendar.set(Calendar.SECOND, 0);
alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(context, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(context, 1, alarmIntent, 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
}
}
Manifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver
android:name=".AlarmReceiver" />
<receiver
android:name=".BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
AlarmReceiver.java -> just notification builder

Notification triggered immediately and not at the time I wanted it to be triggered

I'm relatively new to Android so I'm quite puzzled here...
I want a notification to be triggered at a certain time on a daily basis.
I use a Calendar class to set the time when the notification is triggered every day, and AlarmManager to set the repeating task.
The problem is, the notification is triggered when the app is initially launched and not at the pre-defined time configured in the Calendar object. When I run in debug mode, I see that I go to the setExact method.
I also created a receiver to handle the notification itself and open the MainActivity when the notification is clicked.
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.
.
.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 0);
Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
if (Build.VERSION.SDK_INT < 19)
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
else
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
NotificationReceiver.java
public class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager manager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent mainIntent = new Intent(context, MainActivity.class);
mainIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(context);
builder.setContentTitle("This is the title")
.setContentText("This is the text")
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.deal_icon);
Notification notification = builder.build();
notification.defaults = Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
manager.notify(100, notification);
}
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.goldbox.goldboxdeals">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:name="com.sample.sample1.ApplicationHelper"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity" android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".NotificationReceiver" android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
</application>
Calendar.getInstance() returns a calendar at your current local time. You're then setting the time to be what you wish, with today's date. When you schedule an alarm, the date is likely in the past. The system then will trigger the alarm immediately.
I believe you should use setRepeating(). You can set the trigger / interval times. Keep in mind that your app, or even the device itself, isn't necessarily running all the time.

AlarmManager is not triggered after complete bootup

I've used an alarmManager to send daily notification. Since alarmManager stops after restarting phone so I've created a BroadcastReceiver to trigger on BOOT_COMPLETE, still no success.
Even not getting toast.
BroadcastRreceiver class
package com.aman.dailynoti;
import...
public class BReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if ((intent.getAction()).equals("android.intent.action.BOOT_COMPLETED")) {
Toast.makeText(context, "broadcast", Toast.LENGTH_SHORT).show();
SharedPreferences mpreferences=context.getSharedPreferences("myPreferences",MODE_PRIVATE);
int h=mpreferences.getInt("hour",14);
int m=mpreferences.getInt("minute", 30);
Calendar calendar= Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,h);
calendar.set(Calendar.MINUTE,m);
calendar.set(Calendar.SECOND,00);
Intent notiIntent = new Intent(context, Notification_Receiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, notiIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application...>
<receiver
android:name="com.aman.dailynoti.BReceiver"
android:enabled="true"
android:label="breceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
</application>
Dont quote me on this but I believe android only gives a small window of time for your applications to do what they need to do on boot. If you want the user to receive notifications when not using the app look into push notifications.
you should use also intent filter android.intent.action.QUICKBOOT_POWERON to recieve after restart

How to trigger Notification in background?

I'm trying to trigger a notification every 15 minutes, starting from the time I set. Currently my app notifies only when my application is open or when it is in the recent applications but when i closed my application the notification doesn't work any longer but when i open again my app it will trigger the notification. Based on my research I need a Service. So I have 3 files.
In my MainActivity, i set the alarm
private void scheduleNotification(int week){
Intent notificationIntent = new Intent(this, NotificationPublisher.class);
notificationIntent.putExtra("notifId", getResources().getInteger(R.integer.notification_id));
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, getResources().getInteger(R.integer.notification_id), notificationIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, week);
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent);
}
in the MainActivity i call a BroadcastReceiver which is the NotificationPublisher. Here is my NotificationPublisher
public class NotificationPublisher extends BroadcastReceiver {
final String TAG = "NotificationPublisher";
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, NotificationAlarmService.class);
service.putExtra("notifId", intent.getIntExtra("notifId", 0));
context.startService(service);
}
then I start a service by using the BroadcastReceiver which is the NotificationAlarmService, here i build a Notification using NotificationCompat.Builder.
public class NotificationAlarmService extends Service {
. . . .
#Override
public int onStartCommand(Intent intent,int flag, int startId)
{
notificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent mIntent = new Intent(this, MainActivity.class);
pendingIntent = PendingIntent.getActivity(this, intent.getIntExtra("notifId", 0), mIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle("App");
builder.setContentText("Notify Me");
builder.setAutoCancel(true);
builder.setSmallIcon(getNotificationIcon());
builder.setContentIntent(pendingIntent);
notificationManager.notify(intent.getIntExtra("notifId", 0), builder.build());
return super.onStartCommand(intent, flag, startId);
}
I already tried returning START_STICKY instead of super.onStartCommand I understand that when i used a service it will run in the background even if the user closed the application. I also tried changing this and used getBaseContext() in the service but this it doesn't trigger the notification. I don't know if i'm missing something. Thank you in advance.
EDIT
Here is my Manifest
<receiver android:name=".NotificationPublisher"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<service android:name=".NotificationAlarmService"
android:enabled="true">
</service>
After a week, I finally got it. In my Manifest i put something like this
<receiver android:name=".NotificationPublisher">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<service android:name=".NotificationAlarmService"
android:enabled="true"
android:exported="false" >
<intent-filter>
<action android:name="NOTIFICATION_SERVICE" />
</intent-filter>
</service>
i've removed the enabled="true" in the receiver and also add QUICKBOOT_POWERON. Then add an action in the service which is NOTIFICATION_SERVICE and call it in my service like this
NotificationManager mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Try adding Service in your Manifest file (Same as declaring an Activity) under application tag like this,
<service android:name="com.example.android.NotificationAlarmService">
</service>

setAlarm is not working to fire notification after specific time

I am almost done, but when clicking the set Alarm button to fire the notification after 5 seconds for example, nothing happens.
this is the OnClick method for SetAlarm
public void setAlarm(View view) {
long alertTime = new GregorianCalendar().getTimeInMillis()+5*1000;
Intent alertIntent = new Intent(this, AlertReceiver.class);
//schedule to happen at later date
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, alertTime, PendingIntent.getBroadcast(this, 1, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
}
and this is my receiver:
public class AlertReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
createNotification(context, "Times up", "5 seconds has passed", "Alert");
}
public void createNotification(Context context, String msg, String msgText, String msgAlert) {
PendingIntent notificIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
NotificationCompat.Builder mBuilder=new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.not)
.setContentTitle(msg)
.setTicker(msgAlert)
.setContentText(msgText);
//intent to fire when notification clicked on
mBuilder.setContentIntent(notificIntent);
//how the person will be notified
mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
//cancel notification when clicked in the taskbar
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager= (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1,mBuilder.build());
}
and this is my Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yahyazeid.testnotification" >
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<service android:name=".AlertReceiver">
<intent-filter> <action android:name="NOTIFICATION_SERVICE" />
</intent-filter>
</service>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MoreInfoNotification"
android:label="More on notification"
android:parentActivityName=".MainActivity">
</activity>
</application>
</manifest>
Any suggestions?
The corrected manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yahyazeid.testnotification" >
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MoreInfoNotification"
android:label="More on notification"
android:parentActivityName=".MainActivity">
</activity>
<service android:name=".AlertReceiver">
</service>
</application>
</manifest>
Try this code. It looks like you did not set the notification in your receiver.
public void scheduleAlarm(View V)
{
// time at which alarm will be scheduled here alarm is scheduled at 1 day from current time,
// we fetch the current time in milliseconds and added 1 day time
// i.e. 24*60*60*1000= 86,400,000 milliseconds in a day
Long time = new GregorianCalendar().getTimeInMillis()+5*1000;
// create an Intent and set the class which will execute when Alarm triggers, here we have
// given AlarmReciever in the Intent, the onRecieve() method of this class will execute when
Intent intentAlarm = new Intent(this, AlarmReciever.class);
//Get the Alarm Service
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//set the alarm for particular time
alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this,1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
Toast.makeText(this, "Alarm Set for 5 seconds", Toast.LENGTH_LONG).show();
Then for the Receiver
public class Receiver extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.depressiontest)
.setContentTitle("Time has Expired")
.setContentText("5 Seconds has passed.")
.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(0, mBuilder.build());
}
And then in your manifest
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<service android:name=".Receiver">
<intent-filter> <action android:name="NOTIFICATION_SERVICE" />
</intent- filter>
</service>
For setting a specific date using the get Calendar instance
Calendar cal = Calendar.getInstance();
//Setting date for 11/29/2016
cal.set(Calendar.DATE,29); //1-31 days of week
cal.set(Calendar.MONTH,10); //January starts at 0 (zero), December = 11
cal.set(Calendar.YEAR,2016);//year...
//Setting the specific hour/min/sec
cal.set(Calendar.HOUR_OF_DAY, 16); //HOUR
cal.set(Calendar.MINUTE, 39); //MIN
cal.set(Calendar.SECOND, 10); //SEC
// Create a new PendingIntent and add it to the AlarmManager
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getService(MainActivity.this, 0,intent, 0);
//or if you start an Activity
//PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0,intent, 0);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);

Categories

Resources