Android 在 TimerTask 条件后切换视图
我想建立一些条件来在 X 时间后将用户踢出活动。
我的总体思路是:
- 以毫秒为单位存储当前时间,从以毫秒为单位的日历对象
- 确定我希望用户在活动中停留的时间,
- 添加多长时间+存储的当前时间来确定启动关闭的日历时间(以毫秒为单位) 我发现我能找到的最好的“时间监听器”是 TimerTask,实现
- 这
如下:
protected void onPostExecute(Boolean success){
kickout.schedule(new KickoutTask(), 5000);
}
class KickoutTask extends TimerTask {
public void run() {
Looper.prepare();
replaceRootView(getLocalActivityManager().startActivity("myPreviousActivity", new
Intent(this, myPreviousActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView());
Looper.loop();
}
}
是 AsyncTask 的最后部分,计数和“时间监听”确实有效,但是当需要替换 run()
方法中的视图时,应用程序会崩溃,并显示
“只有创建视图层次结构的原始线程才能触摸其视图” ."
我理解这个概念,但我不明白如何在解析 schedule
函数中的计数后退出此活动。另外,我需要“替换”视图,而不是仅使用“finish()”来完成此活动,因为需要进行一些刷新。
我想使用另一个简单的 AsyncTask,但是 schedule
函数需要 TimerTask
Insight Appreciated
I want to build a few conditions to kick a user out of an activity after X amount of time.
I get the general idea:
- store the current time in milliseconds , from a calendar object in milliseconds
- determine how long I want the user to be in the activity
- add the how long + stored current time to determine what calendar time in milliseconds to boot close that activity
- compare the kickout time to the present time in milliseconds
for the last step I found that the best "time listener" I could find was TimerTask, implemented as such:
protected void onPostExecute(Boolean success){
kickout.schedule(new KickoutTask(), 5000);
}
class KickoutTask extends TimerTask {
public void run() {
Looper.prepare();
replaceRootView(getLocalActivityManager().startActivity("myPreviousActivity", new
Intent(this, myPreviousActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView());
Looper.loop();
}
}
This is at the final part of an AsyncTask, the counting and "time listening" actually works, but when it comes to replace the view in the run()
method, the app crashes with
"Only the original thread that created a view hierarchy can touch its views."
I understand the concept but I don't understand how else to get out of this activity upon resolution of the counting in the schedule
function. Also I need to "replace" the view instead of just using "finish()" for this activity because of some refreshing that needs to take place.
I would like to use another simple AsyncTask, but the schedule
function requires a TimerTask
Insight Appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您应该在 CountDownTimer 中执行此任务
其次,您需要使用 Handler 从其他线程更新视图。
请参阅有关
Handler
和AsyncTask
的教程:http://www.vogella.de/articles/AndroidPerformance/article.html
First you should do this task in CountDownTimer
Second you need to use Handler to update views from other thread.
Refer this tutorial on
Handler
andAsyncTask
:http://www.vogella.de/articles/AndroidPerformance/article.html