1
我有跟隨This link在我的項目中實施Volley。我有相同的「AppController」類。它工作正常。 現在我想每5分鐘後做呼叫服務器,所以我寫了下面的如何停止timer.schedule當我要去另一個活動
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」的祝酒辭。
它的工作原理找到 現在我去到另一個活動由
「每5秒後,‘做以下的事情Intent intent = new Intent(getApplicationContext(), SomeActivity.class);
startActivity(intent);
finish();
的應用會顯示其他活動,但問題是’它也敬酒」 RH
如何從祝酒阻止它(如何停止計時器)
'timer.cancel()'從活動之前出去? –
感謝您的幫助。它的工作 –