0

我阅读了很多教程,但没有解决方案。我想使用 AlarmManager 进行同步。当我选择系统中当前时间的“after15Minutes”复选框警报时(如何在数据库中保存该特定时间。在数据库中保存时间是否重要?)并每 15 分钟刷新一次列表。我不知道如何将复选框值与警报绑定以及如何使其成为可能。完全卡住了。

我的代码:

  private final class syncOkClickListener implements DialogInterface.OnClickListener
{
    public void onClick(DialogInterface dialog, int which) 
    {   //Implement search method here
        if(after15mint.isChecked())
        {
            // Some code!!! or Alarm Manager !!!
        //  Toast.makeText(getApplicationContext(), "15 Minute checked", Toast.LENGTH_LONG).show();
        }
        else
        {
            Toast.makeText(getApplicationContext(), "Default", Toast.LENGTH_LONG).show();
        }
    }

广播接收器活动:

 public class BroadCastReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub


}
public void SetAlarm(Context context)
{
    AlarmManager alarmManager = (AlarmManager)context.getSystemService(context.ALARM_SERVICE);
    Intent syncIntent = new Intent(context, BroadCastReceiver.class);
    syncIntent.putExtra("sync", 0);
    PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, syncIntent, 0);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000*20, pIntent);
}
public void CancelAlarm(Context context)
{
    Intent intent = new Intent(context, BroadCastReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(sender);
}

}

任何建议都会有所帮助。谢谢你。

4

1 回答 1

0

您可以在 onClick 代码中设置闹钟:

    public void onClick(DialogInterface dialog, int which) 
{   //Implement search method here
    if(after15mint.isChecked())
    {
        // Create alarm intent.
        Intent intent = new Intent(this, BroadCastReceiver.class);
        PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);

        // Schedule alarm.
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.MINUTE, 15);
        AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
    }
    else
    {
        Toast.makeText(getApplicationContext(), "Default", Toast.LENGTH_LONG).show();
    }
}

您无需将闹钟时间保存在自己的数据库中。

关于您阅读的许多没有帮助的教程,一个很好的起点是 Android SDK 的 ApiDemos,您将在 ApiDemos/App/Alarm/AlarmController 中找到工作代码,该代码实现单次警报和重复警报。

于 2013-04-22T15:37:30.357 回答