2012-03-31 117 views
1

我的应用程序中有一个数据库,其中存储了类似提醒的内容。其中一列是提醒应该被“提醒”的时间的字符串表示,如下所示:hh:mm。我在我的主要活动中创建一个线程,以定期监视所有提醒,并检查是否设置闹钟的时间。在我修改这个线程之前,我将所有数据库行的时间+ ID加载到一个ArrayList中,并且在我的线程中处理这个ArrayList,而不是数据库本身(我遇到了一些问题)。总之,这里是代码:Android:使用线程在指定时间执行某些操作

首先,我声明使用应用类全局变量:

public class MyApplication extends Application { 
    public ArrayList<String> reminders = new ArrayList<String>(); 
    public int hour; 
    public int minute; 
} 

在我的主要活动:

public class Home extends Activity { 

    ArrayList<String> reminders; 
    String time: 
    int hour; 
    int minute; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     //The usual code at the beginning of onCreate method 

     //I load my global variables 
     MyApplication appState = ((MyApplication)getApplicationContext()); 
     reminders = appState.reminders; 
     hour = appState.hour; 
     minute = appState.minute; 

     //I save curren time into global variables 
     Calendar c = Calendar.getInstance(); 
     hour = c.get(Calendar.HOUR); 
     minute = c.get(Calendar.MINUTE); 

     //I loop over all rows of database and save what I need from them into 
     //Strings in ArrayList reminders. I do this only once on Application 
     //launch to load already existing rows. When the application runs 
     //I can always add or remove existing rows using special Activity 

     //I create and start my Thread 
     Thread t = new Thread() { 
      try { 
       while (true) { 
        time = hour + ":" + minute; 
        if (reminders.size() > 0) { 
         for (int i = 0; i < reminders.size(); i++) { 
          if (reminders.get(i).contains(time)) { 
           //One of the Strings in ArrayList reminders 
           //contains String representation of current 
           //time (along with the ID of database row). 
           //Here I will probably be starting a new 
           //Activity 
          } 
         } 
        } 
        minute++; 
        if (minute == 60) { 
         minute = 0; 
         hour++; 
        } 
        if (hour == 24) { 
         hour = 0; 
        } 
        sleep(1000); 
       } 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
     t.start(); 
    } 
} 

这似乎是工作正常,但我对这个解决方案很不舒服。我的第一个问题是,如果有什么方法来改进这个代码?我是否可以在线程本身中创建我的变量int小时,int分钟和ArrayList提醒,然后在线程循环序列之前加载提醒内容?这样我就不必使用Application类来存储变量,但我需要它们是全局的,即使在我的应用程序中启动新的Activity并需要正确存储这些变量时,Thread也需要运行。

我的第二个问题,如果有一些完全不同的方法来处理这个,你会建议。

非常感谢!


我想添加一些东西给我的问题。因为我会使用AlarmManager,所以我需要在多个活动中设置重复事件。所以我的问题是,我应该在每个活动中使用不同的AlarmManager实例来添加或移除事件,还是应该使用全局声明的同一个实例?谢谢。

回答

3

AlarmManager是定期执行任务的更好选择,例如检查“提醒”表并在必要时提醒用户。原因是当CPU进入睡眠状态时线程不会运行。如果你想让你的线程保持清醒状态,那么你需要一个WakeLock,并且这将会耗费大量的电力。 AlarmManager为此进行了优化。

其次,你不需要全局变量。所以请不要扩展应用程序。这不是必需的。

+0

不知道wakelock。我知道AlarmManager,但我决定采用线程解决方案,因为我知道它来自Java的PC。无论如何,我现在使用AlarmManager,谢谢:) – 2012-03-31 07:45:31

相关问题