如何以时间间隔更新textview文本(服务器数据)?

时间:2018-03-24 08:08:32

标签: android multithreading service

我希望以5秒的间隔更新Textview文本中的数据。数据应该来自服务器。我以15000毫秒的间隔调用“处理程序”。

由于呼叫处理程序,问题很少见。请告诉我有没有其他进程来更新数据的时间间隔。我发送了以下使用过的代码。

final Handler handler = new Handler();
    Timer timer = new Timer();
    TimerTask doAsynchronousTask = new TimerTask() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    try {
                         if(dataFromLogin.trim().equals("yes"))
                         {
                             checkUrlToFetchData(personLoginName);
                         }
                         else
                         {
                             checkUrlForExtraVideo(latestVideoID);
                             checkUrlToFetchDataCreaterLogin(personLoginName);
                         }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                    }
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask, 0, 15000);  

=============================

void checkUrlToFetchData(final String useridt)
{

    RequestQueue queue = Volley.newRequestQueue(AllItemScreen.this);
    String url = "http://liveapp.99emailmarketing.com/notifications/index";
    StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, url,
            new com.android.volley.Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.v( "response:",response);
                    try {
                        JSONObject jsonObj = new JSONObject(response);
                        boolean success = jsonObj.getBoolean("success");
                        if(success == true)
                        {
                            JSONArray notifications = jsonObj.getJSONArray("notifications");
                            if(notifications.length()>0)
                            {
                                JSONObject jo= notifications.getJSONObject(0);
                                createNotification(jo.getString("message"));
                            }
                        }
                        else
                        {
                            String error = jsonObj.getString("error");
                            Toast.makeText(AllItemScreen.this, error, Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        Log.v( "try:",e.toString());
                    }
                }
            }, new com.android.volley.Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(AllItemScreen.this, "That didn't work!", Toast.LENGTH_SHORT).show();
        }

    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("user_id",userIdfromLogin);
            return params;
        }
    };
    queue.add(stringRequest);
}
void checkUrlToFetchDataCreaterLogin(final String useridt)
{
    //Toast.makeText(this, "Validation Successfull", Toast.LENGTH_LONG).show();
    RequestQueue queue = Volley.newRequestQueue(AllItemScreen.this);
    String url = "http://liveapp.99emailmarketing.com/LiveNotifications/index";

    // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, url,
            new com.android.volley.Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // Display the response string.
                    //progressDialog.dismiss();
                    //Toast.makeText(AllItemScreen.this, "response:"+response, Toast.LENGTH_SHORT).show();

                    Log.v( "response:",response);
                    try {
                        //Log.v( "try:","1");
                        JSONObject jsonObj = new JSONObject(response);
                        boolean success = jsonObj.getBoolean("success");
                        String profileimages="",profileimages1="",profileimages2="",profileimages3="",profileimages4="",profileimages5="";


                        if(success == true)
                        {
                            JSONArray notifications = jsonObj.getJSONArray("LiveNotifications");
                            if(notifications.length()>0)
                            {
                                JSONObject jo= notifications.getJSONObject(0);
                                createNotification(jo.getString("message"));
                            }

                        }
                        else
                        {
                            String error = jsonObj.getString("error");
                            Toast.makeText(AllItemScreen.this, error, Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        Log.v( "try:",e.toString());
                    }
                }
            }, new com.android.volley.Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //progressDialog.dismiss();
            Toast.makeText(AllItemScreen.this, "That didn't work!", Toast.LENGTH_SHORT).show();
        }

    }) {
        //adding parameters to the request
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("user_id",userIdfromLogin);

            return params;
        }
    };
    // Add the request to the RequestQueue.
    queue.add(stringRequest);

}
void checkUrlForExtraVideo(final String checkUrlForExtraVideo)
{

    RequestQueue queue = Volley.newRequestQueue(AllItemScreen.this);
    String url = "http://liveapp.99emailmarketing.com/user-videos/newvideo";

    // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, url,
            new com.android.volley.Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // Display the response string.
                    //progressDialog.dismiss();
                    //Toast.makeText(AllItemScreen.this, "response:"+response, Toast.LENGTH_SHORT).show();

                    Log.v( "response:",response);
                    try {
                        //Log.v( "try:","1");
                        JSONObject jsonObj = new JSONObject(response);
                        boolean success = jsonObj.getBoolean("success");

                        if(success == true)
                        {
                            int newVideo = jsonObj.getInt("newVideo");
                            if(newVideo>0)
                            {
                                getResourceUriRecyclerViewtruenew(swipeRefreshLayout);
                            }
                        }
                        else
                        {
                            String error = jsonObj.getString("error");
                            Toast.makeText(AllItemScreen.this, error, Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        Log.v( "try:",e.toString());
                    }
                }
            }, new com.android.volley.Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //progressDialog.dismiss();
            Toast.makeText(AllItemScreen.this, "That didn't work!", Toast.LENGTH_SHORT).show();
        }

    }) {
        //adding parameters to the request
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("video_id",latestVideoID);
            return params;
        }
    };
    // Add the request to the RequestQueue.
    queue.add(stringRequest);
}

2 个答案:

答案 0 :(得分:0)

如果您想每5秒执行一次任务,可以使用

 Handler handler = new Handler();
 new Runnable()
        {
            @Override
            public void run() {
                //do your task
                handler.postDelayed(this, 5000);
            }
        }.run();

答案 1 :(得分:0)

您可以尝试使用5秒计时器

private Handler mCountdownHandler;

private final static int INTERVAL = 5 * 1000;

private Runnable mTimer = new Runnable() {
    @Override
    public void run() {
        // Do something
        ...
        ...
        // Reschedule the timer to execute after 5 seconds
        mCountdownHandler.postDelayed(this, INTERVAL);
    }
};

private void startTimer() {
    stopTimer();
    mCountdownHandler = new Handler(getMainLooper());
    mCountdownHandler.post(mTimer);
}

private void stopTimer() {
    if (mCountdownHandler != null) {
        mCountdownHandler.removeCallbacks(mTimer);
        mCountdownHandler = null;
    }
}

销毁活动时不要忘记释放处理程序

@Override
protected void onDestroy() {
    super.onDestroy();
    stopTimer();
}