-2

In my MainActivity top I did:

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;

Then inside the onCreate i did:

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

Then in the updateTimerThread i did:

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);
    }
};

The timer is running none stop and I did that every second it will send a command to a web server I have on my PC, this is the line in the timer thread that send the command:

checkServer = Get(iptouse + "result");

The method Get is:

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();
    }
}

What i'm trying to do is to send a command every second to the webserver on my pc and if/when something happen on the webserver it will return a value to the client the java is the client.

The problem is that after it's doing this line:

checkServer = Get(iptouse + "result");

Once or twice it's throwing the error on the android device screen. I tried to debug it but i couldn't find the exact place and what cause and how to fix the problem.

I added a break point in the Get method on the line:

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

It's getting to this line stop on this line then when i make continue sometimes it stop on this line again sometimes throw the error sometimes after one time throw the error.

And i'm using my program in more places to send commands to the webserver and it's working fine only in this place where i try to send a command every second it's making the problem.

What i'm trying to do is something called pool i think.

Maybe the problem is that i send a command every second and the method Get can't handle it since it's too fast ?

The thing is that it's not stopping on any of the catch places in the Get method.

This is the error message from the 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)
Anindya Dutta
  • 1,972
  • 2
  • 18
  • 33
Shimrit Hadadi
  • 115
  • 1
  • 12

1 Answers1

0

The exception that is thrown when an application attempts to perform a networking operation on its main thread. This is only thrown for applications targeting the Honeycomb SDK or higher, because earlier SDKs did support networking on the main thread. You can prevent it by using StrictModeas below:

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

However this is highly discouraged and you should always use an AsyncTask for networking tasks.

Anindya Dutta
  • 1,972
  • 2
  • 18
  • 33