1.android 自帶鬧鐘定時任務
安卓鬧鐘可以配合廣播來實現(不推薦)吹泡,系統(tǒng)資源浪費惩妇,安卓系統(tǒng)在5.0以后的定時
任務貌似觸發(fā)時間不準了普筹,因為了為了省電。
//獲取系統(tǒng)鬧鐘
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(ReportDetailsActivity.this, ReportDetailsActivity.MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
//開啟定時任務
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000, 5 * 1000, pendingIntent);
記得在manifeast 文件配置該廣播
public static class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (bo > 0) {
if (bo > 240) {//刷票
handler.sendEmptyMessage(3);//彈窗警告 刷票
} else {
handler.sendEmptyMessage(2);
}
}
}
}
在OnDestroy()中取消鬧鐘
@Override
protected void onDestroy() {
alarmManager.cancel(pendingIntent);
}
2.開啟Thread
睡5s中去定時操作任務面哼。
class MyRunnable implements Runnable{
@Override
public void run() {
while (isLoop){
try {
if (bo > 0) {
if (bo > 240) {//刷票
handler.sendEmptyMessage(3);//彈窗警告 刷票
} else {
handler.sendEmptyMessage(2);
}
}
Thread.sleep(5000);
}catch (Exception e){
e.printStackTrace();
}
}
}
}
在onCreate()方法中開啟:
loopThread=new Thread(new MyRunnable());
loopThread.start();
在頁面銷毀時終止掉該Thread
isLoop=false;
loopThread.interrupt();
3. 使用timer類野宜。
開啟timer
Timer timer=new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
//TODO ...
}
},new Date(),5000);
終止timer
timer.cancel();
以上三種定時任務除了第一種不要隨便使用外,推薦使用第三種和第二種魔策。
我的微信公眾號:行走的那些事匈子,歡迎大家掃一掃。
行走的那些事