Service of service example of Android four components

  • 2020-12-13 19:04:54
  • OfStack

This article illustrates the service usage of the Android4 component. To share for your reference, the details are as follows:

In many cases, applications that have little to do with user interaction, we simply let them run in the background, and we can still run other applications while they're running.

To handle this background process, Android introduced the concept of Service. Service in Android is a long-lived component that does not implement any user interface.

The basic concept

The & # 376; Service is a component that runs in the background and has no interface, starting with calls from other components.
The & # 376; Create Service and define class inheritance from Service, as defined in ES18en.xml < service >
The & # 376; Turn on Service and call the startService method in other components
The & # 376; Stop Service and call the stopService method

1. Call service from activity


/*
 *  Open the service 
 */
public void start(View view) {
  Intent intent = new Intent(this, MyService.class);
  startService(intent);
}
/*
 *  The end of the service 
 */
public void stop(View view) {
  Intent intent = new Intent(this, MyService.class);
  stopService(intent);
}

2. Define Service:


public class MyService extends Service {
  /*
   *  Binding time call 
   */
  public IBinder onBind(Intent intent) {
    return null;
  }
  /*
   *  Invoked when the service is started 
   */
  public void onCreate() {
    super.onCreate();
    System.out.println("onCreate");
  }
  /*
   *  Call at the end of the service 
   */
  public void onDestroy() {
    super.onDestroy();
    System.out.println("onDestroy");
  }
}

3. Define the service in the manifest file:

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

Telephone recording

Telephone recording is realized by using the service. It runs in the background and uses the listener to listen to the state of the call. When the call comes, the listener gets the telephone number of the incoming call, and starts recording when the user answers it.

java code:


@Override
public void onCreate() {
  // Get phone service 
  TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
  // The status monitor for the phone 
  manager.listen(new MyListener(), PhoneStateListener.LISTEN_CALL_STATE);
}
private final class MyListener extends PhoneStateListener {
  private String num;
  private MediaRecorder recorder;  // The recording 
  private File file;
  public void onCallStateChanged(int state, String incomingNumber) {
    switch (state) {
      // Ring the bell state 
      case TelephonyManager.CALL_STATE_RINGING:
        // Save phone number 
        num = incomingNumber;
        break;
      // On call status 
      case TelephonyManager.CALL_STATE_OFFHOOK:
        try {
          // Set the file save location 
          file = new File(Environment.getExternalStorageDirectory(), num + "_" + System.currentTimeMillis() + ".3gp");
          // Create a recorder 
          recorder = new MediaRecorder();
          // Set the source of the audio ( The microphone )
          recorder.setAudioSource(AudioSource.MIC);
          // take 3gp format 
          recorder.setOutputFormat(OutputFormat.THREE_GPP);
          // Set encoder 
          recorder.setAudioEncoder(AudioEncoder.AMR_NB);
          // Output file path 
          recorder.setOutputFile(file.getAbsolutePath());
          // To prepare 
          recorder.prepare();
          // The recording 
          recorder.start();
        } catch (Exception e) {
          e.printStackTrace();
        }
        break;
      // Phone idle state 
      case TelephonyManager.CALL_STATE_IDLE:
        // Stop recording when the phone hangs up 
        if (recorder != null) {
          recorder.stop();
          recorder.release();
        }
        break;
    }
  }
}

Jurisdiction:


<!--  Read the status permissions of the phone  -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!--  The recording permissions  -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- sdCard Read permissions  -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<!-- sdCard Write permissions  -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--  Open network permissions  -->
<uses-permission android:name="android.permission.INTERNET" />

Bind local services

Binding to a local service is essentially activity binding to a service, activity1 generally interacts with the user, and Service 1 usually does background work. If activity needs to access one of the methods in the service to interact, it needs to be bound.

The & # 376; Using the bindService binding service, pass in a custom ServiceConnection to receive IBinder
The & # 376; Define a business interface that defines the methods needed to be used
The & # 376; A custom IBinder in the service inherits from Binder and implements the business interface, returned in the onBind method
The & # 376; The caller converts IBinder to the interface type, and the method in the interface is called to the method in the service

Binding example of Activity and Service:

Activity:


public class MainActivity extends Activity {
  private QueryService qs;
  private EditText editText;
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    editText = (EditText) findViewById(R.id.id);
    //  Binding service ,  The incoming ServiceConnection Used to receive IBinder
    bindService(new Intent(this, PersonService.class), new MyConn(), BIND_AUTO_CREATE);
  }
  /*
   *  The custom of ServiceConnection 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) {
    }
  }
  /*
   *  According to the Id Get contacts 
   */
  public void queryName(View view) {
    String id = editText.getText().toString();
    String name = qs.query(Integer.parseInt(id));
    Toast.makeText(this, name, 0).show();
  }
}

Service:


public class PersonService extends Service {
  private String[] data = { "zxx", "lhm", "flx" };
  /*
   *  This method is called when bound ,  return 1 a IBinder,  Used to invoke methods in the current service 
   */
  public IBinder onBind(Intent intent) {
    return new MyBinder();
  }
  /*
   *  Query methods 
   */
  public String query(int id) {
    return data[id];
  }
  /*
   *  The custom IBinder,  implementation QueryService Business interface ,  Provides a method for the caller to access the current service 
   */
  private final class MyBinder extends Binder implements QueryService {
    public String query(int id) {
      return PersonService.this.query(id);
    }
  }
}

Bind remote services

The & # 376; The AIDL technique is used when a remote binding service cannot invoke a method through the same interface
The & # 376; Change the interface extension to ".aidl"
The & # 376; Remove the permission modifier
The & # 376; The interface with the same name will be generated under the gen folder
The & # 376; Change the custom IBinder class in the service to Stub in the inherited interface
The & # 376; IBinder returned in ServiceConnection is a proxy object. Strong conversions cannot be used. Use Stub.asInterface () instead.

I hope this article has been helpful in Android programming.


Related articles: