user1680782
user1680782

Reputation: 111

Pass data from Service to Activity

I have the service that runs itself (service starts automatically).

And I have the Activity.
In this Activity button starts the method DoIt():

Button.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
      DoIt();
    }
});

Some data is written to the variable data in my service when I push the button and method works.
I can see data in Log:

public String getMessage(String data) {
... 
Log.d(TAG, "Our Data: " + data);
return date;
...   

But how can I see this data in my Activity (under the button) by pushing the button?
Thanks.

Upvotes: 2

Views: 3992

Answers (4)

Rohit Singh
Rohit Singh

Reputation: 18202

Send Data from IntentService to Activity

The key word is BroadcastReceiver

BroadcastReceiver comes handy for such scenarios.

  1. Send broadcast from IntentService
  2. Receive broadcast in the Activity.

Send Data from Service

public class YourService extends IntentService {

  public YourService() {
    super("yourService");
  }

  protected void onHandleIntent(@Nullable Intent intent) {

    sendDataToActivity()
  }

  private void sendDataToActivity()
  {

    Intent sendLevel = new Intent();
    sendLevel.setAction("TIMER_ACTION");
    sendLevel.putExtra( "TIMER_VALUE","This is the value from service");
    sendBroadcast(sendLevel);

  }

}

Receive Data from Service
For this, you need to register your Activity with a BroadcastReceiver

public class YourActivity extends AppCompatActivity {

   TimerReceiver receiver;

   @Override
   public void onCreate(Bundle savedInstanceState)
   {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.track_wifi_activity_layout);
       receiver = new TimerReceiver();
       registerReceiver(receiver, new IntentFilter("TIMER_ACTION"));  //<----Register
   }

   @Override
   public void onStop()
   {
      super.onStop();
      unregisterReceiver(receiver);           //<-- Unregister to avoid memoryleak
   }

   class TimerReceiver extends BroadcastReceiver {

       @Override
       public void onReceive(Context context, Intent intent) {

          if(intent.getAction().equals("TIMER_ACTION"))
          {
              int level = intent.getStringExtra("TIMER_VALUE");

              // Show it in activity
          }

       }

    }

 }

Upvotes: 1

Chandrashekhar
Chandrashekhar

Reputation: 498

Add a handler to your activity like this :-

Handler handler = new Handler() {
        public void handleMessage(Message message) {
            Object path = message.obj;
            if (message.arg1 == RESULT_OK && path != null) {
                Toast.makeText(context,
                        "Success" + path.toString(), Toast.LENGTH_LONG)
                        .show();
            } else {
                Toast.makeText(context, "Operation failed.",
                        Toast.LENGTH_LONG).show();
            }

        };
    };

and send the value from the service in message object like this :-

 Messenger messenger = (Messenger) extras.get("MESSENGER");
                Message msg = Message.obtain();
                msg.arg1 = data;//your value here
                msg.obj = data;
                try {
                    messenger.send(msg);
                } catch (android.os.RemoteException e1) {
                    Log.w(getClass().getName(), "Exception sending message", e1);
                }

Hope it works.

Upvotes: 1

Kenny C
Kenny C

Reputation: 2289

You need to bind the service to your activity. Once the service is bound you can access the methods in your service. Look at this example for how http://developer.android.com/guide/components/bound-services.html

You can also add a listener to your service so that you activity would be instantly notified when the data changes

Upvotes: 0

Lazy Ninja
Lazy Ninja

Reputation: 22527

There is no way you could see this data from your activity.
Making an application class would make things easier for you. You can hold your data in the application class so that the service can update it, and the activity can retrieve it. Not sure if thats what you want though.

Upvotes: 1

Related Questions