如何每2小时弹出一次Alertdialog?

时间:2019-06-11 09:14:28

标签: android popup android-alertdialog

登录后,我想每2小时使用AlertDialog显示一次对话框。

尝试以下代码:

 private void ShowDialog() {

        new SweetAlertDialog(getContext())
                .setTitleText("Attention!")
                .setContentText("Have You Checked Followup list? Check Here !!")
                .setConfirmText("Followup List")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                           ShowFollowupList();
                        sweetAlertDialog.dismissWithAnimation();

                    }
                })
                .setCancelButton("Cancel", new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.dismissWithAnimation();
                    }
                })
                .show();
    }

3 个答案:

答案 0 :(得分:1)

使用工作管理器可以显示它。

引用链接:https://developer.android.com/topic/libraries/architecture/workmanager

使用WorkManager安排任务 通过API,可以轻松安排可延迟的异步任务,即使应用程序退出或设备重启,这些任务也有望运行。

答案 1 :(得分:0)

WorkManagerbackground中将foreground用于计划任务

定期请求示例

PeriodicWorkRequest request= new PeriodicWorkRequest.Builder(WorkerClass.class,
                            2, TimeUnit.HOURS).addTag("TAG").build()
WorkManager.getInstance().enqueueUniquePeriodicWork("TAG", ExistingPeriodicWorkPolicy.KEEP, request);

创建工人班

public class WorkerClass extends Worker {
    @Override
    public Worker.WorkerResult doWork() {

        // Do the work here

        // Indicate success or failure with your return value:
        return WorkerResult.SUCCESS;

        // (Returning RETRY tells WorkManager to try this task again
        // later; FAILURE says not to try again.)
    }
}

将此内容添加到build.gradle

  

实现'android.arch.work:工作运行时:2.1.0-alpha01'

查看最新版本的文档https://developer.android.com/jetpack/androidx/releases/work

答案 2 :(得分:0)

您可以使用AlarmManager来实现。

首先,如下创建扩展BroadcastReceiver的Receiver类。

public class YourReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // show your dialog here
    }
}

然后,创建一个AlarmManagerPendingIntent实例来设置警报,如下所示。

public void setAlarm(Context context, int requestCode) {
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, YourReceiver.class);

    // different request code enable you to set alarm more than one
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    final long everyTwoHours = 2 * 60 * 60 * 1000; // in milliseconds
    alarmManager.setInexactRepeating(
                AlarmManager.RTC, calendar.getTimeInMillis(), everyTwoHours, pendingIntent);
}