Android repeat function Picasso every 2second

时间:2017-04-10 02:49:39

标签: android

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {

            loadImageFromUrl(url);

        }
    }, 2000);
    addTouchlistener();
    addButtonListener();
}

private void loadImageFromUrl(String url) {
    Picasso.with(iv.getContext())
            .load(url)
            .networkPolicy(NetworkPolicy.NO_CACHE, NetworkPolicy.NO_STORE)
            .into(iv);
        }

the "url" is my http server, i will be receiving the .jpg continuously. i want repeat the function every 2s to receive the .jpg

In this case, the first time load the image will be delay 2s but, when i update my photo, it can not show the new photo

i also tried the timer "scheduleAtFixedRate" to repeat but it's not work.

2 个答案:

答案 0 :(得分:0)

因为处理程序只运行您发布一次的内容。它没有反复这样做。为了反复这样做,可运行的需要在最后重新发布。

虽然我建议你不要这样做。你经常改变图像的频率是多少?每隔几分钟?几个小时?每2秒检查一次是荒谬的,你99%的时间都在浪费带宽。使用更长的计时器。更好的是,使用推送消息传递告诉客户端何时重新加载。

答案 1 :(得分:0)

这是我在Fragment中的一个工作示例,但是Activity的逻辑是相同的。 当应用程序进入onPause()时,我提供了额外的代码来关闭下载。

protected Handler programacionTimer;
protected Runnable programacionRunnable;

....

@Override
    public void onResume() {
        super.onResume();
        if (programacionTimer == null) {
                programacionTimer = new Handler();
        }

        if (programacionRunnable == null) {
           programacionRunnable = new Runnable() {
                    @Override
                    public void run() {

                            //Here what you to do (download the image)

                            programacionTimer.postDelayed(this, 2000);

                    }

           };
       }

       programacionTimer.postDelayed(programacionRunnable, 2000);

}


 @Override
    public void onPause() {
        super.onPause();

        programacionTimer.removeCallbacks(programacionRunnable);
        programacionRunnable = null;
    }