如何从后台访问套接字对象到主线程?

时间:2019-07-02 18:38:26

标签: android-studio

我正在尝试访问在后台线程中创建的主线程中的套接字,但是当我尝试在套接字上执行某些任务时,我的应用程序崩溃了,这是我的代码,并且我的应用程序由于套接字对象上的IF_Else而崩溃了或当我尝试在msessegsender类中访问它时。请帮助我,我想在第一次单击按钮时创建套接字连接,在第二次单击按钮时发送消息,并在第三次单击按钮事件时关闭套接字连接。

public class MainActivity extends AppCompatActivity {

    static Socket s;
    Button conn;
    EditText mesg;
    Button send;
    static PrintWriter PW;
    static String msg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        conn = (Button) findViewById(R.id.button);
        send = (Button) findViewById(R.id.button2);
        mesg = (EditText)findViewById(R.id.editText);}
    public void connection(View v) {
        connection c = new connection();
        c.execute();
        if (s.isConnected()) {
        } else
    }
    public void sendmsg(View v){

        messagesender ms = new messagesender();
        ms.execute(mesg.getText().toString());
    }
    class connection extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... voids) {
            try {
                s = new Socket("192.168.xxx.xxx", 11111);

                System.out.println("connected!");

            } catch (IOException e) {
                System.out.println(e);
            }
        return null;
        }
    }
    public class messagesender extends AsyncTask<String,Void,Void>{

        @Override
        protected Void doInBackground(String... Voids) {
            try {

            if(s.isConnected()==true) {
               PW = new PrintWriter(s.getOutputStream());
                PW.write(msg);
                PW.flush();
            }

            }
            catch (IOException e){
                e.printStackTrace();
            }
            return null;
        }
    }
}

0 个答案:

没有答案