java manager 如何使用_java - Android:如何使用AlarmManager

android示例代码中有一些很好的例子

\ Android的SDK\样品\机器人-10\ ApiDemos\ SRC \ COM\示例\机器人\的API\应用

要检查的是:

AlarmController.java

OneShotAlarm.java

首先,你需要一个接收器,它可以在触发时听到你的警报。 将以下内容添加到AndroidManifest.xml文件中

然后,创建以下类

public class MyAlarmReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

Toast.makeText(context, "Alarm went off", Toast.LENGTH_SHORT).show();

}

}

然后,要触发警报,请使用以下内容(例如,在您的主要活动中):

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);

或者,更好的是,创建一个处理它的类,并像这样使用它

Bundle bundle = new Bundle();

// add extras here..

MyAlarm alarm = new MyAlarm(this, bundle, 30);

这样,你把它放在一个地方(别忘了编辑AndroidManifest.xml)

public class MyAlarm extends BroadcastReceiver {

private final String REMINDER_BUNDLE = "MyReminderBundle";

// this constructor is called by the alarm manager.

public MyAlarm(){ }

// you can use this constructor to create the alarm.

// Just pass in the main activity as the context,

// any extras you'd like to get later when triggered

// and the timeout

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) {

// here you can get the extras you passed in when creating the alarm

//intent.getBundleExtra(REMINDER_BUNDLE));

Toast.makeText(context, "Alarm went off", Toast.LENGTH_SHORT).show();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值