使用线程处理程序时主线程发生网络错误

问题描述 投票:0回答:1

我有一个打开线程的活动,我在线程中设置了一个处理程序,我使用该处理程序将消息发送到线程并根据这些消息采取行动。当我的处理程序不得不发出网络操作时,我在主线程异常上得到了网络...

我的问题是,如果我在从活动打开的新线程内的处理程序中,为什么我会在主线程异常上得到网络。

我的线程代码:

public Handler nHandler = new Handler(Looper.myLooper()) {
    @Override
    public void handleMessage(Message inputMessage) {
        switch (inputMessage.what) {
            case (SignalProtocol.MSG_INVITE):{
                mLogger.setMessage("Invite in progress now!");
                JSONObject myMessage = new JSONObject();
                try {
                    myMessage.put("code", SignalProtocol.MSG_INVITE);
                    myMessage.put("player","ddd");
                } catch (JSONException e) { e.printStackTrace();
                    mLogger.setMessage("Could not send invite json Exception");
                }
                out.println(myMessage.toString());
                out.flush();
            }
            default:

        }
        super.handleMessage(inputMessage);
    }
};

public SignalChannel(Handler ac, String userName, String Password) {
    myHandler = ac;
    uname = userName;
    pass = Password;
    mLogger.setActivityName("SignalChannel");
}

我在线程中有运行方法...

我的活动正在像这样调用线程:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_lobby);
    // Set up beacon messages  to inform we are within the lobby
    mLogger.setActivityName("LobbyActivity");
    Intent i = getIntent();
    nickname=i.getStringExtra("Nickname");
    password=i.getStringExtra("Password");
    uid=i.getIntExtra("uid",-1);

    beacon = new KeepAlive();
    beacon.setNickname(nickname);
    beacon.setUid(uid);
    beacon.start();

    final EditText invite=findViewById(R.id.inviteTxt);
    Button inviteBtn=findViewById(R.id.inviteBtn);

    // Set up handler for messages with other players through the server


    mLogger.setMessage("Calling new thread with nick:"+nickname+" And Pass"+password);
    mChannel= new SignalChannel(UpdateUI,nickname,password);
    mChannel.start();

并将消息发送到此处的线程处理程序:

inviteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String player2 = invite.getText().toString();
                mLogger.setMessage("Inviting "+player2);
                Message message = new Message();
                message.what = SignalProtocol.MSG_INVITE;
                mChannel.nHandler.sendMessage(message);
            }
        });

我不明白为什么当线程内部的处理程序尝试在我的套接字上发送消息时,它在主线程上得到错误网络信息。

android multithreading sockets networking handler
1个回答
0
投票

创建AppExecutors.java文件

public class AppExecutors {

private static final int THREAD_COUNT = 3;

private final Executor diskIO;

private final Executor networkIO;

private final Executor mainThread;

private AppExecutors(Executor diskIO, Executor networkIO, Executor mainThread) {
    this.diskIO = diskIO;
    this.networkIO = networkIO;
    this.mainThread = mainThread;
}

public AppExecutors() {
    this(Executors.newSingleThreadExecutor(), Executors.newFixedThreadPool(THREAD_COUNT),
            new MainThreadExecutor());
}

public Executor diskIO() {
    return diskIO;
}

public Executor networkIO() {
    return networkIO;
}

public Executor mainThread() {
    return mainThread;
}

private static class MainThreadExecutor implements Executor {
    private final Handler mainThreadHandler = new Handler(Looper.getMainLooper());

    @Override
    public void execute(@NonNull Runnable command) {
        mainThreadHandler.post(command);
    }
}
}

然后像这样在网络线程中编写代码

 New AppExecutors().networkIO().execute(object: Runnable {
        override fun run() {
    //write your code here
}
}
© www.soinside.com 2019 - 2024. All rights reserved.