Android Studio: Service of Four Components

Keywords: Android Java xml network

1. Services are basically divided into two forms:

start-up
When an application component (such as Activity) starts a service by calling startService(), the service is in the "startup" state. Once started, the service can run indefinitely in the background, even if the component that started the service has been destroyed. Started services usually perform a single operation and do not return the result to the caller. For example, it may download or upload files over the network. When the operation is completed, the service will stop running on its own.
binding
When an application component is bound to a service by calling bindService(), the service is in a "binding" state. Binding services provide a client-server interface that allows components to interact with services, send requests, obtain results, and even perform these operations across processes using interprocess communication (IPC). The binding service runs only when it is bound to another application component. Multiple components can be bound to the service at the same time, but the service will be destroyed when all the components are unbound.

II. Start Service

1. New Project named Service

Java file (MainActivity. Java (main Activity), HelloIntentService.java)
XML file (activity_main.xml)

2.Strings.xml

<resources>
    <string name="app_name">Service</string>
    <string name="button1_name">StartService</string>
    <string name="button2_name">StopService</string>
</resources>

3.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context=".MainActivity">

     <Button
         android:id="@+id/button1"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:text="@string/button1_name"/>
     <Button
         android:id="@+id/button2"
         android:text="@string/button2_name"
         android:layout_width="match_parent"
         android:layout_height="wrap_content" />
</LinearLayout>

4.MainActivity.java

Button listening events are implemented here using the OnClickListener interface

package com.example.administrator.service;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements View.OnClickListener {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button1=findViewById(R.id.button1);
        Button button2=findViewById(R.id.button2);
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent=new Intent(this,HelloIntentService.class);
        switch (v.getId()){
            case R.id.button1:startService(intent);break;
            case R.id.button2:stopService(intent);break;}
    }
}

5.HelloIntentService.java

5.1

Traditionally, two classes can be extended to create startup services:
Service
This is the base class for all services. When extending this class, a new thread must be created to perform all service work, because by default, the service will use the main thread of the application, which will degrade the performance of all activities that the application is running.
IntentService
This is a subclass of Service, which uses workthreads to process all startup requests one by one. If you do not require the service to process multiple requests at the same time, this is the best choice. You just need to implement the onHandleIntent() method, which receives the Intent for each startup request, enabling you to perform background work.

5.2 The following section describes extending the IntentService class to start the service.

IntentService performs the following actions:
1. Create default worker threads to execute all Intent s passed to onStartCommand() outside the main thread of the application.
2. Create a work queue to pass Intent one by one to onHandleIntent() implementations, so you never have to worry about multithreading.
3. Stop service after all start requests are processed, so you never have to call stopSelf().
4. Provide the default implementation of onBind() (return null). (So there is no need for public IBinder on Bind (Intent intent) {return null;})
5. Provide the default implementation of onStartCommand(), which can send Intent to the work queue and onHandleIntent() implementation in turn. (If you need to rewrite other callback methods (such as onCreate(), onStartCommand() or onDestroy()), be sure to call the superclass implementation so that IntentService can properly handle the lifecycle of the worker thread.)
To sum up, just implement onHandleIntent() to complete the work provided by the client. (However, you also need to provide a small constructor for the service.)

package com.example.administrator.service;

import android.app.IntentService;
import android.content.Intent;
import android.widget.Toast;

public class HelloIntentService extends IntentService {
    public HelloIntentService() {
        super("HelloIntentService");
    }

    /**
     * The IntentService calls this method from the default worker thread with
     * the intent that started the service. When this method returns, IntentService
     * stops the service, as appropriate.
     */
    @Override
    protected void onHandleIntent( Intent intent) {
        // Normally we would do some work here, like download a file.
        // For our sample, we just sleep for 5 seconds.
        try {
            Thread.sleep(5000);
            System.out.println("Thread are sleeping");
        } catch (InterruptedException e) {
            // Restore interrupt status.
            Thread.currentThread().interrupt();
        }
    }
    //onStartCommand() must return to the default implementation (that is, how to pass Intent to onHandleIntent()):
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
        return super.onStartCommand(intent,flags,startId);
    }
    @Override
    public void onDestroy() {
        System.out.println("Service onDestroy");
        super.onDestroy();
    }
}

6. implementation

Click on the Start Service button and it will stop automatically after 5 seconds of sleep.
If you click the Start Service button, and then immediately click the Stop Service button, it will stop running directly.

Appendix: & Big Boy's Blog https://blog.csdn.net/javazejian/article/details/52709857
& Official Documents https://developer.android.google.cn/guide/components/services
& Several Settings of Button Monitoring Events https://www.cnblogs.com/xiao-chuan/p/6074075.html
& Learning Course Video Address: Chapter 6 Service of Four Components https://www.imooc.com/learn/179

Posted by creativodev on Fri, 10 May 2019 12:00:21 -0700