Send data from Activity to Service

冷暖自知 提交于 2019-12-22 06:45:07

问题


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
    }
}


来源:https://stackoverflow.com/questions/15234181/send-data-from-activity-to-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!