Some programs do not need to interact, run in the background, and can run for a long time without being killed by the operating system, which is the component Service
-
Statement Service, New class,MyService, extended from service
-
configuration in Androidmanifest, add serivice in Application, select myserivice
Actually added a line:
<serviceandroid:name= "MyService" ></service>
-
add two buttons to start Service and stop service
<button
Android:id= "@+id/btnstartservice"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:text= " start servive"/>
<button
Android:id= "@+id/btnstopservice"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:text= " stop Service"/>
4) Add the definition of the two button in the code:
Private Button Btnstartservice , Btnstopservice ;
@Override
protectedvoid onCreate (Bundle savedinstancestate) {
Super. OnCreate (savedinstancestate);
Setcontentview (r.layout. Activity_main );
btnstartservice= (Button) Findviewbyid (r.id. Btnstartservice );
btnstopservice= (Button) Findviewbyid (r.id. Btnstopservice );
}
5) Add two button listening event, the mouse is placed at the red line, can be automatically generated:
(1) Btnstartservice.setonclicklistener (this);
(2) public class Mainactivity extendsactionbaractivity implements Onclicklistener
(3) @Override
Publicvoid OnClick (View v) {
TODO auto-generated Method Stub
}
6) specific onClick content :
@Override
Publicvoid OnClick (View v) {
TODO auto-generated Method Stub
Switch (V.getid ()) {
Case R.id.btnstartservice:
Break
Case R.id.btnstopservice:
Break
Default
Break
}
7) Start Service , you need to define Intent ,:
Private Intent serviceintent;
and create an instance :
Serviceintent=newintent (This,myservice.class);
8) in our Service Rewrite two method, create and destroy:
@Override
Publicvoid OnCreate () {
System.out.println (" created well ");
Super.oncreate ();
}
@Override
Publicvoid OnDestroy () {
System.out.println (" destroyed ");
Super.ondestroy ();
}
9) the current Activity is destroyed , the Service will run again , by setting - > Applications - run programs or services that you can see.
This article is from "Blue Sea Tactics" blog, please make sure to keep this source http://wanxl.blog.51cto.com/2129901/1589490
10-Day Learning Android Development (2-2)-Core component service creation