Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send data from Activity to Service

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;
}
like image 335
Chintan Avatar asked Mar 05 '13 21:03

Chintan


1 Answers

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
}
like image 53
Hoan Nguyen Avatar answered Oct 01 '22 04:10

Hoan Nguyen