Service Learning routine
Similar to Activity, a Service has its own life cycle. Different services run in the background and there is no user interaction interface.
There are two ways to run the Android Service:
1. Use startService () to start the Service. There is no association between the visitor and the Service. Even if the visitor exits, the Service still runs.
2. bindService () is used to bind a visitor to a Service. Once a visitor exits, the Service is terminated.
The Learning routine uses the first method. There are two buttons, one starting the Service and the other stopping the Service.
Activity on the main interface of TestActivity. java
public class TestActivity extends Activity {private Button startServiceButton = null;private Button stopServiceButton = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);startServiceButton = (Button)findViewById(R.id.startService);stopServiceButton = (Button)findViewById(R.id.stopService);startServiceButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubIntent intent = new Intent();intent.setClass(TestActivity.this, FirstService.class);startService(intent);}});stopServiceButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubIntent intent = new Intent(TestActivity.this, FirstService.class);stopService(intent);}});System.out.println(Activity onCreate);}}FirstService. java defines Service components
Public class FirstService extends Service {@ Overridepublic IBinder onBind (Intent intent) {// TODO Auto-generated method stubSystem. out. println (Service onBind); return null;} // when a Servcie object is created, this function @ Overridepublic void onCreate () {// TODO Auto-generated method stubsuper is called first. onCreate (); System. out. println (Service onCreate) ;}@ Overridepublic int onStartCommand (Intent intent, int flags, int startId) {// TODO Auto-generated method stubSystem. out. println (flags --> + flags); System. out. println (startID --> + startId); System. out. println (Service onStartCommand); return START_STICKY;} @ Overridepublic void onDestroy () {// TODO Auto-generated method stubSystem. out. println (Service onDestory); super. onDestroy ();}}
Register Service in mainfest. xml
The life cycle of the Service