2012-03-31 155 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

相關問題