我希望在时钟上午9:00触发事件 我希望在下午4:30时钟滴答时触发另一个事件,这应该是每天完成的,当用户启用它时(比如使用切换按钮启用/禁用此功能)。
答案 0 :(得分:0)
您应该参考this
但是,如果您的Android应用程序中有重复性任务,则需要考虑Android系统可以终止活动和服务以释放资源。因此,您不能像TimerTasks(AlarmManager)类那样依赖标准的Java调度。
<service
android:name=".MyService"
android:label="some_name"
android:permission="android.permission.BIND_JOB_SERVICE" >
</service>
<receiver android:name="MyStartServiceReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
这应该在你的java类中:
public static void scheduleJob(Context context) {
ComponentName serviceComponent = new ComponentName(context, TestJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(0, serviceComponent);
builder.setMinimumLatency(1 * 1000); // wait at least
builder.setOverrideDeadline(3 * 1000); // maximum delay
//builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED); // require unmetered network
//builder.setRequiresDeviceIdle(true); // device should be idle
//builder.setRequiresCharging(false); // we don't care if the device is charging or not
JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
jobScheduler.schedule(builder.build());
}
创建另一个类以启动服务并收听:
public class MyStartServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Util.scheduleJob(context);
}
}
这将告诉服务启动和参数。
public class TestJobService extends JobService {
private static final String TAG = "SyncService";
@Override
public boolean onStartJob(JobParameters params) {
Intent service = new Intent(getApplicationContext(), LocalWordService.class);
getApplicationContext().startService(service);
Util.scheduleJob(getApplicationContext()); // reschedule the job
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
return true;
}
}