How to Get data from Service to Activity where Cal

2019-08-23 07:09发布

Here's the scenario,

  • I want to get Data from the Service to Activity

  • Whenever The Service gets new data from the server, the following function(callback) gets automatically called

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

  • How to I get the Data got from the above function back to my activity ? (I think I am supposed to use "Messenger" here but i am not able to grasp the concept)

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

Thanks in Advance.

2条回答
太酷不给撩
2楼-- · 2019-08-23 07:27

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);
查看更多
淡お忘
3楼-- · 2019-08-23 07:43

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.

查看更多
登录 后发表回答