java - android中每3秒显示一次通知

标签 java android notifications

我想在我的应用程序中创建一个服务,每 3 秒创建一个通知。我创建了这段代码,但它只在我启动我的应用程序时有效一次。我希望每 3 秒收到一次通知!即使当我关闭我的应用程序时我也会收到通知! (因此我创建了服务) 请帮助我。

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();
    }
}

最佳答案

您使用的schedule方法执行一次性操作

您需要使用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.

试试这个:

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

请注意方法调用中额外的 3,因为此方法需要四个参数。

关于java - android中每3秒显示一次通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15449511/

相关文章:

java - 如何使用加速度计值显示数字

安卓。在运行时更改 LinearLayout 的边距

android - DeepLinking 可以工作,但无法使用 react 导航导航到预期屏幕

Java 等待 IClientNotificationService

java - Swing中使用row来过滤Jtable

java - 将对象从 Activity 传递到 IntentService

ios - PushNotification OneSignal 问题

android - 如何在 Cordova for Android 中除周日外的所有日子发送一个通知?

java - 在线停止其中一种 Http 方法

android - 与 PC 相比,为什么 Android 中的响应时间(对于 Rest Call)较慢?