알리미 같은 것을 저장하는 응용 프로그램에 데이터베이스가 있습니다. 열 중 하나는 다음과 같이 미리 알림을 "알림"으로 표시해야하는 시간의 문자열 표현입니다. 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 time, int minute 및 ArrayList 미리 알림을 만들고 Thread 루프 시퀀스 바로 전에 미리 알림 내용을로드 할 수 있습니까? 이 방법을 사용하면 변수를 저장하기 위해 Application 클래스를 사용해야하지만 전역 변수가 필요합니다. 응용 프로그램에서 새 Activityes를 시작할 때 스레드가 실행되어야하고 해당 변수를 올바르게 저장해야합니다.
내 두 번째 질문은 내가 completand 다른 접근 방식이 있다면 당신은 recommand 것입니다.
대단히 감사합니다.
이드는 내 질문에 뭔가를 추가하고 싶습니다. Ill가 AlarmManager를 사용하고 있기 때문에, 하나의 Activity 이상에서 반복되는 이벤트를 설정해야합니다. 그래서 내 질문은, 각 Activity에서 AlarmManager의 다른 인스턴스를 사용하여 이벤트를 추가하거나 제거해야합니까, 아니면 globaly로 선언 될 동일한 인스턴스를 사용해야합니까? 감사.
wakelock에 대해 알지 못했습니다. AlarmManager에 대해 알고 있었지만 PC 용 Java에서 알았 기 때문에 스레드 솔루션을 사용하기로 결정했습니다. 어쨌든, 이제 AlarmManager를 사용하십시오, 감사합니다 :) –