I found some answer about the difference between onDestroy and finish.
Finish will remove the activity from the stack, but will not free the memory and will not call onDestroy in every time. onDestroy will kill the activity and free the memory.
In my situation: There are 2 activities. A is main activity and B is a activity with some EditText for sending data to server by using Volley.
A -> B -> A
When i sent the data successfully.It will run the finish() to kill B. B is destroyed. But i call B again, all the data still there (content of EditText). Which means the memory haven't clear.
Did anyone face on those issue? There are my code:
public void update(final Context context, final Map<String,String> data,final Activity activity){//pass B
RequestQueue queue = Volley.newRequestQueue(context);
String url = "http://xxxxxxxx";
StringRequest sr = new StringRequest(Request.Method.POST,url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
activity.finish();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//mPostCommentResponse.requestEndedWithError(error);
}
}){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = data;
//data.
//params.put("user",data.get(''));
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
queue.add(sr);
}
UPDATED
Activity B have viewpager and 3 fragment by using FragmentStatePagerAdapter. When i call finish() of B. Those data under the fragments won't clear. I can saw the old data when i start B activity again.
When you call below function:
someActivity.finish(); // This will free the memory, see notes below
It should be noted that all its resources are queued for garbage collection, and all memory that was used by this activity will be freed during next GC cycle.
If you really want to revoke the memory as soon as possible, override your activities' onDestroy method:
@Override
public void onDestroy() {
super.onDestroy();
Runtime.getRuntime().gc(); // notify gc to be called asap
}
Note about Runtime.getRuntime().gc(); this asks the VM to make its best effort to recycle all discarded objects--quoted from http://www.tutorialspoint.com/java/lang/runtime_gc.htm.