Android的 - 运行定期使用postDelayed()的方法调用 [英] Android - running a method periodically using postDelayed() call

查看:411
本文介绍了Android的 - 运行定期使用postDelayed()的方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,一个Android应用程序,我想开始一个网络活动(发送一些数据),它应该运行的每一秒。我做到这一点,如下所示:

I have a situation in an Android app where I want to start a network activity (sending out some data) which should run every second. I achieve this as follows:

的onCreate()我有code:

tv = new TextView(this);
tv.postDelayed(sendData, 1000);

送出数据()功能:

   Handler handler = new Handler();
   private Runnable sendData=new Runnable(){
    public void run(){
        try {
            //prepare and send the data here..
            handler.removeCallbacks(sendData);
            handler.postDelayed(sendData, 1000);    
        }
        catch (Exception e) {
            e.printStackTrace();
        }   
    }
};

问题进来是这样的:当用户presses的后退按钮和app出来(UI消失)的送出数据()功能仍然得到执行,这是我想要的是。现在,当用户重新启动应用,我的的onCreate()被再次打来电话,我得到送出数据()调用两次一秒。它继续这样。每次用户出来并重新开始,多了一个送出数据()每秒发生。

The problem come in like this: When user presses the back buttons and app comes out (UI disappears) the sendData() function still gets executed which is what I want. Now when user re-starts the app, my onCreate() gets called again and I get sendData() invoked twice a second. It goes on like that. Every time user comes out and starts again, one more sendData() per second happens.

我是什么做错了吗?这是我的新处理器()创建问题?什么是处理这一问题的最佳方法是什么?我想每秒一个送出数据()呼叫,直到用户退出应用程序(表格应用程序管理器)

What am I doing wrong? Is it my new Handler() creating problem? What is the best way to handle this? I want one sendData() call per second until user quits the app (form application manager)

感谢您阅读这整个事情! (太长了一点,不好意思ABT的)

Thanks for reading this entire thing! (a bit too long, sorry abt that)

推荐答案

你为什么不创建服务,并把逻辑的onCreate()。在即使你preSS后退按钮服务将继续执行这种情况下。一旦你进入应用程序,它将不会调用 的onCreate()了。相反,它会调用 ONSTART()

Why don't you create service and put logic in onCreate(). In this case even if you press back button service will keep on executing. and once you enter into application it will not call onCreate() again. Rather it will call onStart()

这篇关于Android的 - 运行定期使用postDelayed()的方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆