Reputation: 1876
I have a service in which I have:
Intent intent = new Intent(ClipboardWatcherService.this, DeliDict.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("searchTerm", searchTerm);
startActivity(intent);
and in my activity:
@Override
public void onStart()
{
super.onStart();
Intent intent = getIntent();
String clipboardSearchTerm = intent.getStringExtra("searchTerm");
...
}
But intent.getStringExtra() always returns null.
NOTE: Because I'm calling StartActivity() from my Service (that's outside an activity class) I have to define Intent.FLAG_ACTIVITY_NEW_TASK causing only ONE instance of my activity be alive at a time. So I have to go inside onStart() since onCreate() is called only once. Basically I've been looking for a reliable way to send data from my Service to the activity for a whole day but in vain. can you suggest something?
Upvotes: 3
Views: 4645
Reputation: 8939
If you need to pass some value from Service to any Activity class, you should use BroadcastReceiver.
Step1) You need to register first that BroadcastReceiver to that Activity. For this you need to define Action for that.
public static final String YOUR_ACTION_STRING = "com.test.android.service.receiver";
Now Register the Receiver
registerReceiver(receiver, new IntentFilter("YOUR_ACTION_STRING"));
and receive the value here
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
String clipboardSearchTerm = intent.getString("searchTerm");
}
}
};
Step 2) From Service you need to Broadcast the message.
Intent intent=new Intent();
intent.setAction("YOUR_ACTION_STRING");
intent.putExtra("searchTerm", searchTerm);
sendBroadcast(intent);//Broadcast your message to registered Activity
Upvotes: 2