Search code examples
androidandroid-notificationsandroid-alarms

Create notifications every minute


I want to create notifications every minute, I put code from another question about notification every 48 hour but app is working and notifications do not get created. What am I doing wrong? ShowNotification:

public class ShowNotification extends Service {

    private final static String TAG = "ShowNotification";

    @Override
    public void onCreate() {
        super.onCreate();

        Intent mainIntent = new Intent(this, MainActivity.class);

        NotificationManager notificationManager
                = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

        Notification noti = new NotificationCompat.Builder(this)
                .setAutoCancel(true)
                .setContentIntent(PendingIntent.getActivity(this, 0, mainIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT))
                .setContentTitle("New SMS " + System.currentTimeMillis())
                .setContentText("Hello")
                .setDefaults(Notification.DEFAULT_ALL)
                .setSmallIcon(R.drawable.ic_email_white_24dp)
                .setTicker("ticker message")
                .setWhen(System.currentTimeMillis())
                .build();

        notificationManager.notify(0, noti);

        Log.i(TAG, "Notification created");
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
}

MainActivity:

context = MainActivity.this;
        Intent notificationIntent = new Intent(context, ShowNotification.class);
        PendingIntent contentIntent = PendingIntent.getService(context, 0, notificationIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        am.cancel(contentIntent);
        am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
                , 1000*60, contentIntent);

Solution

  • Couple suggestions:

    1. Implement your notification firing code using an IntentService. If you are using android studio there is a very easy wizard available for making one. Just right click on a package>new>Service>Service(Intent Service). Put your notification firing code in the handle action method. This needs to be declared in your manifest.

    2. Define a BroadcastReceiver, preferably in a different file that calls a static method to start the intent service in its onReceive(). This is also available in the wizard in new>others>BroadcastReciever. This also needs to be declared in your manifest.

    3. Create a static method to initialize the alarms (I put it in the IntentService itself) and call it from your main activity.

    4. As it is now, you are providing the same id (0)to your notifications. this will only replace the original notification instead of creating a new one.

    The Following code might help: (I built it using the wizard so ignore the auto generated comments if they are inaccurate)

    IntentService:

    import android.app.AlarmManager;
    import android.app.IntentService;
    import android.app.Notification;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.content.Intent;
    import android.content.Context;
    import android.support.v7.app.NotificationCompat;
    
    
    import java.util.Calendar;
    
    /**
     * An {@link IntentService} subclass for handling asynchronous task requests in
     * a service on a separate handler thread.
     * <p/>
     * helper methods.
     */
    public class NotificationIntentService extends IntentService {
        // TODO: Rename actions, choose action names that describe tasks that this
        // IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
        private static final String ACTION_FIRENOTIF = "com.example.alarmnotif.action.FOO";
    
        public NotificationIntentService() {
            super("NotificationIntentService");
        }
        public static void initAlarm(Context context) {
            Calendar updateTime = Calendar.getInstance();
            Intent downloader = new Intent(context, AlarmReceiver.class);
            PendingIntent recurringSync = PendingIntent.getBroadcast(context,
                    0, downloader, PendingIntent.FLAG_CANCEL_CURRENT);
    
            AlarmManager alarms = (AlarmManager) context.getSystemService(
                    Context.ALARM_SERVICE);
            alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                    updateTime.getTimeInMillis(),
                    60000, recurringSync);
        }
    
        /**
         * Starts this service to perform action FireNotif with the given parameters. If
         * the service is already performing a task this action will be queued.
         *
         * @see IntentService
         */
        public static void startActionFireNotif(Context context) {
            Intent intent = new Intent(context, NotificationIntentService.class);
            intent.setAction(ACTION_FIRENOTIF);
            context.startService(intent);
        }
    
    
        @Override
        protected void onHandleIntent(Intent intent) {
            if (intent != null) {
                final String action = intent.getAction();
                if (ACTION_FIRENOTIF.equals(action)) {
                    handleActionFireNotif();
                }
            }
        }
    
        /**
         * Handle actionFireNotif in the provided background thread with the provided
         * parameters.
         */
        private void handleActionFireNotif() {
            Intent mainIntent = new Intent(this, MainActivity.class);
    
            NotificationManager notificationManager
                    = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    
            Notification noti = new NotificationCompat.Builder(this)
                    .setAutoCancel(true)
                    .setContentIntent(PendingIntent.getActivity(this, 0, mainIntent,
                            PendingIntent.FLAG_UPDATE_CURRENT))
                    .setContentTitle("New SMS " + System.currentTimeMillis())
                    .setContentText("Hello")
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setSmallIcon(R.drawable.ic_email_white_24dp)
                    .setTicker("ticker message")
                    .setWhen(System.currentTimeMillis())
                    .build();
    
            notificationManager.notify(0, noti);
    
        }
    
    
    }
    

    AlarmReciever:

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    
    public class AlarmReceiver extends BroadcastReceiver {
        public AlarmReceiver() {
        }
    
        @Override
        public void onReceive(Context context, Intent intent) {
            NotificationIntentService.startActionFireNotif(context);
        }
    }
    

    Add the following to the manifest:

        <service
            android:name=".alarmnotif.NotificationIntentService"
            android:exported="false" />
    
        <receiver
            android:name=".alarmnotif.AlarmReceiver"
            android:enabled="true"
            android:exported="false"></receiver>