如何在Android中停止Handler [英] How to stop Handler in Android
问题描述
在我的应用程序中,我使用Gridview创建了一个日历,并且在该Gridview中,我借助Imageview显示了日期和一些事件的可用性,并为此创建了一个处理程序.
In my application I have created a calendar with Gridview and in that Gridview I am displaying dates and some availability of events with the help of Imageview and to do this I have created a handler.
现在我要停止处理程序.
Now I want to stop the handler.
MainActivity.java
// inside oncreate
Handler handler = new Handler();
refreshCalendar();
// outside oncreate
public void refreshCalendar() {
calAdapter.refreshDays();
calAdapter.notifyDataSetChanged();
handler.post(calendarUpdater);
calTitle.setText(android.text.format.DateFormat.format("MMMM yyyy", cal));
}
public Runnable calendarUpdater = new Runnable() {
@Override
public void run() {
items.clear();
allData = new ArrayList<HashMap<String,String>>();
allData.clear();
allData = db.showAllEvents();
String currentDate = (String)android.text.format.DateFormat.format("MM/yyyy", cal);
for(int i=0; i<allData.size(); i++)
{
String date[] = allData.get(i).get("date").split("/");
String md[] = currentDate.split("/");
if(date[1].equals(md[0]) && date[2].equals(md[1]))
{
items.add(date[0]);
System.out.println("dates: "+date[0]);
}
}
calAdapter.setItems(items);
calAdapter.notifyDataSetChanged();
}
};
请告诉我如何以及在何处禁用此线程.
Please tell me how and where I should disable this thread.
推荐答案
您可以使用它来停止可运行的
You can use this to stop that runnable
handler.removeCallbacks(calendarUpdater);
removeCallbacks(Runnable r):删除消息队列中所有 Runnable r
的待处理帖子.
removeCallbacks(Runnable r) :Remove any pending posts of Runnable r
that are in the message queue.
修改
您可以像这样组织代码
在 MainActivity.java
Handler handler = new Handler();
refreshCalendar()
//outside oncreate
public void refreshCalendar() {
calAdapter.refreshDays();
calAdapter.notifyDataSetChanged();
startRepeatingTask();
calTitle.setText(android.text.format.DateFormat.format("MMMM yyyy", cal));
}
public Runnable calendarUpdater = new Runnable() {
@Override
public void run() {
items.clear();
allData = new ArrayList<HashMap<String,String>>();
allData.clear();
allData = db.showAllEvents();
String currentDate = (String)android.text.format.DateFormat.format("MM/yyyy", cal);
for(int i=0; i<allData.size(); i++)
{
String date[] = allData.get(i).get("date").split("/");
String md[] = currentDate.split("/");
if(date[1].equals(md[0]) && date[2].equals(md[1]))
{
items.add(date[0]);
System.out.println("dates: "+date[0]);
}
}
calAdapter.setItems(items);
calAdapter.notifyDataSetChanged();
handler.postDelayed(calendarUpdater,5000); // 5 seconds
}
};
void startRepeatingTask()
{
calendarUpdater.run();
}
void stopRepeatingTask()
{
handler.removeCallbacks(calendarUpdater);
}
现在,您只需调用 startRepeatingTask()
即可发布消息并停止使用 stopRepeatingTask()
Now you can just call startRepeatingTask()
to posting message and to stop use stopRepeatingTask()
继承自以下链接
这篇关于如何在Android中停止Handler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!