I'm performing a check of internet access in a program. I'd like to do a function to that cause this checking need to often happens... But my original function have to return while it because the screen need to refresh. This is what I ha开发者_JAVA技巧ve:
public void isOnline(Runnable Rcallback, Ccallback) {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
boolean checkState = cm.getActiveNetworkInfo().isConnectedOrConnecting();
if(checkState) {
isOnline = true;
if(Rcallback != null) Rcallback.run();
if(Ccallback != null) set;}
else {
isOnline = false;
Toast.makeText(gMain.this, R.string.nointernet, Toast.LENGTH_LONG).show();
Handler reTry = new Handler();
reTry.postDelayed(new Runnable() {
@Override
public void run() {
isOnline(callback) ;
}
},3000);
}
}
My really problem is in Ccallback that it's a function to call back when the program turns online. I don't know how to declare a function as a "variable". Any ideas?
You should setup a listener using the Observer Pattern. This will allow you to tell anyone marked as a listener (likely your UI) that you have done something. In this case, something is connected.
One thing to keep in mind while doing this is to ensure that while doing things on the UI, you are on the Event Thread.
精彩评论