Dinesh Babu K G
Dinesh Babu K G

Reputation: 498

How to Get data from Service to Activity where Callback is Involved?

Here's the scenario,

public void publishArrived(blah, blah) { //some operation here }

CONTEXT: In my activity i Perform a Login operation whose success depends on the above result that arrives in publishArrived.

Thanks in Advance.

Upvotes: 0

Views: 2434

Answers (2)

Theo
Theo

Reputation: 6083

Assuming that you need to start the activity and service at the same time (rather than start the activity after you receive data in the service) you can register a BroadcastReceiver in your activity, and then send a broadcast message from the service once you have the data.

The code to register a broadcast receiver in your activity will be similar to this, but you'll be defining your own custom message:
https://stackoverflow.com/a/2959290/483708

To send a custom broadcasts from your service you'll be using this (lifted from http://www.vogella.de/articles/AndroidServices/article.html):

Intent intent = new Intent();
intent.setAction("de.vogella.android.mybroadcast");
sendBroadcast(intent);

Upvotes: 1

Exorcist
Exorcist

Reputation: 252

Here's the solution for this. Declare a String before your onCreate() Method but inside the class like this -

public static final String pass="com.your.application._something";

In your publishArrived method,you can do this -

String s="Pass this String";//If you want to pass an string
int id=10;//If you want to pass an integer
Intent i=new Intent(currentactivity.this,NewActivity.class);
i.putExtra(pass, id);//If you want to pass the string use i.putExtra(pass, s);
startActivity(i);

And now you want to catch the data which this activity provided. So, In the new activity, simply extract the value as shown -

//this is for getting integer.
int a=getIntent().getExtras().getInt(CurrentActivity.pass);
//this is for getting String
String s=getIntent().getExtras(CurrentActivity.pass);

Note 1 : Actually always String should be passed as it can easily pe parsed as Integer.

Note 2 : Give your CurrentActivity and NewActivity name in the respective places.

Hope this helps.

In your case suppose the Login is "abc" and the password is "pqr" then you can pass this as String s=login+"*"+password; This will result in abc*pqr

Now in the NewActivity simply parse the String till you get '*'.Get its Index by indexOf('*'). The value before this index is the Login and the value after this will be the password.

Upvotes: 0

Related Questions