0
    public class SocketThread {

private boolean connect = false;
private String ip = "*********";
private int port = ****;
private Socket socket;
private SocketAsync socketAsync;

public SocketThread() {
    socketAsync = new SocketAsync();
    socketAsync.execute();
}

public void setMessenger(SocketServiceMessenger messenger) {
    this.socketServiceMessenger = messenger;
}

public void setConnectFlag(boolean connect) {
    this.connect = connect;
}

public void sentData(JSONObject json) {
    socketAsync.sentData2(json);
}

private class SocketAsync extends AsyncTask<Void, Void, String> {

    private PrintWriter printWriter;

    @Override
    protected String doInBackground(Void... params) {
        String msgStr;
        String type;
        try {
            socket = new Socket(InetAddress.getByName(ip),port);
            OutputStreamWriter streamOut = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
            printWriter = new PrintWriter(streamOut);
            streamOut.flush();
            BufferedReader streamIn = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
            while(socket.isConnected()) {
                msgStr = streamIn.readLine();
                System.out.println(msgStr);
                if(!connect) {
                    socket.close();
                }
            }
            System.out.println("SocketDisconnected");
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return null;
    }

    public void sentData2(JSONObject json) {
        if(socket.isConnected()) {
            printWriter.println(json.toString());
            printWriter.flush();
            System.out.println("OUT : " + json);
        }
    }

}

I get android.os.NetworkOnMainThreadException when call sentData()

Now I use

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

to resolve the problem, but I want to know how to use asynctask in true way.

This code is for online game that receive message from server in realtime and it can also sent message to server from some activity by calling sentData().


Resolve

Example: Android bi-directional network socket using AsyncTask

Community
  • 1
  • 1
Tanggyxyz
  • 11
  • 2

3 Answers3

0

You should set the class to be public and no outer class needed.

    public class SocketAsync extends AsyncTask<String, String, String> {

        private PrintWriter printWriter;

        @Override
        protected String doInBackground(String... params) {
            //You do things here.
        }
    }

This is how you set up the class and in the Activity class, you simply call this by code like :

new SocketAsync(this).execute(/*Put parameters here.*/);

Hope this will help.

yoyosir
  • 458
  • 2
  • 11
  • 27
0

The method SocketAsync.sentData2() calls socket.isConnected(). This is being called on the main thread because something calls SocketThread.sendData2() on the main thread.

Code executes on the thread it is called from. Just because you put that code in your AsyncTask class does not mean it will be on a background thread. Only the code in doInBackground() is guaranteed to be executed in the background, because the Android framework takes care to call that method from a background thread. If you called it yourself, it would execute on whatever thread called it. sentData2() is no different.

Karakuri
  • 38,365
  • 12
  • 84
  • 104
0

You are using Asynctask wrong. When you call the execute method the doInBackground is called which runs on a different thread. You use the onPostExecute method from AsyncTask to get your data back to the main thread (a kind of callback method). This method runs on the main ui thread.

The sendData method would require a new AsyncTask, with a new doInbackground and a new call to execute.

Arno van Lieshout
  • 1,570
  • 1
  • 13
  • 19