Easy Tutorial
❮ State Vs Strategy Bucket Sort ❯

4.2.1 Introduction to Services

Category Android Basic Tutorial

Introduction to This Section

>

Alright, in the previous three sections, we studied the Activity in Android, and I believe everyone has benefited a lot from it!

Starting with this section, let's continue to learn about the second component in Android: Service.

Well, without further ado, let's begin with the content of this section!


1. Concepts Related to Threads

>

Before we start learning about Services, let's first understand some concepts about threads!

1) Related Concepts:

>

2) The Life Cycle of Threads:

3) Three Ways to Create Threads:

>

new Thread(new Runnable(){
     public void run();
         }).start();

2. The Difference Between Service and Thread

>

In fact, there is not much relationship between the two, but many friends often confuse the two!

Thread is a thread, the smallest unit of program execution, the basic unit of CPU allocation!

Service, on the other hand, is a component provided by Android that allows long-term residence in the background, the most common use is for polling operations! Or if you want to do something in the background, such as background downloading updates!

Remember not to confuse these two concepts!


3. Service Lifecycle Diagram


4. Lifecycle Analysis

Well, from the above lifecycle diagram, we can know that there are two ways to use Service in Android:

>

1) StartService() to start the Service BindService() to start the Service


1) Detailed Explanation of Related Methods:

>


2) StartService to Start the Service

>

The first start will create a Service instance, and call the onCreate() and onStartCommand() methods in turn, at this time the Service enters the running state, if StartService is called again to start the Service, a new Service object will not be created again, the system will directly reuse the previously created Service object, and call its onStartCommand() method! But such a Service has no necessary connection with its caller, that is to say, when the caller ends its own lifecycle, as long as stopService is not called, the Service will continue to run! No matter how many times the Service is started, only one StopService call is needed to stop the Service.


3) BindService to Start the Service

>

**① start = (Button) findViewById(R.id.btnstart); stop = (Button) findViewById(R.id.btnstop); // Create an Intent for starting the Service and its properties final Intent intent = new Intent(); intent.setAction("com.jay.example.service.TEST_SERVICE1"); // Set click events for the two buttons, which are to start and stop the service start.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) { startService(intent);
} });

stop.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) { stopService(intent); } });

}

Running Screenshots:

Click Start Service:

If you're full from eating and have nothing to do, click a few more times:

Finally, click Stop Service:

Result Analysis:

From the above running results, we can verify the content explained in our lifecycle diagram: We find that the onBind() method is not called, and when we click to start the Service multiple times, only the onStartCommand method is repeatedly called! No matter how many times we start the Service, one stopService will stop the Service!


2) Verify the order of starting the Service with BindService:

Before we start writing the code, let's first understand some things: The first is the Context's bindService method given below the first large diagram:

>

Summary: Step 1: In the custom Service, inherit Binder and implement your own IBinder object. Step 2: Return your own IBinder object through the onBind() method. Step 3: In the class that binds to this Service, define a ServiceConnection object and override two methods, onServiceConnected and onDisconnected! Then you can directly read the IBinder parameter passed!

Well, now it's time to write the code to verify. Here, we define a Service for timing, and then demonstrate the usage of BindService and the method call process! The code is relatively simple, no explanation needed!

TestService2.java:

public class TestService2 extends Service {  
    private final String TAG = "TestService2";  
    private int count;  
    private boolean quit;  

    // Define the object returned by the onBinder method
    private MyBinder binder = new MyBinder();  
    public class MyBinder extends Binder  
    {  
        public int getCount()  
        {  
            return count;  
        }  
    }  

    // The method that must be implemented, called back when the Service is bound
    @Override  
    public IBinder onBind(Intent intent) {  
        Log.i(TAG, "onBind method is called!");  
        return binder;  
    }  

    // The method called back when the Service is created
    @Override  
    public void onCreate() {  
        super.onCreate();  
        Log.i(TAG, "onCreate method is called!");  
        // Create a thread to dynamically change the value of count
        new Thread()  
        {  
            public void run()   
            {  
                while(!quit)  
                {  
                    try  
                    {  
                        Thread.sleep(1000);  
                    }catch(InterruptedException e){e.printStackTrace();}  
                    count++;  
                }  
            }  
        }.start();  
    }  

    // The method called back when the Service is disconnected
    @Override  
    public boolean onUnbind(Intent intent) {  
        Log.i(TAG, "onUnbind method is called!");  
        return true;  
    }  

    // The method called back before the Service is closed
    @Override  
    public void onDestroy() {  
        super.onDestroy();  
        this.quit = true;  
        Log.i(TAG, "onDestroyed method is called!");  
    }  

    @Override  
    public void onRebind(Intent intent) {  
        Log.i(TAG, "onRebind method is called!");  
        super.onRebind(intent);  
    }  
}

Register the Service component in AndroidManifest.xml:

<service android:name=".TestService2" android:exported="false">  

bindService(intent, conn, Service.BIND_AUTO_CREATE);
}
});

btncancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
    //unbind service
    unbindService(conn);                  
}
});

btnstatus.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
    Toast.makeText(getApplicationContext(), "Service's count value is:" 
            + binder.getCount(), Toast.LENGTH_SHORT).show();
}
});
}

Running screenshot:

Click to lock Service:

Continue to click lock: No changes

Get the current status of Service:

Unbind:

If we bind and then directly close the Activity, an error will occur, then automatically call onUnbind and onDestory methods!

The above running results verify the lifecycle diagram:

>

Using BindService to bind Service, it calls onCreate(), onBind() methods in order, we can return a custom IBinder object in the onBind() method; then it calls the ServiceConnection's onServiceConnected() method where the IBinder object can be obtained, and thus perform related operations; when the Service is unbound, it will automatically call onUnbind and onDestroyed methods, of course, in the case of multiple clients binding, all the bindings need to be unbound to call the onDestroyed method for destruction!

-1.0 Android Basic Tutorial Introduction

-1.0.1 Latest Android Basic Tutorial Catalog for 2015

-1.1 Background and System Architecture Analysis

-1.2 Development Environment Setup

-1.2.1 Developing Android APP with Eclipse + ADT + SDK

-1.2.2 Developing Android APP with Android Studio

-1.3 SDK Update Issue Resolution

-1.4 Genymotion Emulator Installation

-1.5.1 Git Tutorial on Basic Operations of Local Repositories

-1.5.2 Git Using GitHub to Set Up a Remote Repository

-1.6 How to Play with 9 (Nine Sister) Images

-1.7 Interface Prototype Design

-1.8 Project Related Analysis (Various Files, Resource Access)

-1.9 Android Program Signing and Packaging

-1.11 Decompile APK to Get Code & Resources

-2.1 The Concept of View and ViewGroup

-2.2.1 LinearLayout (Linear Layout)

-2.2.2 RelativeLayout (Relative Layout)

-2.2.3 TableLayout (Table Layout)

-2.2.4 FrameLayout (Frame Layout)

-2.2.5 GridLayout (Grid Layout)

-2.2.6 AbsoluteLayout (Absolute Layout)

-2.3.1 TextView (Text Box) Detailed Explanation

-2.3.2 EditText (Input Box) Detailed Explanation

-2.3.3 Button (Button) and ImageButton (Image Button)

-2.3.4 ImageView (Image View)

-2.3.5 RadioButton (Radio Button) & Checkbox (Checkbox)

-2.3.6 ToggleButton (Toggle Button) and Switch (Switch)

-2.3.7 ProgressBar (Progress Bar)

-2.3.8 SeekBar (Slider)

-2.3.9 RatingBar (Star Rating Bar)

-2.4.1 ScrollView (Scroll View)

-2.4.2 Date & Time Components (Part 1)

-[2.4.3 Date & Time Components (Part 2)]

WeChat Follow

❮ State Vs Strategy Bucket Sort ❯