android - 处理程序延迟 60 秒不工作?

标签 android android-studio android-handler

我正在运行一个处理程序以在后台显示一些通知。在测试时,当我将延迟限制设置为 5 秒时,它可以完美运行。但每当我将它设置为 60 秒或更长时间时,它就不起作用。这是为什么?

    int delay = 1000 * 60;
    HandlerThread hThread = new HandlerThread("HandlerThread");
    hThread.start();
    Handler handler = new Handler(hThread.getLooper());

    Runnable task = new Runnable() {
        @Override
        public void run() {
            NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
            Intent launchIntent = new Intent(getApplicationContext(), AndroidLauncher.class);
            PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, launchIntent, 0);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(AndroidLauncher.this);
            //Set notification information
            builder.setSmallIcon(R.drawable.ic_launcher)
                    .setTicker("Hi!")
                    .setWhen(System.currentTimeMillis())
                    .setAutoCancel(true)
                    .setDefaults(Notification.DEFAULT_SOUND)
                    .setContentTitle(mytitle)
                    .setContentText(mytext)
                    .setContentIntent(contentIntent);

            NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle(builder);
            style.setSummaryText("4 Task");
            style.addLine("Two");
            style.addLine("Three");
            style.addLine("Four");
            style.addLine("Five");

            Notification note = style.build();
            manager.notify(50, note);
        }
    };

    handler.postDelayed(task, delay);

最佳答案

导入 导入android.os.Handler;

并使用以下代码:

  new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    //do your work here after 60 second
                }
            },60000);

关于HandlerHandlerThreadLooper 有很好的教程here .

关于android - 处理程序延迟 60 秒不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37309904/

相关文章:

java - 字符串换行导致错误

android - 本地路径不存在 Android Studio 1.0

java - 将上下文从服务类传递到另一个服务类

java - 来自非 Activity 类的处理程序

java - 如何知道 Activity 已经完成?

android - 有没有办法从 Android 的自定义相机 View 中删除暂停按钮?

android - 在启动时和安装应用程序后启动服务

android - 选项卡布局中的回收 View

java - 每 x 毫秒执行一次的代码,可更改

java - Android:显示带有时间延迟的数组元素?