Sending data from Activity to Service

How can I send data from the current Activity to the background Service class that is running at a specific time? I tried setting in Intent.putExtras() but I don't get it in the Service class

The code in the Activity class that calls Service .

 Intent mServiceIntent = new Intent(this, SchedulerEventService.class); mServiceIntent.putExtra("test", "Daily"); startService(mServiceIntent); 

Code in the Service class. Put in onBind() and onStartCommand() . None of these methods print a value.

 @Override public IBinder onBind(Intent intent) { //Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show(); //String data = intent.getDataString(); Toast.makeText(this, "Starting..", Toast.LENGTH_SHORT).show(); Log.d(APP_TAG,intent.getExtras().getString("test")); return null; } 
+4
source share
2 answers

Your code should be onStartCommand . If you never call bindService in your activity, onBind will not be called and use getStringExtra() instead of getExtras()

 @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, "Starting..", Toast.LENGTH_SHORT).show(); Log.d(APP_TAG,intent.getStringExtra("test")); return START_STICKY; // or whatever your flag } 
+4
source

If you want to pass primitive data types that can be entered into Intent, I would recommend using IntentService. To start IntentService, enter your activity:

 startService(new Intent(this, YourService.class).putExtra("test", "Hello work"); 

Then create a service class that extends the IntentService class:

 public class YourService extends IntentService { String stringPassedToThisService; public YourService() { super("Test the service"); } @Override protected void onHandleIntent(Intent intent) { stringPassedToThisService = intent.getStringExtra("test"); if (stringPassedToThisService != null) { Log.d("String passed from activity", stringPassedToThisService); // DO SOMETHING WITH THE STRING PASSED } } 
+1
source

All Articles