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

时间:2016-05-18 20:52:05

标签: android android-studio android-handler

我正在运行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);

1 个答案:

答案 0 :(得分:1)

导入 import android.os.Handler;

并使用以下代码:

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

有关HandlerHandlerThreadLooper here的良好教程。