SoFunction
Updated on 2025-03-01

Detailed explanation of Service (service) instances of the four major components of Android

This article describes the service usage of the four major components of Android. Share it for your reference, as follows:

In many cases, some applications that rarely need to interact with users, we usually just have to run them in the background, and we can still run other applications while they are running.

To handle such background processes, Android introduced the concept of Service. Service is a long life cycle component in Android, which does not implement any user interface.

Basic concepts

Ÿ   Service is a component that runs in the background without an interface, starting with calls from other components.
Ÿ   Create Service, define the class inheritance Service, and define <service>
Ÿ   Open Service and call the startService method in other components
Ÿ   Stop Service and call the stopService method

1. Call service in activity

/*
  * Turn on the service
  */
public void start(View view) {
  Intent intent = new Intent(this, );
  startService(intent);
}
/*
  * End service
  */
public void stop(View view) {
  Intent intent = new Intent(this, );
  stopService(intent);
}

2. Define Service:

public class MyService extends Service {
  /*
    * Called during binding
    */
  public IBinder onBind(Intent intent) {
    return null;
  }
  /*
    * Called when opening the service
    */
  public void onCreate() {
    ();
    ("onCreate");
  }
  /*
    * Called at the end of service
    */
  public void onDestroy() {
    ();
    ("onDestroy");
  }
}

3. Define services in the manifest file

Copy the codeThe code is as follows:
<service android:name=".PMyService" />

Telephone recording

Telephone recording is implemented using services, which runs in the background and uses a monitor to monitor the status of the phone. When the call is incoming, the monitor obtains the phone number of the incoming call. When the user answers, it starts recording. When the monitor has hung up the status of the phone, it stops recording and saves the recording to the sdcard.

Java code:

@Override
public void onCreate() {
  //Get the telephone service  TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
  //The status listener of the phone  (new MyListener(), PhoneStateListener.LISTEN_CALL_STATE);
}
private final class MyListener extends PhoneStateListener {
  private String num;
  private MediaRecorder recorder;  //recording  private File file;
  public void onCallStateChanged(int state, String incomingNumber) {
    switch (state) {
      //Ring Status      case TelephonyManager.CALL_STATE_RINGING:
        //Save the phone number        num = incomingNumber;
        break;
      //Response status      case TelephonyManager.CALL_STATE_OFFHOOK:
        try {
          //Set the file saving location          file = new File((), num + "_" + () + ".3gp");
          //Create a recorder          recorder = new MediaRecorder();
          //Set the source of the audio (microphone)          ();
          //Save in 3gp format          (OutputFormat.THREE_GPP);
          //Set the encoder          (AudioEncoder.AMR_NB);
          //Output file path          (());
          //Prepare          ();
          //recording          ();
        } catch (Exception e) {
          ();
        }
        break;
      //Idle phone status      case TelephonyManager.CALL_STATE_IDLE:
        //Stop recording after the phone is hung up        if (recorder != null) {
          ();
          ();
        }
        break;
    }
  }
}

Permissions:

&lt;!-- Read the status permissions for the phone --&gt;
&lt;uses-permission android:name=".READ_PHONE_STATE" /&gt;
&lt;!-- Recording permissions --&gt;
&lt;uses-permission android:name=".RECORD_AUDIO" /&gt;
&lt;!-- sdCardRead permission --&gt;
&lt;uses-permission android:name=".MOUNT_UNMOUNT_FILESYSTEMS" /&gt;
&lt;!-- sdCardPermission to write --&gt;
&lt;uses-permission android:name=".WRITE_EXTERNAL_STORAGE" /&gt;
&lt;!-- Turn on network permissions --&gt;
&lt;uses-permission android:name="" /&gt;

Bind local services

Binding local services is actually binding the activity and the service. Activity is generally interacting with users, while services are generally working in the background. If the activity needs to access some methods in the service and interact, this requires binding.

Ÿ  Use bindService to bind the service, pass in a custom ServiceConnection to receive the IBinder
Ÿ   Define a business interface that defines the required methods of use
Ÿ   Customize an IBinder in the service to inherit Binder and implement business interface, and return it in the onBind method
Ÿ   The calling side converts IBinder to an interface type, and calls methods in the interface to call methods in the service.

Example of binding between Activity and Service:

Activity:

public class MainActivity extends Activity {
  private QueryService qs;
  private EditText editText;
  public void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    setContentView();
    editText = (EditText) findViewById();
    // Binding service, passing in ServiceConnection to receive IBinder    bindService(new Intent(this, ), new MyConn(), BIND_AUTO_CREATE);
  }
  /*
    * Custom ServiceConnection is used to receive IBinder
    */
  private final class MyConn implements ServiceConnection {
    public void onServiceConnected(ComponentName name, IBinder service) {
      qs = (QueryService) service;
    }
    public void onServiceDisconnected(ComponentName name) {
    }
  }
  /*
    * Get contacts based on ID
    */
  public void queryName(View view) {
    String id = ().toString();
    String name = ((id));
    (this, name, 0).show();
  }
}

Service:

public class PersonService extends Service {
  private String[] data = { "zxx", "lhm", "flx" };
  /*
    * When this method is called when bound, it returns an IBinder to call the method in the current service.
    */
  public IBinder onBind(Intent intent) {
    return new MyBinder();
  }
  /*
    * Query method
    */
  public String query(int id) {
    return data[id];
  }
  /*
    * Custom IBinder, implements QueryService business interface, and provides a method to callers to access the current service
    */
  private final class MyBinder extends Binder implements QueryService {
    public String query(int id) {
      return (id);
    }
  }
}

Bind remote services

Ÿ   When remotely binding a service, the method cannot be called through the same interface. At this time, AIDL technology is required.
Ÿ   Change the interface extension to ".aidl"
Ÿ   Remove permission modifier
Ÿ  The interface with the same name will be generated under the gen folder
Ÿ   Change the custom IBinder class in the service to the Stub in the inheritance interface
Ÿ   The IBinder returned in ServiceConnection is a proxy object, and cannot be used for forced conversion, use () instead

I hope this article will be helpful to everyone's Android programming design.