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:
>
Program: A set of instructions written in a certain language to complete a specific task (a set of static code).
Process: A running program, an independent unit for system scheduling and resource allocation, the operating system will allocate a memory space for each process! The program is executed in sequence, experiencing the complete process of code loading, execution, and completion!
Thread: A smaller unit of execution than a process, each process may have multiple threads, threads need to be placed in a process to be executed, threads are managed by the program, and processes are scheduled by the system!
Understanding of Multithreading: Parallel execution of multiple instructions, the CPU time slice is allocated to each thread according to the scheduling algorithm, which is actually time-sharing execution, it's just that the switching time is very short, and the user feels "simultaneous"!
2) The Life Cycle of Threads:
3) Three Ways to Create Threads:
>
Inheriting the Thread Class
Implementing the Runnable Interface
Implementing the Callable Interface If: If the thread is created using 2, it can be started directly like this:
new Thread(myThread).start();
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:
>
onCreate(): This method is called immediately after the Service is created for the first time, and it is called only once in the entire lifecycle!
onDestory(): This method is called when the Service is closed, and it is called only once!
onStartCommand(intent, flag, startId): In the early versions, it was onStart(intent, startId), when the client calls the startService(Intent) method, it will be called, the StartService method can be called multiple times, but it will not create a new Service object again, but will continue to reuse the Service object previously generated, but will continue to call the onStartCommand() method!
IBinder onOnbind(intent): This method is a method that all Services must implement, this method will return an IBinder object, the app communicates with the Service component through this object!
onUnbind(intent): This method is called when all clients bound to the Service are disconnected!
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:
>
ServiceConnection object: Listens for the connection status between the visitor and the Service. If successfully connected, the callback onServiceConnected() is called. If the connection is terminated due to an exception or other reasons, the onServiceDisconnected method is called. Unbinding the Service with unBindService() will not call this method!
In the onServiceConnected method, there is an IBinder object, which can facilitate communication with the bound Service! When we develop the Service class, by default, we need to implement the IBinder onBind() method. The IBinder object returned by this method will be passed to the ServiceConnection object's onServiceConnected parameter, and we can communicate with the Service through this IBinder here!
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.5 RadioButton (Radio Button) & Checkbox (Checkbox)
-2.3.6 ToggleButton (Toggle Button) and Switch (Switch)
-2.3.7 ProgressBar (Progress Bar)
-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)]
4.2.1 Service Introduction
5.2.1 Fragment Detailed Example – Bottom Navigation Bar Implementation (Method 1)
5.2.2 Fragment Detailed Example – Bottom Navigation Bar Implementation (Method 2)
5.2.3 Fragment Detailed Example – Bottom Navigation Bar Implementation (Method 3)
5.2.4 Fragment Detailed Example – Bottom Navigation Bar + ViewPager Page Swiping
5.2.5 Fragment Detailed Example – Simple Implementation of News (Shopping) App List Fragment
6.2 Data Storage and Access – SharedPreferences Saving User Preferences
[8.2.1
12.2 DrySister Viewing Girls App (First Edition) — 2. Parsing Backend Data
12.4 DrySister Viewing Girls App (First Edition) — 4. Adding Data Caching (Integrating SQLite)