"不幸的是应用程序停止了#34;由于NetworkOnMainThreadException

时间:2015-09-03 13:32:54

标签: java android

在我的MainActivity顶部,我做了:

private static final int MY_DATA_CHECK_CODE = 0;
public static MainActivity currentActivity;
TextToSpeech mTts;
private String targetURL;
private String urlParameters;
private Button btnClick;
private String clicking = "clicked";
private String[] ipaddresses = new String[]{
private String iptouse = "";
private TextView text;
private boolean connectedtoipsuccess = false;
private int counter = 0;
private NotificationCompat.Builder mbuilder;
private Timer timer = new Timer();
private TextView text1, text2, text3;
private Button startButton;
private Button pauseButton;
private TextView timerValue;
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeSwapBuff = 0L;
private int servercheckCounter = 0;
private byte[] checkServer = null;
private boolean connectedSuccess = false;

然后在onCreate里面我做了:

startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread,0);

然后在updateTimerThread中我做了:

private Runnable updateTimerThread = new Runnable() {
    public void run() {
        long updatedTime = 0L;
        long timeInMilliseconds = 0L;
        timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
        updatedTime = timeSwapBuff + timeInMilliseconds;
        servercheckCounter +=1 ;
        if (servercheckCounter == 10) {
            if(connectedSuccess == true) {
                checkServer = Get(iptouse + "result"); 
                if (checkServer != null) {
                    String a = null;
                    try {
                        a = new String(checkServer, "UTF-8");
                        textforthespeacch = a;
                        MainActivity.currentActivity.initTTS();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }
            servercheckCounter = 0;
        }
        int secs = (int) (updatedTime / 1000);
        int mins = secs / 60;
        secs = secs % 60;
        int milliseconds = (int) (updatedTime % 1000);
        timerValue.setText("" + mins + ":" + String.format("%02d", secs) + ":" + String.format("%03d", milliseconds) + " counter: " + String.format("%01d",servercheckCounter));
        customHandler.postDelayed(this, 100);
    }
};

计时器正在运行,没有停止,我每隔一秒就会发送一个命令给我在PC上的Web服务器,这是发送命令的计时器线程中的一行:

checkServer = Get(iptouse + "result");

Get方法是:

private byte[] Get(String urlIn) {
    URL url = null;
    String urlStr = urlIn;
    if (urlIn != null)
        urlStr=urlIn;

    try {
        url = new URL(urlStr);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    }
    HttpURLConnection urlConnection = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        byte[] buf=new byte[10*1024];
        int szRead = in.read(buf); 
        byte[] bufOut;
        if (szRead==10*1024) {
            throw new AndroidRuntimeException("the returned data is bigger than 10*1024.. we don't handle it..");
        } else {
            bufOut = Arrays.copyOf(buf, szRead);
        }

        return bufOut;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        if (urlConnection!=null)
            urlConnection.disconnect();
    }
}

我试图做的是每秒向我的电脑上的网络服务器发送一个命令,如果/当网络服务器上发生某些事情时,它会向客户端返回一个值,而java是客户端。

问题是在完成这一行之后:

checkServer = Get(iptouse + "result");

一次或两次它在Android设备屏幕上抛出错误。 我试图调试它,但我找不到确切的位置,原因以及如何解决问题。

我在线上的Get方法中添加了一个断点:

InputStream in = new BufferedInputStream(urlConnection.getInputStream());

它在这一行停止此行然后当我继续有时它再次停在此行时有时会在一次抛出错误后抛出错误。

我在更多地方使用我的程序向网络服务器发送命令,它只在我试图每秒发送一个命令的地方工作正常

我想做的事情就是我认为的游泳池。

也许问题是我每秒都发送一个命令而Get方法因为它太快而无法处理它?<​​/ p>

问题是它没有停在Get方法中的任何捕获位置。

这是来自logcat的错误消息:

09-03 17:16:46.476  17224-17224/com.test.webservertest E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.adilipman.webservertest, PID: 17224, android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:249)
at libcore.io.IoBridge.recvfrom(IoBridge.java:553)
at java.net.PlainSocketImpl.read(PlainSocketImpl.java:485)
at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:37)
at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:237)
at com.android.okio.Okio$2.read(Okio.java:113)
at com.android.okio.RealBufferedSource.indexOf(RealBufferedSource.java:147)
at com.android.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:94)
at com.android.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:175)
at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:101)
at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:616)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:379)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:190)
at com.adilipman.webservertest.MainActivity.Get(MainActivity.java:582)
at com.adilipman.webservertest.MainActivity.access$700(MainActivity.java:72)
at com.adilipman.webservertest.MainActivity$3.run(MainActivity.java:188)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5274)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)

1 个答案:

答案 0 :(得分:0)

应用程序尝试在其主线程上执行网络操作时引发的异常。这仅适用于针对Honeycomb SDK或更高版本的应用程序,因为早期的SDK确实支持主线程上的网络。您可以使用StrictMode进行阻止,如下所示:

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build());
}

然而,这是非常气馁的,您应该始终使用AsyncTask进行网络任务。