如何在另一个类中实现处理程序?

时间:2013-06-22 04:21:17

标签: java android handler

在我的应用程序中,我有三个按钮,当单击一个按钮时,它调用一个线程启动的东西是我希望能够在edittext字符串中输入到线程并对它做一些工作然后让它返回到UI线程,我可以在其中显示它或将其放入opengl以显示对象。我已经阅读了Handles,我不确定我是否完全理解它们,也许有人知道如何制作我自己的处理程序代码。此外,我已经阅读了Async,我不认为这会对我的应用程序有利。(个人opion,如果它有利于我的应用程序让我知道)我的问题是当我输入按下该行时,我将如何从UI edittext获取信息在DrawingUtils类中的线程然后完成工作然后它回到UI以显示或在openGl程序中输入?

这是MainActivity类:

  public class MainActivity extends Activity implements OnClickListener {
    EditText cl;
    TextView info;
    Button enter;
    Button line;
    Button arc;
    Line callLine = new DrawingUtils.Line();
    Enter callEnter = new DrawingUtils.Enter();
    Arc callArc = new DrawingUtils.Arc();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        info = (TextView) findViewById(R.id.info);
        enter = (Button) findViewById(R.id.enter);
        line = (Button) findViewById(R.id.line);
        arc = (Button) findViewById(R.id.arc); 

        Handler UIhandler = new Handler() {
              @Override
              public void handleMessage(Message msg) {
                  Bundle bundle = msg.getData();
                    String string = bundle.getString("myKey");

                 }
             };

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.enter:
             callEnter.start();
            break;
        case R.id.line:
            callLine.start();
            break;
        case R.id.arc:
            callArc.start();
            break;
        }

    };

}

这是DrawingUtils类:

    public class DrawingUtils {
    MainActivity handle = new MainActivity();

    // Thread classes for buttons
    public static class Enter extends Thread {
        Thread enter = new Thread() {
            public void run() {

            }

        };

        public static class Line extends Thread {
            Thread line = new Thread() {
                public void run() {

                }
            };

        }

        public static class Arc extends Thread {
            Thread arc = new Thread() {
                public void run() {

                }
            };
        }
    }
}

1 个答案:

答案 0 :(得分:6)

public class MyActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstance) {
        // ....
        Handler myHandler = new Handler() {
            @Override
            public void handleMessage (Message msg) {
                doCoolStuffWhenMessageReceived();
            }
        }
        MySecondClass secondClass = new MySecondClass(myHandler);
        // ....
    }
}


public class MySecondClass {
    private handler;
    public MySecondClass(Handler handler){
        this.handler = handler;
    }

    private void someMethodToCallActivity() {
        handler.sendEmptyMessage(0);
    }

}