Ada beberapa contoh bagus dalam kode contoh android
. \ android-sdk \ samples \ android-10 \ ApiDemos \ src \ com \ example \ android \ apis \ app
Yang harus diperiksa adalah:
- AlarmController.java
- OneShotAlarm.java
Pertama, Anda memerlukan penerima, sesuatu yang dapat mendengarkan alarm Anda saat dipicu. Tambahkan berikut ini ke file AndroidManifest.xml Anda
<receiver android:name=".MyAlarmReceiver" />
Kemudian, buat kelas berikut
public class MyAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm went off", Toast.LENGTH_SHORT).show();
}
}
Kemudian, untuk memicu alarm, gunakan yang berikut (misalnya dalam aktivitas utama Anda):
AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MyAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
time.add(Calendar.SECOND, 30);
alarmMgr.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pendingIntent);
.
Atau, lebih baik lagi, buat kelas yang menangani semuanya dan gunakan seperti ini
Bundle bundle = new Bundle();
MyAlarm alarm = new MyAlarm(this, bundle, 30);
dengan cara ini, Anda memiliki semuanya di satu tempat (jangan lupa untuk mengedit AndroidManifest.xml
)
public class MyAlarm extends BroadcastReceiver {
private final String REMINDER_BUNDLE = "MyReminderBundle";
public MyAlarm(){ }
public MyAlarm(Context context, Bundle extras, int timeoutInSeconds){
AlarmManager alarmMgr =
(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, MyAlarm.class);
intent.putExtra(REMINDER_BUNDLE, extras);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
time.add(Calendar.SECOND, timeoutInSeconds);
alarmMgr.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(),
pendingIntent);
}
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm went off", Toast.LENGTH_SHORT).show();
}
}