Service is one of the four components of Android development, and the following is an introduction to the simple usage of service
1. You need to create a new service class that inherits from the service interface and needs to implement the Onbind method, which is followed by an introduction
2. Create the intent object, set the class of the intent target for the new service, there are two ways to start the service using the StartService method and the Bindservice method
The difference between the two methods is that the service is still running in the system background after the StartService is started and after the current activity is closed
Bindservice the service is bound to the main interface after the service is started, and the main interface is closed, service ends.
3. The main interface and service information interaction needs to use AIDL, need to create a new Aidl package under Project SRC, and create a new interface, will automatically generate the corresponding Java files in the Gen directory, these things are not modified.
Also, be sure to register your service in Androimanifest
PackageCom.wentjiang.shixi_service;ImportCom.wentjiang.shixi_service.aidl.MyInterface;ImportAndroid. r.string;Importandroid.app.Activity;ImportAndroid.app.Service;ImportAndroid.content.BroadcastReceiver;ImportAndroid.content.ComponentName;ImportAndroid.content.Context;Importandroid.content.Intent;ImportAndroid.content.IntentFilter;Importandroid.content.ServiceConnection;ImportAndroid.os.Bundle;ImportAndroid.os.IBinder;Importandroid.os.RemoteException;ImportAndroid.util.Log;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.TextView; Public classMainactivityextendsActivityImplementsonclicklistener{PrivateButton Mstartservice,mstopservice,mbindservice,munbindservice,maidl; PrivateTextView Mtextview; Privateserviceconnection Mconn; PrivateMyreceiver Myreceiver; PrivateMyInterface Minterface; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); InitData (); Initview (); } Private voidInitview () {Mstartservice=(Button) Findviewbyid (R.id.startservice); Mstopservice=(Button) Findviewbyid (R.id.stopservice); Mbindservice=(Button) Findviewbyid (R.id.bindservice); Munbindservice=(Button) Findviewbyid (R.id.unbindservice); Maidl=(Button) Findviewbyid (R.ID.AIDL); Mtextview=(TextView) Findviewbyid (R.id.text); Mstartservice.setonclicklistener ( This); Mstopservice.setonclicklistener ( This); Mbindservice.setonclicklistener ( This); Munbindservice.setonclicklistener ( This); Maidl.setonclicklistener ( This); } Private voidInitData () {Mconn=Newserviceconnection () {@Override Public voidonservicedisconnected (componentname name) {//methods that are called when a connection fails} @Override Public voidonserviceconnected (componentname name, IBinder service) {//successful connection is the method calledLOG.I ("Connection succeeded", "---"); Minterface=MyInterface.Stub.asInterface (service); } }; Myreceiver=NewMyreceiver (); Intentfilter Filter=NewIntentfilter (); Filter.addaction ("Action.went"); Registerreceiver (myreceiver, filter); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.main, menu); return true; } @Override Public Booleanonoptionsitemselected (MenuItem item) {intID =Item.getitemid (); if(id = =r.id.action_settings) { return true; } return Super. onoptionsitemselected (item); } @Override Public voidOnClick (View v) {Intent Intent=NewIntent ( This, MyService.class); Switch(V.getid ()) { CaseR.id.startservice:startservice (Intent); Break; CaseR.id.stopservice:stopservice (Intent); Break; CaseR.id.bindservice:bindservice (Intent, Mconn, service.bind_auto_create); Break; CaseR.id.unbindservice:unbindservice (Mconn); Break; CaseR.id.aidl:Try { intNum= Minterface.getmul (10, 6); Mtextview.settext (string.valueof (num)); } Catch(RemoteException e) {e.printstacktrace (); } default: Break; } } Public classMyreceiverextendsbroadcastreceiver{@Override Public voidOnReceive (Context context, Intent Intent) {String action=intent.getaction (); if("Action.went". Equals (action)) { intNum=intent.getintextra ("num", 0); Mtextview.settext (string.valueof (num)); } } }}mainactivity
PackageCom.wentjiang.shixi_service;ImportJava.util.Timer;ImportJava.util.TimerTask;ImportCom.wentjiang.shixi_service. Mainactivity.myreceiver;ImportCom.wentjiang.shixi_service.aidl.MyInterface;ImportAndroid. R.integer;ImportAndroid.app.Service;Importandroid.content.Intent;ImportAndroid.content.IntentFilter;ImportAndroid.net.ConnectivityManager;ImportAndroid.os.IBinder;Importandroid.os.RemoteException;ImportAndroid.util.Log; Public classMyServiceextendsService {PrivateMyreceiver Mreceiver; PrivateMyinterface.stub Mbinder =Newmyinterface.stub () {@Override Public intGetmul (intNUM1,intNUM2)throwsRemoteException {intTemp=num1*num2; returntemp; } }; @Override Publicibinder onbind (Intent Intent) {log.i ("Onbind was called", "----"); returnMbinder; } @Override Public voidonCreate () {Super. OnCreate (); LOG.I ("OnCreate was called", "----"); } @Override Public voidOnDestroy () {LOG.I ("OnDestroy was called", "---"); Super. OnDestroy (); } @Override Public voidOnrebind (Intent Intent) {log.i ("Onrebind", "---"); Super. Onrebind (Intent); }}MyService
Package Com.wang.service.aidl; Interface myinterface{ int mul (intint b); }
MyInterface
<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:background= "#ffffff"android:orientation= "Vertical"android:padding= "20DP" > <TextView Android:id= "@+id/tv"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Test"Android:textcolor= "#000000"android:textsize= "24sp"/> <Button Android:id= "@+id/btn01"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Start Service"/> <Button Android:id= "@+id/btn02"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Stop Service"/> <Button Android:id= "@+id/btn03"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Bind Service"/> <Button Android:id= "@+id/btn04"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Unbind Service"/> <Button Android:id= "@+id/btn05"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:layout_margintop= "10DP"Android:text= "Work"/> </LinearLayout>
Activity_main
Simple usage of Android-service