至於其他社區用戶建議,不要使用TimerTask的,android有 AlarmManager
,您可以使用。
如何?
- 註冊報警經理廣播接收器,還有覆蓋(當alamr被激發做什麼)
- 設置要執行日常的間隔和時間報警的onReceive方法。
這裏摘錄如實施例:
public class MainActivity extends Activity {
private static final String TAG ="MainActivity";
PendingIntent myPendingIntent;
AlarmManager alarmManager;
BroadcastReceiver myBroadcastReceiver;
Calendar firingCal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Register AlarmManager Broadcast receive.
firingCal= Calendar.getInstance();
firingCal.set(Calendar.HOUR, 8); // At the hour you want to fire the alarm
firingCal.set(Calendar.MINUTE, 0); // alarm minute
firingCal.set(Calendar.SECOND, 0); // and alarm second
long intendedTime = firingCal.getTimeInMillis();
registerMyAlarmBroadcast();
alarmManager.set(AlarmManager.RTC_WAKEUP, intendedTime , AlarmManager.INTERVAL_DAY , myPendingIntent);
}
private void registerMyAlarmBroadcast()
{
Log.i(TAG, "Going to register Intent.RegisterAlramBroadcast");
//This is the call back function(BroadcastReceiver) which will be call when your
//alarm time will reached.
myBroadcastReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
Log.i(TAG,"BroadcastReceiver::OnReceive()");
Toast.makeText(context, "Your Alarm is there", Toast.LENGTH_LONG).show();
}
};
registerReceiver(myBroadcastReceiver, new IntentFilter("com.alarm.example"));
myPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.alarm.example"),0);
alarmManager = (AlarmManager)(this.getSystemService(Context.ALARM_SERVICE));
}
private void UnregisterAlarmBroadcast()
{
alarmManager.cancel(myPendingIntent);
getBaseContext().unregisterReceiver(myBroadcastReceiver);
}
@Override
protected void onDestroy() {
unregisterReceiver(myBroadcastReceiver);
super.onDestroy();
}
}
編輯:
如果能在App取決於用戶輸入動態地改變的時間,那麼就改日曆燒製可調整時間的變量。
不*使用'TimerTask'來做這個。你的過程將在一天之前終止。使用'AlarmManager'。 – CommonsWare
但是我正在動態改變指定的時間並從數據庫中獲取它,當我的警報管理器開始進行活動時,如何獲得新時間。 – zeeali