2

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.

Chirag Shah
  • 3,654
  • 22
  • 29
user1680782
  • 111
  • 4
  • 9

4 Answers4

1

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.

Lazy Ninja
  • 22,342
  • 9
  • 83
  • 103
1

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.

Chandrashekhar
  • 498
  • 4
  • 19
  • I have String data. msg.arg1 = data (Type mismatch: cannot convert from String to int) – user1680782 Sep 19 '12 at 12:00
  • Messenger messenger = (Messenger) extras.get("MESSENGER"); (extras cannot be resolved) – user1680782 Sep 19 '12 at 12:03
  • 1
    /**use this when u start the service**/ Messenger messenger = new Messenger(handler); intent.putExtra("MESSENGER", messenger); intent.putExtra("urlpath", "whatever this was my requirement"); startService(intent); – Chandrashekhar Sep 19 '12 at 12:35
  • you can add integer parameter to the arg1 like 0 or 1 and then check for the it when u recieve the response. – Chandrashekhar Sep 19 '12 at 12:38
  • in that case ur message will not be sent cause ur activity's current state is not active. or you can start the activity from service also. depends on ur requirement – Chandrashekhar Sep 19 '12 at 13:00
1

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
          }

       }

    }

 }
Community
  • 1
  • 1
Rohit Singh
  • 16,950
  • 7
  • 90
  • 88
0

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

Kenny C
  • 2,279
  • 1
  • 19
  • 20
  • Sorry, but I don't know how to do it :( Can you give me more examples? Thanks. – user1680782 Sep 19 '12 at 11:43
  • Unfortunately the information in the android developer guide is too vague. Maybe if you add a few lines of code as example, it would be more helpful. – Yván Ecarri May 11 '20 at 07:47