Service as its name, we have known that activity represents a page, but if we do not need to show the page, the value needs a background operation, we can create a service, general socket communication, HTTP requests, and other operations.
1. We create an Android project
2, add a service, the code is as follows
PackageCom.example.learnservice;ImportAndroid.app.Service;ImportAndroid.content.Intent;ImportAndroid.os.IBinder; Public class myservice extends Service { @Override PublicIBinderOnbind(Intent Intent) {//TODO auto-generated method stub return NULL; }@Override Public int Onstartcommand(Intent Intent,intFlagsintStartid) {NewThread () {@Override Public void Run() {Super. Run ();//while (true) {System.out.println ("Running in the background ...");Try{Thread.Sleep ( +); }Catch(Interruptedexception e) {E.printstacktrace (); }//}}}.start ();return Super. Onstartcommand (Intent, flags, Startid); }}
Inherit the service and override Onstartcommand, which is executed when this service is enabled.
3, we add 2 buttons on the empty Activity page, respectively, to start and stop the service operation, the code is as follows
PackageCom.example.learnservice;Importandroid.app.Activity;ImportAndroid.content.Intent;ImportAndroid.os.Bundle;ImportAndroid.view.Menu;ImportAndroid.view.View; Public class mainactivity extends Activity { PrivateIntent Intent;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); Intent =NewIntent (mainactivity. This, Myservice.class); Findviewbyid (R.id.button1). Setonclicklistener (NewView.onclicklistener () {@Override Public void OnClick(View v) {//TODO auto-generated method stubStartService (Intent); } }); Findviewbyid (R.id.button2). Setonclicklistener (NewView.onclicklistener () {@Override Public void OnClick(View v) {System.out.println ("Turn off background services ...."); StopService (Intent); } }); }@Override Public Boolean Oncreateoptionsmenu(Menu menu) {//inflate the menu; This adds items to the action bar if it is present.Getmenuinflater (). Inflate (R.menu.main, menu);return true; }}
Operation via StartService and StopService.
4, we look at the background of Android running process,
5, we first click the Start Service button, and then view the background process
See, this is my service, it started up in the background.
6. We call the StopService method to stop the service,
Android--Service usage