0

I would like to pass an object (docket for printing) to a new thread which will print the docket. My code is:

  private final Button.OnClickListener cmdPrintOnClickListener = new Button.OnClickListener() {

    public void onClick(View v) {
        new Thread(new Runnable() {
            public void run() {
                enableTestButton(false);
                Looper.prepare();
                doConnectionTest();
                Looper.loop();
                Looper.myLooper().quit();
            }
        }).start();

      }
};

How do I pass the object to it? Also - I need to generate the object in the UI thread, just before starting the new thread so where could I put this method (e.g. getDocketObject()) in relation to my code below

thanks,

anton

4

1 に答える 1

3

You could create your own Runnable class implementation:

    private class RunnableInstance implements Runnable {

    protected Docket docket;

    public void run() {
        //do your stuff with the docket
    }

    public void setDocket(Docket docket) {
        this.docket = docket;
    }

}

And then use it to create the thread

public void onClick(View v) {
        RunnableInstance target = new RunnableInstance();
        target.setDocket(docketInstance);
        new Thread(target).start();
    }

If you need to stick to an anonymous class you could do:

        public void onClick(View v) {
        final Docket docket = docketInstance;
        Runnable target = new Runnable(){
            public void run() {
                // do your stuff with the docket
                System.out.println(docket);
            }
        };
        new Thread(target).start();

    }

But you have make sure you assign the instance to a final variable.

于 2012-07-11T03:13:06.710 に答える