Show notifications every 3 seconds on android

I want to create a service in my application that creates a notification every 3 seconds. I create this code, but it only works once when I launch my application. I want to be notified every 3 seconds! even when I close my application, I get notifications! (because of this I create a 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(); } } 
0
java android notifications
source share
1 answer

The schedule method used performs a one-time action.

You need to use ScheduledExecutorService.scheduleWithFixedDelay :

Creates and performs a periodic action that is first turned on after a given initial delay, and then with a given delay between the termination of one execution and the beginning of the next.

Try the following:

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

Note the extra 3 in the method call, as these methods have four arguments.

+2
source share

All Articles