Connection between Activity and Service

2019-09-06 10:19发布

I have an Activity with an EditText and some checkboxes. After the user inserts a text the text should be sent to the Service and the Service will run in background showing a Toast from time to time.

I am having a really hard time trying to figure out how to send the data(Strings and Boolean values that user inputs through the Activity) to the Service .

2条回答
Emotional °昔
2楼-- · 2019-09-06 10:52

Use Intent on Activity put values in puExtra

Intent intent = new Intent(current.this, YourClass.class);
intent.putextra("keyName","value"); 

and then call StartService so the OnStart method call be called.. in service get the values in OnStart by using intent

Bundle extras = getIntent().getExtras();
   if (extras != null) 
   {
     String value = extras.getString("key");
   }
查看更多
Deceive 欺骗
3楼-- · 2019-09-06 11:16

Have you taken a look at the Android Documentation For Services?

It explains everything you need to know and more :)

(hint: you must pass an Intent to OnStartCommand())

If you google "pass an intent to a service in android" among the first results you'll find:

Pass data from Activity to Service using an Intent

查看更多
登录 后发表回答