1. Service Usage
Activity can render a user interface, but the Service does run in the background, creating a new Myservice.java that automatically configures <Service> tags in androidmanifest.
<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "/http Schemas.android.com/apk/res/android "package=" Com.example.lhb.service "> <application android:allowback Up= "true" android:icon= "@mipmap/ic_launcher" android:label= "@string/app_name" android:theme= "@style/A Pptheme "> <activity android:name=". Mainactivity "android:label=" @string/app_name "> <intent-filter> <action Android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER "/> </intent-filter> </activity> <service android:name=". MyService "android:enabled=" true "android:exported=" true "> </service> </appli Cation></manifest>
in the new service, rewrite the Onstartcommand () function, create a thread, click the Start Thread button, let it cycle through the background, pay attention to press the back key to exit the activity, the service is still in progress.
Package Com.example.lhb.service;import Android.app.service;import Android.content.intent;import Android.os.IBinder ;p ublic class MyService extends Service {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) {new Thread () {@Over Ride public void Run () {super.run (); do {System.out.println ("Service is running ..."); try {sleep (1000); } catch (Interruptedexception e) {e.printstacktrace (); }} while (true); }}.start (); Return Super.onstartcommand (Intent, flags, Startid); }}The main code is as follows:
Package Com.example.lhb.service;import Android.app.activity;import Android.content.intent;import android.os.Bundle ; Import Android.view.view;import Android.widget.textview;public class Mainactivity extends Activity implements view.onclicklistener{private TextView TextView; Private Intent Intent; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Initview (); } private void Initview () {textview=new TextView (this); Textview.settext (R.string.hello_world); Findviewbyid (R.id.btnstartservice). Setonclicklistener (this); Findviewbyid (R.id.btnstopservice). Setonclicklistener (this); Intent=new Intent (Mainactivity.this,myservice.class); } @Override public void OnClick (View v) {switch (V.getid ()) {r.id.btnstartservice: StartService (Intent); Break Case R.id.btnstopservIce:stopservice (Intent); Break } }}
2. Binding Service
You can start myservice in a binding manner, and then add a button that binds the service and unbind the service.
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android: paddingleft= "@dimen/activity_horizontal_margin" android:paddingright= "@dimen/activity_horizontal_margin" Android :p addingtop= "@dimen/activity_vertical_margin" android:paddingbottom= "@dimen/activity_vertical_margin" Android:o rientation= "Vertical" tools:context= ". Mainactivity "> <button android:layout_width=" wrap_content "android:layout_height=" Wrap_content " android:text= "Start service" android:id= "@+id/btnstartservice"/> <button android:layout_width= "Wrap_con Tent "android:layout_height=" Wrap_content "android:text=" Stop Service "android:id=" @+id/btnstopservice "/> <button android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:text= "Binding Service" android:id= "@+id/btnbindservice "/> <button android:layout_width=" wrap_content "android:layout_height=" Wrap_con Tent "android:text=" unbound Service "android:id=" @+id/btnunbindservice "/></linearlayout>
Main program:
Package Com.example.lhb.service;import Android.app.activity;import Android.content.componentname;import Android.content.context;import Android.content.intent;import Android.content.serviceconnection;import Android.os.bundle;import Android.os.ibinder;import Android.view.view;import Android.widget.textview;public class Mainactivity extends Activity implements View.onclicklistener, serviceconnection {private TextView TextView; Private Intent Intent; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Initview (); } private void Initview () {textview=new TextView (this); Textview.settext (R.string.hello_world); Findviewbyid (R.id.btnstartservice). Setonclicklistener (this); Findviewbyid (R.id.btnstopservice). Setonclicklistener (this); Findviewbyid (R.id.btnbindservice). Setonclicklistener (this); Findviewbyid (R.id.btnunbindservice). SetOnclicklistener (this); Intent=new Intent (Mainactivity.this,myservice.class); } @Override public void OnClick (View v) {switch (V.getid ()) {r.id.btnstartservice: StartService (Intent); Break Case R.id.btnstopservice:stopservice (Intent); Break Case R.id.btnbindservice:bindservice (Intent,this, context.bind_auto_create); Directly with this connection will be error, press Alt+enter, create the following onserviceconnected () break; Case R.id.btnunbindservice:unbindservice (this); Break }} @Override//service binding executes public void onserviceconnected (componentname name, IBinder service) {System.ou T.println ("Service connected"); } @Override//process ran out of execution public void onservicedisconnected (componentname name) {}}Note: After completing the above code, change the IBinder in Myservice.java to return new Binder (), otherwise an error will occur!
@Override public IBinder onbind (Intent Intent) { //Todo:return The communication channel to the service. throw new Unsupportedoperationexception ("not yet implemented"); return new Binder (); }
Java.lang.RuntimeException:Unable to bind to service [email protected] with Intent {cmp=com.example.lhb.service/. MyService}: Java.lang.UnsupportedOperationException:Not yet implemented at Android.app.ActivityThread.handleB Indservice (activitythread.java:2771) at android.app.activitythread.access$1900 (activitythread.java:144) At Android.app.activitythread$h.handlemessage (activitythread.java:1366) at Android.os.Handler.dispatchMessa GE (handler.java:102) at Android.os.Looper.loop (looper.java:135) at Android.app.ActivityThread.main (A ctivitythread.java:5221) at Java.lang.reflect.Method.invoke (Native Method) at Java.lang.reflect.Meth Od.invoke (method.java:372) at Com.android.internal.os.zygoteinit$methodandargscaller.run (ZygoteInit.java:899) At Com.android.internal.os.ZygoteInit.main (zygoteinit.java:694) caused BY:JAVA.LANG.UNSUPPORTEDOPERATIONEXC Eption:not yet ImplementeD at Com.example.lhb.service.MyService.onBind (myservice.java:14) 3. Service life cycle
Package Com.example.lhb.service;import Android.app.service;import Android.content.intent;import android.os.Binder; Import Android.os.ibinder;public class MyService extends Service {public MyService () { } @Override Public IBinder Onbind (Intent Intent) { //Todo:return The communication channel to the service. throw new Unsupportedoperationexception ("not yet implemented"); return new Binder (); } @Override public int Onstartcommand (Intent Intent, int flags, int startid) { return Super.onstartcommand ( Intent, flags, Startid); } @Override public void OnCreate () { super.oncreate (); System.out.println ("OnCreate"); } @Override public void OnDestroy () { Super.ondestroy (); System.out.println ("OnDestroy");} }
runtime found that at the same time click on the start service and binding services, you need to click Stop Service and Unbind service to stop the service, click on the binding service, then quit the activity, the program will throw an exception, and then perform the Unbind service, the entire program interface such as:
Android Studio Development Foundation Service