Saturday, February 23, 2019

Passing data from activity to service

We want to passing data from activity to service.
In activity.
String text="some text";
Intent mIntent = new Intent(this, service.class);
          Bundle mBundle = new Bundle();
          mBundle.putString("to", text);
          mIntent.putExtras(mBundle);
   startService(mIntent);
In service class.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
     //TODO   
String receive = intent.getStringExtra("to");
return Service.START_STICKY;
}
We must use data passed inside onStartCommand, if want set to view, you must draw view inside onStartCommand.
If draw view inside onCreate() we can’t use passed data.

Remember to declare service in file manifest.xml.

No comments:

Post a Comment