This example demonstrates starting the service and passing data from the activity to the service, creating a new service and tapping 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 ("D ATA ");//The intent here is a parameter, not a 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 value passed! ", 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 V OID OnClick (View v) {Intent Intent; Intent=new Intent (Mainactivity.this,myservice.class); StopService (Intent); } }); }}
Android Studio develops the foundation of the start service and passes data from activity to service