简体   繁体   中英

How to use multiple buttons for multiple threads in android?

I've been working on this program for some time now and. I was stuck on how to handle my multiple buttons issue.I have three buttons that needs to start different threads but i've looked at the the stuff on google for threading and multithreading and i couldnt find the answer i was looking for. From my understanding public void run() can only be called once in an class for threads? How would i create multiple threads that differ in code in one class?

Example of what i have seen that would be the best solution to my problem is:

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.Line:
       // Call to Thread line
        break;
    case R.id.Enter:
        //Call to Thread Enter
            break;
    case R.id.arc
    //Call to Thread Arc
        } 

Example of the line thread and enter thread:

        Thread enter = new Thread() {
        public void run() {
    DrawingUtils call = new DrawingUtils();
    EditText cl = (EditText) findViewById(R.id.editText1);
    String in = cl.getText().toString();
    call.setInputCoords(in);
    notifyAll();
        }

};

        Thread line = new Thread() {
        public void run() {
            info.setText("Enter X,Y,Z for Point 1");
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            call.addLine();
            info.setText("Enter X,Y,Z for Point 2");
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            call.addLine();


        }
    };
    line.start();

Create other inner class which extends thread like

    class Line extends Thread {
        public void run() {
    DrawingUtils call = new DrawingUtils();
    EditText cl = (EditText) findViewById(R.id.editText1);
    String in = cl.getText().toString();
    call.setInputCoords(in);
    notifyAll();
        }

};

now start using new Line().start()

U Cant update UI normally on new thread which you launch.. please read more about UI before development..... this may help you

to set test for text view in your code

info.post(new Runnable() {
 @Override
    public void run() {
       info.setText("Enter X,Y,Z for Point 1"); 
    }
});

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