问题
I want to create multiple handler and run-able when my app receive response from server.
The handlers can be maximum 4 and minimum 1.
Problem
Actually i want to divide cell screen in different part and after dividing i need to display different type of data in all parts of the screen. And in these parts, Each part have multiple items to display.
e.g! User want to divide screen in two parts
part one contains a video, image and again a video. (3) item in part one
part two contain image and a video. (2) item in part two.
each item needs to display for a specific time period (user defined)
when the time for one item complete then app needs to display next item in list.
What i have tried
As per my knowledge there is one way to achieve this is that
I need to to create multiple handlers which will take care of all the parts.
i tried to create new handler using a for loop and save it instance but by doing so i am not able to manage that when and which screen part needs to be updated.
Please can anyone tell me how to create any number of handlers dynamically. and save there states.
private void createStreamHandler(){
for(int i=0; i < serverResponse2.vMedialist.size(); i++){
final int index = i;
Handler hadler = new Handler();
hadler.postDelayed(myRunnable = new Runnable() {
public void run() {
if (sDuration[0] <= 0){
// check if wait counter expired? get show next media and gets
// its display duration
sDuration[0] = runPlaylist(serverResponse2.vMedialist.get(index), index);
}
sDuration[0] -= 5;
handler.postDelayed(myRunnable, 5000);
}
}, 500);
streamsHandler.add(hadler);
streamRunnable.add(myRunnable);
}
}
private int runPlaylist(ArrayList<Media2> mediaList, int index){
Log.e("mediaList ", "mediaList size at " + index +" = " + mediaList.size());
return mediaList.get(index).duration;
}
Every time i am getting the size of the last index of the arraylist. and only last handler keep on running. Please Help i am stuck at it.
How can i keep the track of all the handlers??
Is there any other way to do manage handlers.
I hope i have explained the problem well. Please suggest any solution. Thanks.
回答1:
If I correctly understand your code you need to replace
handler.postDelayed(myRunnable, 5000);
with
handler.postDelayed(this, 5000);
because myRunnable
is the latest Runnable that you created. And all your handlers post it instead of themselfs.
EDIT:
You store in each handler it's number - index
. You can add method
void handleResponse(int index, Object someData)
to your class, that creates handlers. After that each handler can call handleResponse(index, data)
to notify about some changes.
来源:https://stackoverflow.com/questions/35443200/create-multiple-handler-based-on-server-response-and-manage-there-states