Learn Android<service services from scratch. 43 .>

Source: Internet
Author: User

Services is an important component in the development of Android systems. If some of the operations that some programs require now are time-consuming, you can define them in the service so that you can run the program in the background (or run in the form of a non-display interface), which is: Services It's actually the equivalent of a non-graphical interface. Activity program, and the service can be used when the user wants to perform certain operations that require cross-process access. Service is an operating component without UI interface, the main function is to provide some necessary support for the activity program, such as: MP3 player software in the mobile phone, the components can still run when they return to the desktop, in fact, these are the functions of the service, At development time, the user only needs to inherit from the Android.app.Service class to complete the service program development, in the service also has its own life cycle method.
Next, use an example to illustrate the life cycle of the service.
<relativelayout 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:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools: Context= ". Mainactivity "> <button android:id=" @+id/button1 "android:layout_width=" Wrap_content "Androi        d:layout_height= "Wrap_content" android:layout_alignparenttop= "true" android:layout_centerhorizontal= "true"         android:layout_margintop= "90DP" android:text= "open service"/> <button android:id= "@+id/button2" Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_alignleft= "@ +id/button1 "android:layout_below=" @+id/buttoN1 "android:layout_margintop=" 100DP "android:text=" Close Service "/></relativelayout> 

Sevice
Package Com.example.service2;import Android.app.service;import Android.content.intent;import android.os.IBinder; Import Android.util.log;public class MyService extends Service {@Overridepublic ibinder onbind (Intent Intent) {//TODO Aut O-generated method Stubreturn null;} @Overridepublic void OnCreate () {//TODO auto-generated method Stubsuper.oncreate (); LOG.I ("Log", "OnCreate");} @Overridepublic void OnDestroy () {//TODO auto-generated method Stubsuper.ondestroy (); LOG.I ("Log", "OnDestroy");} @Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) {//TODO auto-generated method stublog.i ("Log", "Onstartcommand"); return Super.onstartcommand (Intent, flags, Startid);}}

Main class
Package Com.example.service2;import Android.os.bundle;import Android.app.activity;import android.content.Intent; Import Android.view.menu;import Android.view.view;import Android.widget.button;public class MainActivity extends Activity {Private Button button1, button2; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main); button1 = (Button) This.findviewbyid (R.id.button1); Button2 = (Button) This.findviewbyid (R.id.button2); Button1.setonclicklistener (new View.onclicklistener () {@ overridepublic void OnClick (View v) {//TODO auto-generated method stubintent intent=new Intent (Mainactivity.this, MyServ Ice.class); StartService (intent);}); Button2.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated Method Stubintent Intent=new Intent (mainactivity.this, Myservice.class); StopService (intent);}});}}





To bind a service to activity
<relativelayout 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:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools: Context= ". Mainactivity "> <button android:id=" @+id/button1 "android:layout_width=" Wrap_content "Androi        d:layout_height= "Wrap_content" android:layout_alignleft= "@+id/button2" android:layout_alignparenttop= "true" android:layout_margintop= "22DP" android:text= "open service"/> <button android:id= "@+id/button2 "Android:layout_width=" wrap_content "android:layout_height=" Wrap_content "android:layout_alignright= "@+id/button4" android:layout_below= "@+id/butTon4 "android:layout_margintop=" 32DP "android:text=" close service "/> <button android:id=" @+id/b Utton3 "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "android:layout_align left= "@+id/button1" android:layout_below= "@+id/button1" android:layout_margintop= "32DP" android:text= "Bind service"/> <button android:id= "@+id/button4" android:layout_width= "Wrap_content" Android        : layout_height= "Wrap_content" android:layout_centerhorizontal= "true" android:layout_centervertical= "true" android:text= "Unbind"/></relativelayout>
Service
Package Com.example.service1;import Android.app.service;import Android.content.intent;import android.os.Binder; Import Android.os.ibinder;public class MyService extends Service {private IBinder Mybinder = new Binder () {@Override//serv Ice defines the method public String Getinterfacedescriptor () {System.out.println ("***mybinder"); return "MyService Class.";}}; @Overridepublic ibinder onbind (Intent Intent) {System.out.println ("* * * Service Onbind ()"); return this.mybinder;// No processing is done here temporarily} @Overridepublic void Onrebind (Intent Intent) {//Rebind System.out.println ("* * * Service Onrebind ()"); Super.onrebind (intent);} @Overridepublic boolean onunbind (Intent Intent) {//unbound System.out.println ("* * * Service Onunbind ()"); return Super.onunbind (intent);} @Overridepublic void OnCreate () {//create servicesuper.oncreate (); SYSTEM.OUT.PRINTLN ("* * * Service onCreate ()");} @Overridepublic void OnDestroy () {//Destroy Servicesuper.ondestroy (); SYSTEM.OUT.PRINTLN ("* * * Service OnDestroy ()");} @Overridepublic int Onstartcommand (Intent Intent, intFlags, int Startid)//Execute SERVICE{SYSTEM.OUT.PRINTLN ("* * * Service onstartcommand"); return Service.start_continuation_ MASK; Continue execution}}

Mainactivity
Package Com.example.service1;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.os.remoteexception;import Android.view.View;import Android.widget.button;public class Mainactivity extends Activity {private Button button1,button2,button3,button4;// Bind service and activity to private serviceconnection serviceconnection = new Serviceconnection () {@Overridepublic void onserviceconnected (componentname name, IBinder service) {try {System.out.println ("# # # Service Connect Success. Service = "+ Service.getinterfacedescriptor ());} catch (RemoteException e) {}} @Overridepublic void onservicedisconnected (componentname name) {System.out.println ("# # #    Service Connect Failure. ");};        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_Main);        button1= (Button) This.findviewbyid (R.id.button1);        Button2= (Button) This.findviewbyid (R.id.button2);        button3= (Button) This.findviewbyid (R.id.button3); button4= (Button) This.findviewbyid (R.ID.BUTTON4);//Start Service monitoring Button1.setonclicklistener (new View.onclicklisten ER () {@Overridepublic void OnClick (View v) {//TODO auto-generated method StubMainActivity.this.startService (New Intent ( Mainactivity.this, Myservice.class)); OnStart ();}); /Shutdown Service Listener Button2.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View v) {//TODO Au         To-generated method StubMainActivity.this.stopService (New Intent (Mainactivity.this, Myservice.class)); OnStop ();}}); Button3.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated met  Hod StubMainActivity.this.bindService (New Intent (Mainactivity.this, Myservice.class), Mainactivity.this.serviceconnection,context.bind_auto_create);}); Button4.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated    Method StubMainActivity.this.unbindService (Serviceconnection);}}); }    }


Open



Binding


Unbind


Destroying service






Using the service to get other operations on the system
1 public static final String Clipboard_service Constant Clipboard Service
2 public static final String Window_service Constant Window Services
3 public static final String Alarm_service Constant Alarm Service
4 public static final String Audio_service Constant Audio Services
5 public static final String Notification_service Constant Notification Service
6 public static final String Search_service Constant Search Service
7 public static final String Power_service Constant Power Management Services
8 public static final String Wifi_service Constant WiFi Service
9 public static final String Activity_service Constant Running the program service

Today, we will simply use two examples to illustrate
Using the service to get the Clipboard service
<relativelayout 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:paddingbottom= "@dimen/activity_vertical_margin"    android:paddingleft= "@dimen/activity_ Horizontal_margin "    android:paddingright=" @dimen/activity_horizontal_margin "    android:paddingtop=" @dimen /activity_vertical_margin "    tools:context=". Mainactivity ">    <edittext        android:id=" @+id/edittext1 "        android:layout_width=" Wrap_content "        android:layout_height= "wrap_content"        android:layout_alignparenttop= "true"        android:layout_ Centerhorizontal= "true"        android:layout_margintop= "41DP"        android:ems= "ten" >        <requestfocus/ >    </EditText></RelativeLayout><strong></strong>


Package Com.example.service3;import Android.os.bundle;import Android.app.activity;import Android.content.clipboardmanager;import Android.view.menu;public class Mainactivity extends Activity {    @Override    protected void OnCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);//        Get Clipboardmanager object Clipboardmanager clipboardmanager= ( Clipboardmanager) Getsystemservice (clipboard_service);//Set Text Clipboardmanager.settext ("Wind snow is not Young");}    }




using the service to operate the phone wifi
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayoutxmlns:android= "http://schemas.android.com/apk/res/ Android "android:orientation=" vertical "android:layout_width=" fill_parent "android:layout_height=" Fill_parent " ><textviewandroid:id= "@+id/msg" android:layout_width= "fill_parent" android:layout_height= "wrap_content"/ ><buttonandroid:id= "@+id/open" android:layout_width= "fill_parent" android:layout_height= "Wrap_content" android:text= "Open WiFi"/><buttonandroid:id= "@+id/close" android:layout_width= "Fill_parent" Android:layout_ height= "Wrap_content" android:text= "Off WiFi"/><buttonandroid:id= "@+id/check" android:layout_width= "Fill_ Parent "android:layout_height=" wrap_content "android:text=" Check wifi status "/></linearlayout>

Package Com.example.service5;import Android.app.activity;import Android.content.context;import Android.net.wifi.wifimanager;import Android.os.bundle;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.textview;public Class  Mainactivity extends Activity {private button open = null;//button component Private button close = null;//button component Private button check = null;//button Component Private TextView msg = null;//text component private Wifimanager Wifimanager = null;//wifi management @overridepublic void Oncre Ate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Super.setcontentview (R.layout.activity_main) ;//Configuration layout Manager This.open = (button) Super.findviewbyid (r.id.open);//Get Component This.close = (Button) Super.findviewbyid ( R.id.close);//Get Component This.check = (Button) Super.findviewbyid (R.id.check);//Get Component this.msg = (TextView) Super.findviewbyid (r.id.msg);//Get Component This.wifimanager = (Wifimanager) super.getsystemservice (Context.WIFI_SERVICE) ;//Get wife service This.open.setOnClickLIstener (New Onclicklistener () {@Overridepublic void OnClick (view view) {MainActivity.this.wifiManager.setWifiEnabled (true); Enable WifiMainActivity.this.msg.setText ("Open WiFi, Status:" + MainActivity.this.wifiManager.getWifiState ());//Set Text}}); This.close.setOnClickListener (New Onclicklistener () {@Overridepublic void OnClick (view view) { MainActivity.this.wifiManager.setWifiEnabled (FALSE); Turn off WIFIMainActivity.this.msg.setText ("Turn off WiFi, status:" + MainActivity.this.wifiManager.getWifiState ());//Set Text}}); This.check.setOnClickListener (New Onclicklistener () {@Overridepublic void OnClick (view view) { MainActivity.this.msg.setText ("Check WiFi, Status:" + MainActivity.this.wifiManager.getWifiState ());//Set Text}});}}





Of course, you can refer to the API below to get other services and configure the corresponding, the others are no longer one by one description.

next section forecast: Notification notice

Learn Android<service services from scratch. 43 .>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.