非同步訪問介面回撥返回資料
import android.os.AsyncTask;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by jane on 2018/1/5.
*/
public class MyTask extends AsyncTask<String,Void,String> {
//2.申明介面型別變數
private ICallBacks iCallBacks;
//4.傳入實現此介面的類物件
public MyTask(ICallBacks iCallBacks) {
this.iCallBacks = iCallBacks;
}
@Override
protected String doInBackground(String... strings) {
try {
URL url=new URL(strings[0]);
HttpURLConnection connection =(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
if(connection.getResponseCode()==200){
InputStream inputStream = connection.getInputStream();
String s=StreamToStingUtis.streamToString(inputStream);
return s;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//3.呼叫介面
iCallBacks.getJson(s);
//iCallBacks=new MainActivity();
// iCallBacks.getJson(s);
}
//1.定義一個介面
public interface ICallBacks{
void getJson(String json);
}
}