--------MyTask工具类---------
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); } }
---------将流转成字符串的工具类----------
public class StreamToStingUtis { public static String streamToString(InputStream stream){ ByteArrayOutputStream outputStream=null; try { outputStream = new ByteArrayOutputStream(); byte[] bytes=new byte[1024]; int len; while ((len=stream.read(bytes))!=-1){ outputStream.write(bytes,0,len); } } catch (IOException e) { e.printStackTrace(); } return outputStream.toString(); }}
--------得到网络状态的工具类-------------
public class NetStateUtil { /* * 判断网络连接是否已开 * true 已打开 false 未打开 * */ public static boolean isConn(Context context){ boolean bisConnFlag=false; ConnectivityManager conManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo network = conManager.getActiveNetworkInfo(); if(network!=null){ bisConnFlag=conManager.getActiveNetworkInfo().isAvailable(); } return bisConnFlag; } /** * 当判断当前手机没有网络时选择是否打开网络设置 * @param context */ public static void showNoNetWorkDlg(final Context context) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setIcon(R.mipmap.ic_launcher) // .setTitle(R.string.app_name) // .setMessage("当前无网络").setPositiveButton("设置", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 跳转到系统的网络设置界面 Intent intent = null; // 先判断当前系统版本 if(android.os.Build.VERSION.SDK_INT > 10){ // 3.0以上 intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS); }else{ intent = new Intent(); intent.setClassName("com.android.settings", "com.android.settings.WirelessSettings"); } context.startActivity(intent); } }).setNegativeButton("知道了", null).show(); } }