0

I would like to call different code (callbacks) from within a background thread loop and use that background thread to perform the work. It would be similar to delegates in C#.

public class test {
    private boolean keepRunning;
    private boolean messageReady;
    private MyClass myClass;
    void LongBackgroundWork(){
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (keepRunning) {
                    if (messageReady){
                        myClass.callback();  // call different methods here 
                                    //   to be decided at runtime and run on this worker thread
                    }
                }
            }
        });
        thread.start();
    }
}

I want to use the background thread not the UI thread. I want to set a callback from within myClass to choose what code is called. It's easy in C# how to do it Java. I don't have much experience in Java and don't understand what mechanism to use. Should I be using a handler? Can a handler run code on a background thread?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Paul Stanley
  • 1,999
  • 1
  • 22
  • 60
  • BackgroundTask in Android is called AsyncTask. Start from here : https://developer.android.com/reference/android/os/AsyncTask.html. – an_droid_dev Aug 09 '17 at 15:42
  • I think you misunderstand my question. – Paul Stanley Aug 09 '17 at 15:43
  • "Can a handler run code on a background thread?". No. You should use AsyncTask instead – an_droid_dev Aug 09 '17 at 15:46
  • That is definitely not the solution but thanks. – Paul Stanley Aug 09 '17 at 15:48
  • Mine is not an answer , just a hint (comment). – an_droid_dev Aug 09 '17 at 15:49
  • AsyncTask enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.Not what I want. – Paul Stanley Aug 09 '17 at 15:50
  • If you want to perform background operations you can also look into services for Android. https://developer.android.com/guide/components/services.html This can help you schedule tasks and perform operations in the background without having the application at the forground even. Scheduling tasks can also aid in insuring your application isn't draining battery which will be useful for your users and yourself. There's a bit of work and setup involved, but it may be worth the look. https://developer.android.com/guide/components/services.html – Yoshi_64 Aug 09 '17 at 16:11

2 Answers2

1

I'd wager you want to have a pattern where an event or some occurence happens and you need to initiate a code block somewhere.

A pattern that could help you is perhaps an Observer Wiki and firing off to the event. You can also check out this SO question here if you'd like: Delegate vs Callback in Java

In your case, I think you'd want to have someone handle the responsibility of what you have to do when a message is ready. So what you're looking for is someone to perform the action, once the event is read (message ready).

Take for example Class Foo is your container of listeners, or also called an Observer that will be notified of any events. You can have a list of callbacks here to some object that is responsible for your logic to do what you need to do next.

Then you would have an Observable object or a class that would implement some logic when notified. You could then have various class objects perform the necessary logic by implementing the callback function required.

Example:

// Observer
public class Foo {
    // List of objects that implement Callbacks interface
    private List<Callbacks> mList;
    public Foo() {
        // Initialize here
    }
    public void addListener(Callbacks cb) {
        mList.add(cb);
    }
    public void notifyListeners() {
        for ( Callback cb : mList) {
            cb.onCallback();
        }
    }
    // Public interface to be implemented by users
    public interface Callback {
        void onCallback();
    }
}

Then just have a class implement this object and you can pass it along if you'd like.

// Bar implements Foo.Callback interface
public class Bar implements Foo.Callback {
    public class Bar() {}

    @Override
    public void onCallback() {
        // Perform logic here
    }
}

Finally in your code, you'd just create the Foo object, add a listener, and notify them when it's time to fire your event.

Yoshi_64
  • 306
  • 2
  • 9
0

if i understood you properly,you cant do this on UI thread, basically when android see Thread like this it will expect that it's a long operation however you can call it by AsyncTask or Handler

you can make something like this

private class MyAsyncTask extends AsyncTask<Void,Void,Void>{
 protected Void doInBackground() {
   MyClass myClass=new MyClass();
   myClass.LongBackgroundWork();
     }
     return totalSize;
 }
}

this is how yo can call your thread otherwise you have to use Handler instead

Handler handler=new Handler();
handler.post(new Runnable(){
MyClass myClass=new MyClass();
myClass.LongBackgroundWork();
})
Basil Battikhi
  • 2,638
  • 1
  • 18
  • 34