当我去另一个活动时如何停止timer.schedule

时间:2015-11-08 09:07:53

标签: java android

我已按照This link在我的项目中实施Volley。我有相同的“AppController”类。它工作正常。 现在我想每隔5分钟打电话给服务器,所以我写了下面的

Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        public void run() {

            try {

                JSONObject json = new JSONObject();

                json.put("SomeData1", "SomeData1Value");
                json.put("SomeData2", "SomeData2Value");
                JsonObjectRequest j = new JsonObjectRequest("SomeUrl", json,
                        responseSaveTokenJson(), genericErrorListener());
                AppController.getInstance().addToRequestQueue(j);

            } catch (Exception e) {
                // TODO: handle exception
            }
        }
}, 0, 5000);
private Response.ErrorListener genericErrorListener() {
    return new ErrorListener() {

        public void onErrorResponse(VolleyError error) {

            try {
                Toast.makeText(getApplicationContext(),
                        "Code :" + error.networkResponse.statusCode + "\nNetwork Error\nPlease Try AgainH",
                        Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "No internet connection availableH\n" + error.getMessage(),
                        Toast.LENGTH_LONG).show();
            }
        }

    };
}

private Response.Listener<JSONObject> responseSaveTokenJson() {
    return new Response.Listener<JSONObject>() {

        public void onResponse(JSONObject response) {
            Toast.makeText(HomeActivity.this, "RH", Toast.LENGTH_SHORT).show();

        }
    };
}

如您所知,如果请求成功,则会显示“RH”的祝酒词。

它可以找到 现在我通过做一些事情去另一个活动

Intent intent = new Intent(getApplicationContext(), SomeActivity.class);
                startActivity(intent);
                finish();

该应用程序显示其他活动,但问题是“每隔5秒钟它也会”烤“RH”

如何阻止它烘烤(如何停止该计时器)

1 个答案:

答案 0 :(得分:2)

Intent intent = new Intent(getApplicationContext(), SomeActivity.class);
                startActivity(intent);
timer.cancel();
                finish();