mydDeveler
mydDeveler

Reputation: 71

How can I pass data from service/thread class to the main activity?

I have created variable in the main activity called "sum" and in the Thread of the service I created loop that increase variable by 1 like this:

public void run() {
    for(int i=0;i<50000000;i++) {
        num++;
    }

Now I want that every time that the variable "num" is increased by 1 , it will update the value of "sum" to the value of "num".

but I don't really know how to do it .

I want that it will be a live update and not after the thread will be end or the service will be destroyed.

Upvotes: 0

Views: 185

Answers (2)

Aleksandar Stojadinovic
Aleksandar Stojadinovic

Reputation: 5049

You will accomplish that by broadcasting an intent in you service thread, and registering a receiver for that type of intent in your main thread. For that you will need three components:

  • The intent, with added Extras if you need additional data sent from the service to your main thread
  • Broadcast receiver, a class that extends BroadcastReceiver, and executes it's OnReceive method when an intent is broadcasted
  • An intent filter, basically the thing that links a Intent to a Receiver. You register a receiver using a filter type.

I could retype the code, but on this link there are explanations on how to use that. You are interested in the last three slides:

http://www.slideshare.net/CodeAndroid/android-intent-intent-filter-broadcast-receivers

Also, check this out: http://developer.android.com/reference/android/content/BroadcastReceiver.html http://developer.android.com/reference/android/content/IntentFilter.html

Upvotes: 0

Budius
Budius

Reputation: 39836

You'll have to make the activity bind to the service and define the interface for it. But does it have to be a service? Maybe a AsyncTask can be an easier solution?

Upvotes: 1

Related Questions