首页 > 解决方案 > Daily job using Evernote's job library

问题描述

I just wanna to fire local push notification at the specific time every day! I found in the documentation I can achieve this. Below code:

public class MyDailyNotMorning extends DailyJob {

public static final String TAG = "MyDailyJob";

public static void schedule() {
    // schedule between 1 and 6 *PM*
    DailyJob.schedule(builder, TimeUnit.HOURS.toMillis(1), TimeUnit.HOURS.toMillis(6));
}

@NonNull
@Override
protected DailyJobResult onRunDailyJob(Params params) {
    PendingIntent pi = PendingIntent.getActivity(getContext(), 0,
            new Intent(getContext(), MainActivity.class), 0);

    Notification notification = new NotificationCompat.Builder(getContext())
            .setContentTitle("Morning")
            .setContentText("It's time to send a photo!")
            .setAutoCancel(true)
            .setContentIntent(pi)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setShowWhen(true)
            //   .setColor(Color.RED)
                .setLocalOnly(true)
            .build();


    NotificationManagerCompat.from(getContext())
            .notify(new Random().nextInt(), notification);
    Log.d("myTag", "onRunJob: notification setted daily success:morning");

    return DailyJobResult.SUCCESS;
}
}

Say in this case notification receives at 1 a.m(or p.m), so the issue is what the second parameter of this method. Or how can I achieve "receive local notification" at 8 a.m (only 8 a.m. not p.m)? Please help me?!

标签: androidjobs

解决方案


来自文档的注释:

// 安排在凌晨 1 点到 6 点之间

DailyJob.schedule(new JobRequest.Builder(TAG), TimeUnit.HOURS.toMillis(1),TimeUnit.HOURS.toMillis(6));

这不是 PM 。如果您尝试18:00:00它是 PM 它遵循 24 小时制。


代码

这是我的理论思考(需要测试)但您可以在下面尝试,如果可行,请发表评论。

您设置08:00:0008:00:05DailyJob之间的值。这意味着开始时间和结束时间之间有五秒的差异。

您可以使用TimeUnit.Seconds.toMillis(5) 就像您以前使用的一样。

public class Tasker extends DailyJob {
    static final String TAG = "do_update_value_job_tag";

    static void schedulePeriodic(Context context) {
        Long startMs = TimeUnit.HOURS.toMillis(8);
        Long endMs = TimeUnit.HOURS.toMillis(8) + TimeUnit.SECONDS.toMillis(5); //←←←
        JobRequest.Builder requestByTag = new JobRequest.Builder(Tasker.TAG).setUpdateCurrent(true);
        DailyJob.schedule(requestByTag, startMs, endMs);
    }

    @NonNull
    @Override
    protected DailyJobResult onRunDailyJob(@NonNull Params params) {
        //do stuff
        return DailyJobResult.SUCCESS;
    }

    @Override
    protected void onCancel() {
        //do stuff
        super.onCancel();
    }
}

推荐阅读