Send data from Activity to Service

2019-05-03 23:09发布

问题:

How can I send data from the current Activity to a background Service class which is running at certain time? I tried to set into Intent.putExtras() but I am not getting it in Service class

Code in Activity class which calls the Service.

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

Code in Service class. I treid to put in onBind() and onStartCommand(). None of these methods prints the 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;
}

回答1:

Your code should be onStartCommand. If you never call bindService on 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
}


回答2:

If you want to pass primitive data types that can be put into Intent I would recommend to use IntentService. To start the IntentService, type in your activity:

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

Then create a service class that extends 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
    }
}