简体   繁体   中英

I need to use a thread in another android activity that connects to a server

I have an application Android that need to connect to a server, when i try to connect my device in the MainActivity it works, but when i start another activity i need to stay connected and that continue to send data.

MainActivity

            package com.example.clientandroid;

        import java.io.IOException;
        import java.io.ObjectOutputStream;
        import java.io.Serializable;
        import java.net.Socket;

        import android.os.Bundle;
        import android.app.Activity;
        import android.content.Intent;
        import android.view.Menu;
        import android.view.View;
        import android.widget.Button;
        import android.widget.EditText;
        import android.widget.TextView;

        public class MainActivity extends Activity {
            class myRunnable implements Runnable{
                MainActivity mainAct = null;
                String ip = "";
                public myRunnable(MainActivity m, String ip){
                    super();
                    this.mainAct = m;
                    this.ip = ip;
                }
                public void run()
                {
                    try {
                        clientSocket = new Socket(this.ip, 4000);

                        oos = new ObjectOutputStream (clientSocket.getOutputStream());
                        oos.writeUTF(new String("Bye\n"));
                        oos.flush();

                        Intent intent = new Intent(this.mainAct, MouseTestActivity.class);


                        Bundle b = new Bundle();
                        b.putSerializable("OOS", (Serializable) oos);
                        //cerca serializable oos
                        intent.putExtra("OOS", b); //Put your id to your next Intent

                        startActivity(intent);

                    } catch (IOException e) {
                        System.out.println("Eccezione!! "+e);
                        TextView drCuloCane = (TextView) findViewById(R.id.textView1);
                        drCuloCane.setText(drCuloCane.getText()+" "+e.toString());
                    }

                }
            }

            public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
            ObjectOutputStream  oos;
            Socket clientSocket;


            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

            }


            public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.menu.main, menu);
                return true;
            }
            public void sendText(View view){

                EditText user_id = (EditText) findViewById(R.id.editText1);
                final String user_id1 = user_id.getText().toString();

              //parte modificata per connettersi allla premuta del tasto
                final String Text;
                String send = " ";
                Thread m_objThreadClient = new Thread(new myRunnable(this, user_id1));
                //MouseTestActivity mouse = null ;
                //mouse.setThread(m_objThreadClient);
                m_objThreadClient.start();   
            }
        }

and thats is the other activity where i need to use the thread and continue to send data

        package com.example.clientandroid;

    import java.io.IOException;
    import java.io.ObjectOutputStream;

    import android.os.Bundle;
    import android.app.Activity;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.EditText;
    import android.support.v4.app.NavUtils;
    import android.annotation.TargetApi;
    import android.os.Build;

    public class MouseTestActivity extends Activity {
        ObjectOutputStream  oos;
        Thread mainThread;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_mouse_test);
            // Show the Up button in the action bar.



        /*  Bundle b = getIntent().getBundleExtra("OOS");

            oos = (ObjectOutputStream)b.getSerializable("OOS");*/

            setupActionBar();
        }
        /*
        public void setThread(Thread t){
            mainThread = t;
        }
        */
        /**
         * Set up the {@link android.app.ActionBar}, if the API is available.
         */
        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        private void setupActionBar() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                getActionBar().setDisplayHomeAsUpEnabled(true);
            }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.mouse_test, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
            case android.R.id.home:
                // This ID represents the Home or Up button. In the case of this
                // activity, the Up button is shown. Use NavUtils to allow users
                // to navigate up one level in the application structure. For
                // more details, see the Navigation pattern on Android Design:
                //
                // http://developer.android.com/design/patterns/navigation.html#up-vs-back
                //
                NavUtils.navigateUpFromSameTask(this);
                return true;
            }
            return super.onOptionsItemSelected(item);
        }


        public void Send(View view) throws IOException{

            EditText message = (EditText) findViewById(R.id.editText1);
            String msg = message.getText().toString();

            /*oos.writeUTF(new String("Bye\n"));
            oos.flush();*/

        }



    }

I hope to find a solution, thanks to everybody.

For long tasks (eg connecting to a server) you should consider using a Service rather than an Activity. Because an Activity could be destroyed at any time by the user pressing home/back button, or by the system for memory saving issues.

Every thing you need to know is here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM