[英]Start AlarmManager on button click
I want to start an AlarManager when a button is pressed. 我想在按下按钮时启动AlarManager。 The problem is: The AM starts when I start the app :/ 问题是:我启动应用程序时AM开始:/
My Code: 我的代码:
public void scheduleAlarm()
{
int time = 10 * 1000;
intentAlarm = new Intent(this, AlarmReciever.class);
alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, time, time, PendingIntent.getBroadcast(this,1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
}
And I try to call this in a onClickListener of a button. 我尝试在按钮的onClickListener中调用它。 But it starts from beginning of activity :/ 但这是从活动开始开始的:/
Can anyone help me? 谁能帮我?
thanks for posting your code. 感谢您发布代码。 Try this: 尝试这个:
public static String ALARM_TO_SET = "ALRMTOSEND";
yourButton.setOnClickListener(new OnClickListener(){
public void onClick(View view){
int time = 10 * 1000;
intentAlarm = new Intent(ALARM_TO_SET);
alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, intentAlarm, 0)
alarm.setRepeating(AlarmManager.RTC_WAKEUP, time, time, pIntent);
}
});
Your Broadcast receiver should be registered in the Manifest.xml file as: 您的广播接收器应在Manifest.xml文件中注册为:
<receiver android:name=".AlarmRecieverClass">
<intent-filter>
<action android:name="ALRMTOSEND" />
</intent-filter>
</receiver>
你应该移动setRepeating
电话里面onClickListener
方法
为什么不为此使用timerTask。
Try this: 尝试这个:
Button yourButton = (Button)findViewById(R.id.yourId);
yourButton.setOnClickListener(new OnClickListener(){
public void onClick(View view){
int time = 10 * 1000;
intentAlarm = new Intent(this, AlarmReciever.class);
alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, time, time, PendingIntent.getBroadcast(this,1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.