Beginners take you to learn series Introduction to the use of Android services

Let’s introduce the use of Android services. Interested partners are welcome to come and discuss! ! !

Android service (Service)

A service is a component that runs in the background and performs long-running tasks that do not require user interaction. Works even if the app is destroyed. A service basically contains two states −

Services have [lifecycle] methods that allow you to monitor changes in service state and perform work at the appropriate stage. The following diagram on the left shows the lifecycle when a service is created with startService(), and the diagram on the right shows the lifecycle when a service is created with bindService():

To create a service, you need to create a Java class that inherits from the Service base class or one of its known subclasses. The Service base class defines different callback methods and most important methods. You don’t need to implement all callback methods. Nonetheless, it is important to understand all the methods. Implementing these callbacks ensures that your app performs the way users expect.

The main service below 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 {

    /** Identifies the behavior of the service if it is killed */ 
    int mStartMode;

    /** Binding client interface */
    Binder mBinder;

    /** Identifies whether onRebind can be used */ 
    boolean mAllowRebind;

    /** Called when the service is created. */ 
    @Override 
    public  void  onCreate ()  {

    }

    /** Callback when startService() is called to start the service*/ 
    @Override 
    public  int  onStartCommand (Intent intent, int flags, int startId)  {
         return mStartMode;
    }

    /** Clients bound to the service via bindService() */ 
    @Override 
    public IBinder onBind (Intent intent)  {
         return mBinder;
    }

    /** Called when all clients are unbound via unbindService() */ 
    @Override 
    public  boolean  onUnbind (Intent intent)  {
         return mAllowRebind;
    }

    /** Called when the client is bound to the service via bindService() */ 
    @Override 
    public  void  onRebind (Intent intent)  {

    }

    /** Called when the service is no longer useful and is about to be destroyed */ 
    @Override 
    public  void  onDestroy ()  {

    }
}

Example

This example will show you how to create your own Android service in simple steps. Follow the steps below to modify the Android application created earlier in the Hello World Example chapter:

The following is the modified content of the main activity file src/cn.uprogrammer.androidservices/MainActivity.java file. This file contains all the basic lifecycle methods. I added startService() and stopService() methods to start and stop the service.

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));
    }
}

The following is the content of src/cn.uprogrammer.androidservices/MyService.java. This file can implement one or more service-related 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.
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText( this , "The service has stopped" , Toast.LENGTH_LONG).show();
    }
}

The following will modify the AndroidManifest.xml file. Add the tag here to include our service:

<?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:version>

    <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:
            android:label="@string/title_activity_main" >

            <intent-filter>
                <action android: />
                <category android:/>
            </intent-filter>

        </activity>

        <service android: />

    </application>

</manifest>

Here is the content of the res/layout/activity_main.xml file, which 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: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:onClick="startService"
        android:layout_below="@+id/imageButton"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        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 is the content of res/values/strings.xml to define two new constants:

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

    <string >Android Services</string>
    <string >MainActivity</string>
    <string >Settings</string>
    <string >Settings</string>

</resources>

Let’s run the My Application application we just modified. I’m assuming you’ve created the AVD when installing the environment. Open the active file in your project and click the icon in the toolbar to run the application in Android Studio. Android Studio installs the app on the AVD and launches it. If all goes well, the following will appear on the emulator window:

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

Leave a Comment

Your email address will not be published. Required fields are marked *