Android Studio starts the Service and transmits data from the Activity to the Service. androidactivity
This example demonstrates starting the Service and passing data from the Activity to the Service, creating a new Service, and typing the following code:
Package com. example. lhb. startservice; import android. app. service; import android. content. intent; import android. OS. IBinder; import android. view. viewDebug; import android. widget. toast; public class MyService extends Service {private boolean Running = false; private String data = "default information !!! "; Public MyService () {}@ Override public IBinder onBind (Intent intent) {// TODO: Return the communication channel to the service. throw new UnsupportedOperationException ("Not yet implemented");} @ Override public int onStartCommand (Intent intent, int flags, int startId) {data = intent. getStringExtra ("data"); // The intent here is in the parameter, not the custom return super. onStartCommand (intent, flags, startId) ;}@ Override public void onCreate () {super. onCreate (); Running = true; new Thread () {@ Override public void run () {super. run (); while (Running) {System. out. println (data); try {sleep (3000);} catch (InterruptedException e) {e. printStackTrace ();}}}}. start () ;}@ Override public void onDestroy () {super. onDestroy (); Running = false ;}}
Main program code:
Package com. example. lhb. startservice; import android. content. intent; import android. support. v7.app. actionBarActivity; import android. OS. bundle; import android. view. menu; import android. view. menuItem; import android. view. view; import android. widget. editText; import android. widget. toast; public class MainActivity extends ActionBarActivity {private EditText inputText; @ Override protected void onCreate (Bundle SavedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); findViewById (R. id. btnStartService ). setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {inputText = (EditText) findViewById (R. id. inputText); if (inputText. getText (). length () = 0) {Toast. makeText (MainActivity. this, "Enter the passed value! ", Toast. LENGTH_SHORT ). show (); return;} Intent intent; intent = new Intent (MainActivity. this, MyService. class); intent. putExtra ("data", inputText. getText (). toString (); startService (intent) ;}}); findViewById (R. id. btnStopService ). setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {Intent intent; intent = new Intent (MainActivity. this, MyService. class); stopService (intent );}});}}