【问题标题】:show notification in every 3 sec in android在android中每3秒显示一次通知
【发布时间】:2016-05-31 16:33:33
【问题描述】:

我想在我的应用中创建一个服务,每 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();
    }
}

【问题讨论】:

  • 我认为您必须在活动后每 3 秒调用一次服务... n 在开始时写入通知代码的其余部分...

标签: java android notifications


【解决方案1】:

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

你需要使用ScheduledExecutorService.scheduleWithFixedDelay:

创建并执行首先启用的周期性操作 在给定的初始延迟之后,然后在给定的延迟之后 在一项执行的终止和该执行的开始之间 下一个。

试试这个:

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

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

【讨论】:

  • 你能给我一个真实的例子吗?我无法修改我的代码来执行此操作。谢谢
猜你喜欢
  • 1970-01-01
  • 2020-11-17
  • 2011-02-01
  • 2019-09-28
  • 2021-05-10
  • 2015-07-07
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多