状况:TextView 已经显示 【可以上网】
出错代码:HttpResponse response = client.execute(request);
但是 在 catch 模块 捕获异常信息时 结果为 null null :result = e.getLocalizedMessage() + ” ” + e.getMessage(); 没有异常信息
刚学 android ,不能解决
出错代码:HttpResponse response = client.execute(request);
但是 在 catch 模块 捕获异常信息时 结果为 null null :result = e.getLocalizedMessage() + ” ” + e.getMessage(); 没有异常信息
刚学 android ,不能解决
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); btn = (Button) findViewById(R.id.btnRemote); tv = (TextView) findViewById(R.id.txtRemoteResult); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String result = executeGet(); tv.setText(result); } }); tv.setText(isNetworkAvailable(this)?"可以上网":"不可以上网"); } public String executeGet() { String result = null; BufferedReader reader = null; try { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI("http://www.baidu.com")); HttpResponse response = client.execute(request); reader = new BufferedReader(new InputStreamReader(response .getEntity().getContent())); StringBuffer strBuffer = new StringBuffer(""); String line = null; while ((line = reader.readLine()) != null) { strBuffer.append(line); } result = strBuffer.toString(); } catch (Exception e) { result = e.getLocalizedMessage() + " " + e.getMessage(); e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); reader = null; } catch (IOException e) { e.printStackTrace(); } } } return result; } public static boolean isNetworkAvailable(Context context) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) { } else { //假如仅仅是用来判断网络连接 //则可以使用 cm.getActiveNetworkInfo().isAvailable(); NetworkInfo[] info = cm.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; }
权限配置如下
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" > </uses-permission> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" > </uses-permission> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" > </uses-permission> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" > </uses-permission> <uses-permission android:name="android.permission.INTERNET" > </uses-permission> <uses-permission android:name="android.permission.WAKE_LOCK" > </uses-permission>
解决方案:40分
你在主线程上作网络请求了,它有抛出异常,简单的说,这个异常就是要求你连网操作这类需要「等」的耗时操作,不要在主线程执行(,不然会造成 ANR)。
06-26 00:37:26.925 W/System.err( 1630): android.os.NetworkOnMainThreadException 06-26 00:37:27.195 W/System.err( 1630): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128) 06-26 00:37:27.195 W/System.err( 1630): at java.net.InetAddress.lookupHostByName(InetAddress.java:385) 06-26 00:37:27.195 W/System.err( 1630): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 06-26 00:37:27.195 W/System.err( 1630): at java.net.InetAddress.getAllByName(InetAddress.java:214) 06-26 00:37:27.195 W/System.err( 1630): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137) 06-26 00:37:27.195 W/System.err( 1630): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 06-26 00:37:27.195 W/System.err( 1630): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 06-26 00:37:27.205 W/System.err( 1630): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 06-26 00:37:27.205 W/System.err( 1630): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 06-26 00:37:27.205 W/System.err( 1630): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 06-26 00:37:27.205 W/System.err( 1630): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 06-26 00:37:27.205 W/System.err( 1630): at testxxx.debug.MainActivity.executeGet(MainActivity.java:50) 06-26 00:37:27.205 W/System.err( 1630): at testxxx.debug.MainActivity$1.onClick(MainActivity.java:36) 06-26 00:37:27.205 W/System.err( 1630): at android.view.View.performClick(View.java:4171) 06-26 00:37:27.205 W/System.err( 1630): at android.view.View$PerformClick.run(View.java:17097) 06-26 00:37:27.205 W/System.err( 1630): at android.os.Handler.handleCallback(Handler.java:615) 06-26 00:37:27.205 W/System.err( 1630): at android.os.Handler.dispatchMessage(Handler.java:92) 06-26 00:37:27.205 W/System.err( 1630): at android.os.Looper.loop(Looper.java:137) 06-26 00:37:27.205 W/System.err( 1630): at android.app.ActivityThread.main(ActivityThread.java:4819) 06-26 00:37:27.215 W/System.err( 1630): at java.lang.reflect.Method.invokeNative(Native Method) 06-26 00:37:27.215 W/System.err( 1630): at java.lang.reflect.Method.invoke(Method.java:511) 06-26 00:37:27.215 W/System.err( 1630): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 06-26 00:37:27.215 W/System.err( 1630): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 06-26 00:37:27.215 W/System.err( 1630): at dalvik.system.NativeStart.main(Native Method) 06-26 00:37:27.445 I/XiaomiFirewall( 1210): firewall pkgName:android, result:0
本人把你代码改了一下,为了省麻烦,把 Handler直接设为 static 静态属性,以避免 Handler””s Leak 这种会造成内存泄漏的问题,代码如下:
import android.app.Activity; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.TextView; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; public class MainActivity extends Activity implements View.OnClickListener { private static int MSG_UPDATE_INFO = 100; private static TextView sNetworkMsgTv; private static Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == MSG_UPDATE_INFO) { sNetworkMsgTv.setText((String) msg.obj); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn = (Button) findViewById(R.id.btnRemote); sNetworkMsgTv = (TextView) findViewById(R.id.txtRemoteResult); sNetworkMsgTv.setText(isNetworkAvailable(this) ? "可以上网" : "不可以上网"); btn.setOnClickListener(this); } public String executeGet() { String result = null; BufferedReader reader = null; try { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI("http://www.baidu.com")); HttpResponse response = client.execute(request); reader = new BufferedReader(new InputStreamReader(response .getEntity().getContent())); StringBuffer strBuffer = new StringBuffer(""); String line = null; while ((line = reader.readLine()) != null) { strBuffer.append(line); } result = strBuffer.toString(); } catch (Exception e) { result = e.getLocalizedMessage() + " " + e.getMessage(); e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } public static boolean isNetworkAvailable(Context context) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) { } else { //假如仅仅是用来判断网络连接 //则可以使用 cm.getActiveNetworkInfo().isAvailable(); NetworkInfo[] info = cm.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; } @Override public void onClick(View v) { final int id = v.getId(); if (id == R.id.btnRemote) { new Thread(new Runnable() { @Override public void run() { String result = executeGet(); Message msg = Message.obtain(); msg.what = MSG_UPDATE_INFO; msg.obj = result; mHandler.sendMessage(msg); } }).start(); } } }
附带一提,可以 adb logcat -v time,在按下的一瞬间抓 log 这可以帮你解决很多问题