Last active
August 29, 2015 14:00
-
-
Save SemonCat/11177386 to your computer and use it in GitHub Desktop.
CallbackExample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CallbackExample { | |
public interface OnNetworkFinish{ | |
void OnFinish(String Data); | |
void OnFail(); | |
} | |
class GetGoogleData{ | |
List<OnNetworkFinish> mListener; | |
void getGoogleTitle(){ | |
new Thread(new Runnable(){ | |
@Overwrite | |
void run(){ | |
try{ | |
//do something to get network date on nonuithread; | |
... | |
String data = something; | |
//when finish ,callback | |
if (mListener!=null){ | |
for (OnNetworkFinish listener:mListener) | |
listener.OnFinish(data); | |
} | |
}catch (Exception e){ | |
if (mListener!=null){ | |
for (OnNetworkFinish listener:mListener) | |
listener.OnFail(); | |
} | |
} | |
} | |
}).start; | |
} | |
void setListener(OnNetworkFinish listener){ | |
if (mListener==null){ | |
mListener = new ArrayList<OnNetworkFinish>(); | |
} | |
mListener.add(listener); | |
} | |
} | |
GetGoogleData mGetGoogleData; | |
int main(){ | |
mGetGoogleData = new GetGoogleData(); | |
mGetGoogleData.setListener(new OnNetworkFinish{ | |
void OnFinish(String Data){ | |
//this will be call when nonuithread work finish. | |
//do something to data... | |
} | |
void OnFail(){ | |
//do something when get error | |
} | |
}); | |
mGetGoogleData.getGoogleTitle(); | |
} | |
void otherNeed2Notify(){ | |
mGetGoogleData.setListener(new OnNetworkFinish{ | |
void OnFinish(String Data){ | |
//I'm other place. | |
} | |
void OnFail(){ | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment