Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Android Services


May 21, 2021 Android


Table of contents


Android Services

A service is a component that runs in the background and performs long-running tasks that do not require user interaction. A pplications can still work even if they are destroyed. The service basically consists of two states -

State Describe
Started Android's application components, such as activities, start the service through StartService(), and the service is in TheStarted state. Once started, the service can run indefinitely in the background, even if the component that started it has been destroyed.
Bound When an Android application component binds a service through bindService(), the service is in a Bound state. The Bound state service provides a customer server interface that allows components to interact with the service, such as sending requests, getting results, and even communicating across processes through the IPC.

A service has a lifecycle approach that enables monitoring changes in service status and can perform work at the right stage. The following image on the left shows the declaration cycle when a service is created through startService(), and the figure on the right shows the life cycle when a service is created through bindService():

Android Services Android Services

To create a service, you need to create a Java class that inherits from the service base class or its known sub-classes. T he service base class defines different callback methods and most important methods. Y ou don't need to implement all the callback methods. N evertheless, it is important to understand all methods. Implementing these callbacks ensures that your app is implemented the way users expect it to.

Callback Describe
onStartCommand() The method is called by the system when other components, such as activities, request that the service be started by calling start-up services. If you implement this approach, it is your responsibility to stop the service by stoping the service by stoping the topSelf() or stop Service () method when the work is complete.
onBind The method is called when other components want to bindService() to bindService(). I f you implement this method, you need to return the IBinder object to provide an interface so that the customer can communicate with the service. You must implement this method and return null directly if you do not allow binding.
onUnbind() The method is called when the customer interrupts a special interface for all service releases.
onRebind() The method is called when a new client is connected to the service and it has previously been disconnected by an onUnbind notification.
onCreate() The method is called when the service is first created through onStartCommand() and onBind(). The call requires a one-time installation.
onDestroy() The method is called when the service is no longer useful or destroyed. Your service needs to implement this method to clean up any resources, such as threads, registered listeners, receivers, etc.

The following main service demonstrates the lifecycle of each method -

package cn.uprogrammer.androidservices;

import android.app.Service;
import android.os.IBinder;
import android.content.Intent;
import android.os.Bundle;

public class HelloService extends Service {

    /** 标识服务如果被杀死之后的行为 */
    int mStartMode;

    /** 绑定的客户端接口 */
    IBinder mBinder;

    /** 标识是否可以使用onRebind */
    boolean mAllowRebind;

    /** 当服务被创建时调用. */
    @Override
    public void onCreate() {

    }

    /** 调用startService()启动服务时回调 */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return mStartMode;
    }

    /** 通过bindService()绑定到服务的客户端 */
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    /** 通过unbindService()解除所有客户端绑定时调用 */
    @Override
    public boolean onUnbind(Intent intent) {
        return mAllowRebind;
    }

    /** 通过bindService()将客户端绑定到服务时调用*/
    @Override
    public void onRebind(Intent intent) {

    }

    /** 服务不再有用且将要被销毁时调用 */
    @Override
    public void onDestroy() {

    }
}

This example will show you how to create your own Android service in a simple step. Follow these steps to modify the Android application you created earlier in the Hello World Instances section:

Steps Describe
1 Use the Android Studio IDE to create the Android app and name it androidservices under the cn.uprogrammer.androidservices package. Similar to the Hello World instance chapter.
2 Modify the main activity file MainActivity .java to add startService() and StopService() methods.
3 Create a new Java file MyService under package cn.uprogrammer.androidservices.java. This file will implement the Android service-related approach.
4 Define the service .xml in the Android Manifest file. An application can have one or more services without any restrictions.
5 Modify the default layout in the activity_main.xml/layout/layout, including two buttons in the linear layout.
6 Do not modify any constants in the res/values/strings .xml file in the file. Android Studio pays attention to string values.
7 Launch the Android simulator to run the app and verify the results of the changes made by the app.

The following is the main activity file src/cn.uprogrammer.androidservices/mainActivity.java the main event file. T his file contains all the basic lifecycle methods. We've added startservice() and stop service methods.

package cn.uprogrammer.androidservices;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;


import android.content.Intent;
import android.view.View;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    // Method to start the service
    public void startService(View view) {
        startService(new Intent(getBaseContext(), MyService.class));
    }

    // Method to stop the service
    public void stopService(View view) {
        stopService(new Intent(getBaseContext(), MyService.class));
    }
}

Here's what src/cn.uprogrammer.androidservices/MyService .java content. T his file can implement one or more service association methods based on requirements. For newcomers, we only implement onStartCommand() and onDestroy() -

package cn.uprogrammer.androidservices;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Let it continue running until it is stopped.
        Toast.makeText(this, "服务已经启动", Toast.LENGTH_LONG).show();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "服务已经停止", Toast.LENGTH_LONG).show();
    }
}

The Android Manifest file will .xml below. Add the hashtag here to include our services:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.uprogrammer.androidservices"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk
        android:minSdkVersion="13"
        android:targetSdkVersion="22" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>

        </activity>

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

    </application>

</manifest>

Here's what the res/layout/activity_main.xml file contains two buttons:

<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android 服务实例"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textSize="30dp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="www.uprogrammer.cn"
        android:textColor="#ff87ff09"
        android:textSize="30dp"
        android:layout_above="@+id/imageButton"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="40dp" />

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageButton"
        android:src="@drawable/ic_launcher"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button2"
        android:text="启动服务"
        android:onClick="startService"
        android:layout_below="@+id/imageButton"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="停止服务"
        android:id="@+id/button"
        android:onClick="stopService"
        android:layout_below="@+id/button2"
        android:layout_alignLeft="@+id/button2"
        android:layout_alignStart="@+id/button2"
        android:layout_alignRight="@+id/button2"
        android:layout_alignEnd="@+id/button2" />

</RelativeLayout>

Here's what res/values/strings .xml to define two new constants:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Android Services</string>
    <string name="title_activity_main">MainActivity</string>
    <string name="menu_settings">Settings</string>
    <string name="action_settings">Settings</string>

</resources>

Let's run the My Application application that we just modified. L et me assume that you created the AVD when you installed the environment. O pen the active file in Android Services your project and click the icon in the toolbar to run the app in Android Studio. A ndroid Studio installs the app on the AVD and launches it. If all goes well, it will appear on the emulator window as follows:

Android Services

Now click the "Start Service" button to start the service, which will execute the onStartCommand() method we wrote, and a "Service started" message appears at the bottom of the emulator, as follows:

Android Services

You can stop the service by clicking the Stop Service button at the bottom.