Android - running a method periodically using postDelayed() call

前端 未结 8 1328
一向
一向 2020-11-27 13:45

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:

In th

相关标签:
8条回答
  • 2020-11-27 14:17

    Perhaps involve the activity's life-cycle methods to achieve this:

    Handler handler = new Handler();
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          handler.post(sendData);
    }
    
    @Override
    protected void onDestroy() {
          super.onDestroy();
          handler.removeCallbacks(sendData);
    }
    
    
    private final Runnable sendData = new Runnable(){
        public void run(){
            try {
                //prepare and send the data here..
    
    
                handler.postDelayed(this, 1000);    
            }
            catch (Exception e) {
                e.printStackTrace();
            }   
        }
    };
    

    In this approach, if you press back-key on your activity or call finish();, it will also stop the postDelayed callings.

    0 讨论(0)
  • 2020-11-27 14:20

    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()

    0 讨论(0)
  • 2020-11-27 14:22
    Handler h = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==0){
                // do stuff
                h.removeMessages(0);  // clear the handler for those messages with what = 0
                h.sendEmptyMessageDelayed(0, 2000); 
            }
        }
    };
    
    
     h.sendEmptyMessage(0);  
    
    0 讨论(0)
  • 2020-11-27 14:23

    You can simplify the code like this.

    In Java:

    new Handler().postDelayed (() -> {
        //your code here
    }, 1000);
    

    In Kotlin:

    Handler().postDelayed({
       //your code here
    }, 1000)
    
    0 讨论(0)
  • 2020-11-27 14:24

    I think you could experiment with different activity flags, as it sounds like multiple instances.

    "singleTop" "singleTask" "singleInstance"

    Are the ones I would try, they can be defined inside the manifest.

    http://developer.android.com/guide/topics/manifest/activity-element.html

    0 讨论(0)
  • 2020-11-27 14:25

    You should set andrid:allowRetainTaskState="true" to Launch Activity in Manifest.xml. If this Activty is not Launch Activity. you should set android:launchMode="singleTask" at this activity

    0 讨论(0)
提交回复
热议问题