Android Development Practice Service

Source: Internet
Author: User

Service is the most similar component of Android's four components and activity, all of which represent executable programs, except that the service is running in the background and has no user interface.

Class diagram and life cycle of 1.Service

First look at the class diagram of the service:

Next look at the service life cycle:

2. Development Service

(1) Development service requires two steps:
1th Step: Define subclasses, inherit service
2nd Step: Configure the service in the Androidmanifest.xml file

(2) Create service

 Public  class myservice extends Service {    //Must be implemented, callback when binding the service    @Override     PublicIBinderOnbind(Intent Intent) {return NULL; }//service is created when callback    @Override     Public void onCreate() {Super. OnCreate ();//define related business logicSystem.out.println ("Service is Created"); }callback when service is started    @Override     Public int Onstartcommand(Intent Intent,intFlagsintStartid) {//define related business logicSystem.out.println ("Service is Started");returnStart_sticky; }//service is turned off before callback    @Override     Public void OnDestroy() {Super. OnDestroy (); System.out.println ("Service is destroyed"); }}

(3) Configuring the service

<application ... <! --Configure a Service component- ->          <service android:name=". MyService ">        <intent-filter>            <!--Configure the Intent-filter for the service component            <action android:name="Com.gc.service.MY_SERVICE" />        </intent-filter>    </Service></Application>

Next, you can run the service.

(4) Start and stop service (general mode)

// 创建启动Service的Intentfinal Intent intent = new Intent();// 为Intent设置Action属性intent.setAction("com.gc.service.MY_SERVICE");...// 启动指定SerivcestartService(intent);...// 停止指定SerivcestopService(intent);

When the program starts and shuts down the service using StartService (), StopService (), the service is unable to communicate with the visitor, and the data is exchanged, so another way to start and stop the service is described below.

(5) Start and stop service (BIND service and communicate with it)

If a method call or data exchange is required between the service and the visitor, the service should be started and stopped using the Bindservice () and Unbindservice () methods.

bindService(Intent intent, ServiceConnection conn, int flags),三个参数如下:intent:指定要启动的Serviceconn:用于监听访问者与Service之间的连接情况,当访问者与Service之间连接成功时将回调该ServiceConnection对象的onServiceConnected(ComponentName name, IBinder service)方法;反之回调该ServiceConnection对象的onServiceDisconnected(ComponentName name)方法(主动调用unbindService方法断开连接时则不回调)flags:指定绑定时是否创建Service,0:不自动创建;BIND_AUTO_CREATE:自动创建注意:ServiceConnection对象的onServiceConnected方法中有一个IBinder对象,该对象即可实现与绑定Service之间的通信。在绑定本地Service的情况下,onBind(Intent intent)方法所返回的IBinder对象将会传给ServiceConnection对象里onServiceConnected(ComponentName name, IBinder service)方法的service参数,这样访问者就可以通过该IBinder对象与Service进行通信。

The actual development usually implements its own IBinder object in the way of inheriting binder (IBinder implementation Class).

 Public  class myservice extends Service {    Private intCount//Define the object returned by the Onbinder method    PrivateMybinder Binder =NewMybinder ();//By inheriting binders to implement the IBinder class     Public  class mybinder extends Binder {         Public int GetCount() {returnCount//Get service running status}    }//Must be implemented, callback when binding the service    @Override     PublicIBinderOnbind(Intent Intent) {System.out.println ("Service is binded");returnBinder//Return IBinder object}//service is created when callback    @Override     Public void onCreate() {Super. OnCreate (); System.out.println ("Service is Created"); Count = -; }callback when service is disconnected    @Override     Public Boolean Onunbind(Intent Intent) {System.out.println ("Service is unbinded");return true; }//service is turned off before callback    @Override     Public void OnDestroy() {Super. OnDestroy (); System.out.println ("Service is destroyed"); }}

Next, define an activity to bind the service, and in that activity, access the internal state of the service through the Mybinder object.

After the activity binds the service, the activity can also get the service's running state through the Mybinder object. For the IBinder object returned by the service's Onbind (Intent Intent) method, the service allows the client to access the data inside the service through the IBinder object, which enables the client to communicate with the service.

 Public  class myservicetest extends Activity {    IBinder object for//serviceMyservice.mybinder Binder;//Define a Serviceconnection object    PrivateServiceconnection conn =NewServiceconnection () {//callback when the activity and service connection is successful        @Override         Public void onserviceconnected(componentname name, IBinder service) {//Gets the Mybinder object returned by the Onbind method of the serviceBinder = (myservice.mybinder) service; }//callback when the activity is disconnected from the service        @Override         Public void onservicedisconnected(componentname name) {        }    };@Override     Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); ...//Create a intent to start the service        FinalIntent Intent =NewIntent ();//Set the Action property for intentIntent.setaction ("Com.gc.service.MY_SERVICE");//bind specified SerivceBindservice (Intent, Conn, service.bind_auto_create); ... binder.getcount ();//Get the Count value of Serivce...//Unbind SerivceUnbindservice (conn); }}

Android Development Practice Service

Related Article

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.