目标:构建一个让我想起了在机器上一拳的应用程序。它将在上午8点开始,每10分钟重复一次。每一次,它会使用文字转语音提醒我一拳。使用Job Scheduler在特定的时间,然后重复工作在特定的时间间隔
的基本服务和活动到位。 JobScheduler如何在特定的时间和分钟运行,然后每10分钟运行一次作业直到特定时间?
public class Util {
public static void scheduleJob(Context context) {
ComponentName serviceComponent = new ComponentName(context, TestJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(0, serviceComponent);
JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
jobScheduler.schedule(builder.build());
}
}
public class MyStartServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Util.scheduleJob(context);
}
}
public class TestJobService extends JobService {
@Override
public boolean onStartJob(JobParameters jobParameters) {
Intent service = new Intent(getApplicationContext(), TestVoice.class);
getApplicationContext().startService(service);
Util.scheduleJob(getApplicationContext()); // reschedule the job
return true;
}
@Override
public boolean onStopJob(JobParameters jobParameters) {
return true;
}
}
public class TestVoice extends AppCompatActivity {
TextToSpeech tts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, new TextToSpeech.OnInitListener(){
@Override
public void onInit(int status) {
// TODO Auto-generated method stub
if(status == TextToSpeech.SUCCESS){
int result=tts.setLanguage(Locale.US);
if(result==TextToSpeech.LANG_MISSING_DATA ||
result==TextToSpeech.LANG_NOT_SUPPORTED){
Log.e("error", "This Language is not supported");
}
else{
ConvertTextToSpeech("Have you punched in?");
}
}
else
Log.e("error", "Initilization Failed!");
}
});
}
private void ConvertTextToSpeech(String text) {
// TODO Auto-generated method stub
if(text==null||"".equals(text))
{
text = "Content not available";
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}else
tts.speak(text+"is saved", TextToSpeech.QUEUE_FLUSH, null);
}
}
“然后运行作业每10分钟” - IMO根本,如果你在牛轧糖或更高,并且设备进入休眠模式 - 我试图与这两个模拟器和“真实”的设备,间隔有时只是超过10次,有时(10'片)接近23分钟。 – 0X0nosugar