Fcoder
Fcoder

Reputation: 9216

show notification in every 3 sec in android

I want create a service within my app that every 3 sec creates a notification. i create this code but it works only one time when i launch my app. i want get notification in every 3 sec!! even when i close my app i get notifications!! ( because of this i create service) please help me.

public class notifService extends Service {
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
private static final int HELLO_ID = 1;

    @Override
        public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        final Intent intent1 = new Intent(this, notifService.class);

        scheduler.schedule(new Runnable() {
            @Override
            public void run() {
                // Look up the notification manager server
                NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

                // Create your notification
                int icon = R.drawable.fifi;
                CharSequence tickerText = "Hello";
                long when = System.currentTimeMillis();
                Notification notification = new Notification(icon, tickerText,when);
                Context context = getApplicationContext();
                CharSequence contentTitle = "My notification";
                CharSequence contentText = "Hello World!";
                PendingIntent pIntent = PendingIntent.getActivity(notifService.this, 0, intent1, 0);
                notification.setLatestEventInfo(context, contentTitle,contentText, pIntent);
                // Send the notification
                nm.notify(HELLO_ID, notification);
            }
        }, 3, SECONDS);
    }

    @Override
        public void onDestroy() {
        super.onDestroy();
    }
}

Upvotes: 0

Views: 3103

Answers (1)

user2030471
user2030471

Reputation:

The schedule method you're using executes a one-shot action.

You need to use ScheduledExecutorService.scheduleWithFixedDelay:

Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next.

Try this:

scheduler.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
          // your code
        }
    }, 3, 3, SECONDS);

Note the extra 3 in the method call as this methods expects four arguments.

Upvotes: 2

Related Questions