Android App Development Basics (6)-----Service

Source: Internet
Author: User

Link Address: http://www.cnblogs.com/lknlfy/archive/2012/02/20/2360336.html

I. Overview

We know that service is one of the four components of Android. In my opinion, services can be understood as a service running in the background, but it is not run in a separate thread, but runs in the main thread, and when the program has a "heavy" task to execute, it can be placed in the service execution. The service also has its own life cycle, which is somewhat similar to activity, but it does not have a user interface and runs only in the background.

Second, the requirements

Write a program with service, in which the user can start and stop the service and communicate with the service.

Third, the realization

Create a new project MyService, modify the/res/layout/main.xml file, add 3 button buttons and a TextView text inside, complete the Main.xml file as follows:

1 <?xml version= "1.0" encoding= "Utf-8"?>
2 <linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
3 android:layout_width= "Fill_parent"
4 android:layout_height= "Fill_parent"
5 android:orientation= "Vertical" >
6
7 <button
8 android:id= "@+id/button"
9 android:layout_width= "Fill_parent"
Ten android:layout_height= "Wrap_content"
android:text= "Start Service"
Android:textsize= "15px"
/>
14
<button
Android:id= "@+id/sbutton"
Android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
android:text= "Stop Service"
Android:textsize= "15px"
/>
22
<button
Android:id= "@+id/gbutton"
Android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
android:text= "Get Service Information"
Android:textsize= "15px"
/>
30
<view
Android:layout_width= "Fill_parent"
android:layout_height= "70px"
/>
35
Approx. <textview
PNS android:id= "@+id/mtextview"
Android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
Android:gravity= "Center_horizontal"
Android:textsize= "20px"
Android:textcolor= "#0000FF"
/>
44
</LinearLayout>

Create a new Myservice.java file, write a MyService class that inherits from the service, write a Mybinder class that inherits from Binder in the class, used to communicate with the client, write a returnservice in the Mybinder class () method, which is used to return information to the client, complete

The Myservice.java file is as follows:

1 package com.nan.service;
2
3 Import Android.app.Service;
4 Import android.content.Intent;
5 Import Android.os.Binder;
6 Import Android.os.IBinder;
7 Import Android.util.Log;
8
9 public class MyService extends Service
10 {
One final String TAG = "MyService";
12
Mybinder Mmybinder = new Mybinder ();
14
@Override
IBinder Onbind (Intent arg0)
17 {
/TODO auto-generated Method stub
19//Return object to Client
return mmybinder;
21}
22
@Override
public boolean onunbind (Intent Intent)
25 {
26
return true;
28}
29
@Override
to public void OnCreate ()
32 {
Super.oncreate ();
LOG.V (TAG, "+ + onCreate () + +");
35}
36
Panax Notoginseng @Override
$ public int Onstartcommand (Intent Intent, int flags, int startid)
39 {
Super.onstartcommand (Intent, flags, Startid);
LOG.V (TAG, "+ + Onstartcommand () + +");
The return of the flags;
43}
44
@Override
OnDestroy public void ()
47 {
Super.ondestroy ();
LOG.V (TAG, "+ + OnDestroy () + +");
50}
51
52//Define yourself a class that inherits from Binder
public class Mybinder extends Binder
54 {
55//Return information in service
$ public String Returnservice ()
57 {
"This String is from servive!";
59}
60}
61
62}

Next, modify the Myserviceactivity.java file, define 1 Myservice.mybinder objects, and a Serviceconnection object, to implement
The onserviceconnected () method in Serviceconnection, which is automatically called after Bindservice (), receives the binder object from MyService. Other content in the program has detailed comments, the complete Myserviceactivity.java file is as follows:

1 package com.nan.service;
2
3 Import Com.nan.service.MyService.MyBinder;
4 Import android.app.Activity;
5 Import Android.content.ComponentName;
6 Import android.content.Intent;
7 Import android.content.ServiceConnection;
8 Import Android.os.Bundle;
9 Import Android.os.IBinder;
Ten import Android.view.View;
Import Android.widget.Button;
Import Android.widget.TextView;
13
14
public class Myserviceactivity extends Activity
16 {
+ private Button Mbutton = null;
Private Button Sbutton = null;
Private Button Gbutton = null;
Private TextView Mtextview = null;
21//Define a Mybinder object
The private Myservice.mybinder Mbinder;
23//Define a Serviceconnection object
Private Serviceconnection mserviceconnection;
Private Intent mintent = new Intent ();
26
/** called when the activity is first created. */
@Override
public void OnCreate (Bundle savedinstancestate)
30 {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
33
Mbutton = (Button) Findviewbyid (R.id.button);
Sbutton = (Button) Findviewbyid (R.id.sbutton);
Gbutton = (Button) Findviewbyid (R.id.gbutton);
PNS Mtextview = (TextView) Findviewbyid (R.id.mtextview);
38
39//Set button action handling
Mbutton.setonclicklistener (New View.onclicklistener ()
41 {
42
@Override
The public void OnClick (View v)
45 {
$//TODO auto-generated method stub
47//Set to start the service class
Mintent.setclass (Myserviceactivity.this, Myservice.class);
49//Bind (build) This service
Bindservice (mintent,mserviceconnection,bind_auto_create);
51}
52});
53
Sbutton.setenabled (FALSE);
55//Set button action handling
Sbutton.setonclicklistener (New View.onclicklistener ()
57 {
58
@Override
public void OnClick (View v)
61 {
+//TODO auto-generated method stub
63//Cancel the connection to the service
Unbindservice (mserviceconnection);
Mbutton.setenabled (TRUE);
Sbutton.setenabled (FALSE);
Gbutton.setenabled (FALSE);
68}
69});
70
Gbutton.setenabled (FALSE);
72//Set button action handling
Gbutton.setonclicklistener (New View.onclicklistener ()
74 {
75
@Override
The public void OnClick (View v)
78 {
/TODO auto-generated Method stub
80//Show information returned from the service
Bayi Mtextview.settext (Mbinder.returnservice ());
82}
83});
84
85//Similar to the use of the handler class
Mserviceconnection = new Serviceconnection ()
87 {
88
@Override
90//When a connection is established with the service, this function is automatically called
onserviceconnected public void (componentname name, IBinder service)
92 {
/TODO auto-generated Method stub
94//Get IBinder object from service
Mbinder = (mybinder) service;
Sbutton.setenabled (TRUE);
Mbutton.setenabled (FALSE);
98 gbutton.setenabled (TRUE);
99}
100
101 @Override
102//When disconnected from service, this function is automatically called
103 public void onservicedisconnected (componentname name)
104 {
//TODO auto-generated method stub
106
107}
108
109};
110
111}
112
113}

Finally, in the Androidmanifest.xml file, add a service statement inside, as follows:

<service android:name= ". MyService "android:exported=" true "/>

Run the program:

Click on the "Start Service" button:

Then click on the "Get Service Info" button and a string will appear stating that the information has been obtained from the service:

Click the "Stop Service" button:

Complete.

Android App Development Basics (6)-----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.