2012-04-01 63 views
1

周期性的闹钟在我的应用程序,我需要一个行添加到一个数据库,并同时放设置了一个报警事件每天都重复在数据库列的一个指定的时间。我已经有了一些代码,但它在指定的时间触发了闹钟事件。这里是我的代码:安卓:建立与AlarmManager

public class Add_reminder extends Activity { 
    AlarmManager am; 
    int hours, minutes; 
    REMIND_DB db; 
    Calendar calendar; 
    Cursor cursor; 
    Button button; 

    public void onCreate(Bundle savedInstanceState) { 
     //The usual code in the beginning of onCreate 

     //I load db from extended Application class as global since i use it in more 
     //Activities. Ints hours and minutes is set by user interaction 

     calendar = Calendar.getInstance(); 
     am = (AlarmManager) getSystemService(ALARM_SERVICE); 

     button.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       db.open(); 
       db.insertReminder(-- parameters for database --); 
       cursor = db.getAllReminders(); 
       cursor.moveToLast(); 
       calendar.set(Calendar.HOUR, hours); 
       calendar.set(Calendar.MINUTE, minutes); 
       Intent intent = new Intent(Add_reminder.this, ReminderAlarm.class); 
       intent.putExtra("id_of_db_row", cursor.getInt(0)); 
       PendingIntent pi = PendingIntent.getActivity(Add_reminder.this, 
        cursor.getInt(0), intent, PendingIntent.FLAG_CANCEL_CURRENT); 
       am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 
        24*3600*1000, pi); 
       db.close() 
      } 
     }); 
    } 
} 

数据库正确更新,但绝不ReminderActivity开始于指定的时间。我不知道什么是错的。我看到一些使用BroadcastReceiver的示例代码,而不是使用PendingIntent启动Activity,但这也应该可以,对吧?有谁知道什么可能是错的?

我的第二个问题是,如果我要去需要AlarmManager的同一个实例时,我想从一个不同的活动添加或删除某些报警,还是我只是声明另一个AlarmManager在每一个活动,我需要?

谢谢!

回答

1

您应该使用的广播接收器的报警,然后启动,做实际工作的服务。广播接收器不应该用很长的操作阻塞UI线程(例如写入数据库)。此外,“每日一次”警报可能会产生问题:如果用户重新启动电话:注册的警报将会丢失。您需要:

  • 保存报警应该运行,比如说时间,SharedPreferecnes
  • ,然后重新注册报警时手机启动(接收BOOT_COMPLETED广播)
  • 不使用setRepeating()但让每个闹钟注册下一个

使用较短的时间(1或2分钟)进行测试也有帮助。

对于AlarmManager例如,它是一个系统服务,你不需要关心你所使用的实例。刚开始使用getSystemService()

+0

得到它当我看到我的手机今天上午,我注意到,所需的活动开始!看起来问题在于我为它设置的时间(而不是24格式使用HOUR_OF_DAY,我使用HOUR格式为12格式,因此提醒会在12小时后提醒自己)。我的主要活动中有一段代码,在活动启动后只执行一次。我可以使用数据库中的数据在那里重新注册我的警报吗?如果用户只重新启动应用程序,而不是电话本身,它会替代我的警报吗?或者它会重复。谢谢。 – 2012-04-02 07:10:08

+0

进步:)尽管如此,让活动从不知不觉中跳出来是一个糟糕的主意。正如我所说的,使用广播接收器和服务。如果您需要用户交互,请发布通知并让用户开始活动。如果使用等价的PendingIntent,则报警将被覆盖,而不是重复。 – 2012-04-02 07:22:31

+0

一个很好的帮助,谢谢:)我将使用BroadcastReceiver,因为你说,这个时间问题只是更直接:) – 2012-04-02 07:41:22