Skip to content Skip to sidebar Skip to footer

How To Program Outside The Main Ui Thread

I don't know if a UI thread exists by default, how to create it if not, or how to tell when I'm 'in' it where it begins and ends if so. How do I make sure PacketListener isn't part

Solution 1:

ui thread is main thread. you know about current thread by

Thread.currentThread().getName();

sorry i didn't read your whole question but you have to do blocking proccess in another thread than mainThread.

there are many ways to do that : AsyncTask , Services , ExecutorService and RxJava . and which one to pick depends on your need

this link would be helpful :)

Solution 2:

Your last method is correct, except the thread isn't started yet. So you need to call the start():

publicvoidsendAnother(View view) {
  //adapter.add("button clicked");new Thread(new Runnable() {
    publicvoidrun() {
      listview.post(new Runnable() {
        publicvoidrun() {
          adapter.add("inside worker thread");
        }
      });
    }
  }).start();
}

Solution 3:

I'm still not sure I like AsyncTask for this project, so if someone can offer advice or a link to a tutorial to use Handler or Runnable, PLEASE post it!

Strictly speaking though, this at least finally lets me do stuff outside the UI thread, and that was the question. Sooo, for what it's worth to any others having this problem, here's what first worked for me.

publicclassMainActivityextendsAppCompatActivity {
    ArrayAdapter<String> adapter;
    privatestaticfinalint PORT= 8888;
    privatestaticfinalintTIMEOUT_MS=500;

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ArrayList<String> listItems = newArrayList<>();
        ListViewlistview= (ListView) findViewById(R.id.lvMain);
        adapter = newArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItems);
        listview.setAdapter(adapter);

        UpdateViewtask=newUpdateView();
        task.execute();

        //just to show these parts are in different threadsStringtemp= Thread.currentThread().getName();
        adapter.add("onCreate: " + temp);
    }

    privateclassUpdateViewextendsAsyncTask<URL, Integer, Long> {
        protected Long doInBackground(URL... urls) {
            //just to show these parts are in different threadsStringtemp= Thread.currentThread().getName();
            adapter.add("UpdateView: " + temp);

            byte[] buf = newbyte[256];
            byte[] ipAddress = {(byte)192,(byte)168,0,1};

            try {
                InetAddressaddress= InetAddress.getByAddress(ipAddress);

                Stringmessage="\"xyz\"";
                DatagramSocketsocket=newDatagramSocket(PORT);
                DatagramPacketpacket=newDatagramPacket(message.getBytes(), message.length(), address, PORT);
                socket.send(packet);

                packet = newDatagramPacket(buf, buf.length);
                socket.receive(packet);
            }
            catch(IOException e) {
                adapter.add("IO Exception: " + e.toString() );
                e.printStackTrace();
            }

            adapter.notifyDataSetChanged();
            return0L;
        }
    }
}

Post a Comment for "How To Program Outside The Main Ui Thread"