1. Service and process priorities
1.1 What is a service?
windows services: no interface, long-running applications in the background;
android services: a component of the application, no interface activity, long-term running in the background;
Process: It is the carrier of application running.
The relationship between processes and applications: The linux operating system creates a process that runs the dalvik virtual machine, and Android applications run on the dalvik virtual machine.
1.2 Process life cycle:
(1) The process is created as soon as the application is started;
(2) When the application exits, the process does not exit.
(3) Only when the process is stopped manually will the process end;
The operating system runs the process of the application as long as possible. In order to ensure that the memory space is not occupied in large quantities, it will kill the process from the lower level to the higher level according to the priority of the process, until the memory space is almost cleaned up.
1.3 Process Level:
(1) Foreground process
Application, user is operating, activity's onresume method is executed, you can click the event accordingly.
(2) Visible process
The ui interface of the application can be seen by the user, but it can't be operated.
(3) Service process
The application has no interface, but a back-end service is still running.
(4) Background process
The application has no service running, the application is minimized, and the activity executes the onstop method
(5) Empty process (empty process)
No components are running, all activities are closed, and the task stack is empty
2. Characteristics of Service
-
Characteristics of services:
When a service is created, onCreate, onStartCommand are invoked.
Services can only be created once and onStartCommand can be opened multiple times.
Services can only be stopped once;
There are no onPause, onStop, onResume, onRestart methods because service has no interface and runs in the background for a long time.
-
Life cycle approach:
onCreate: Call this method when the service is created;
onStartCommand: Open Services
onDestroy: Destruction Services
3. Template code of telephone eavesdropper (emphasis)
- Sample code:
(1) Add a Service service Service to the project and re-create the onCreate method:
public class DHQTService extends Service {
/**
* Call this method when the service is created
*/
@Override
public void onCreate() {
System.out.println("=========onCreate=========");
super.onCreate();
TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
tm.listen(new MyListener(), PhoneStateListener.LISTEN_CALL_STATE);
}
}
(2) Configure the service in the manifest file:
<service android:name="com.itheima.dhqtq.DHQTService"></service>
(3) Open services in activity:
service = new Intent(this, DHQTService.class);
// Open Services
startService(service);
(4) In the onCreate method, Telephone Manager is used to monitor the state of the telephone:
/**
* Call this method when the service is created
*/
@Override
public void onCreate() {
System.out.println("=========onCreate=========");
super.onCreate();
TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
tm.listen(new MyListener(), PhoneStateListener.LISTEN_CALL_STATE);
}
/**
*Customize a phone status monitor to listen on the phone
*/
private class mylistener extends phonestatelistener {
private MediaRecorder r;
@Override
public void onCallStateChanged(int state, String incomingNumber) {
try {
// super.onCallStateChanged(state, incomingNumber);
System.out.println("====state===============" + state);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE: // Idle state
System.out.println("Close the recorder and upload audio files..................");
if(r != null){
r.stop();
r.release();
r = null;
// Upload files
}
break;
case TelephonyManager.CALL_STATE_RINGING: // Idle state
System.out.println("Get the tape recorder ready. Get the tape recorder ready...................");
r = new MediaRecorder();
r.setAudioSource(MediaRecorder.AudioSource.MIC);
r.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
// r.setOutputFile("/mnt/sdcard/info.3gp");
r.setOutputFile(Environment.getExternalStorageDirectory()+"/info.3gp");
r.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
r.prepare();
break;
case TelephonyManager.CALL_STATE_OFFHOOK: // Idle state
System.out.println("Start recording..................");
r.start();
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
(5) Add permissions to the list configuration file:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
4. start opens the service life cycle (emphasis)
-
Characteristics of services:
(1) When a service is created, onCreate, onStartCommand are invoked;
(2) Services can only be created once, and onStartCommand can be opened multiple times;
(3) Service can only be stopped once;
(4) There are no onPause, onStop, onResume, onRestart methods, because service has no interface and runs in the background for a long time.
-
Life cycle approach:
onCreate: Call this method when the service is created;
onStartCommand: Open Services
onDestroy: Destruction Services
5. The bind approach opens the service life cycle (emphasis)
bindService binding service and unBindService unbound service;
The service is created when it is bound, calling oncreate and onbind methods. Services can only be bound once; The service can only be unbound once. When unbound, onUnbind and onDestroy methods are called. If unbound is unbound many times, an exception is thrown.
Recommended ways:
startService: Open and create a service that runs in the background for a long time. Binding Service: Binding service, which can call the method in the service; unBindService: Remove the service and stop the method in the service; stopService: Stop service, destroy service object;
Why introduce the API of bindservice?
To invoke business logic methods in services.
6. The process of invoking service methods by binding services
The business logic method in calling service is implemented by bindservice.
Steps:
(1) Create a middleman MyBinder in the service class, inheriting Binder, which implements the IBinder interface:
public class MyBinder extends Binder{
}
(2) Create a MyBinder member variable in the service class:
private MyBinder myBinder;
(3) Write a method in the MyBinder class to invoke the business logic method of the service:
public class MyBinder extends Binder{
// Use middlemen to invoke methods in services
public void callMethodInService(){
methodInService();
}
}
(4) When bindService is used in activity, Service Connection is defined. In this connection, two services are implemented:
private class MyConn implements ServiceConnection {
/**
* Call this method when the service connection is successful
*/
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// Middleman MyBinder object returned after successful service binding
myBinder = (MyBinder) service;
}
/**
* Call this method when service disconnection succeeds
*/
@Override
public void onServiceDisconnected(ComponentName name) {
System.out.println("-------onServiceDisconnected-------");
}
}
(5) Through the business logic method of intermediary services in activity:
myBinder.callMethodInService();
7. Binding Service Extraction Interface (emphasis)
interface: Open up the exposed functions, but do not expose the details of the implementation of the functions;
Let the middleman realize the purpose of service interface: only expose the business logic method in the interface, hide the other methods in the middleman;
Steps:
(1) Create a service interface class that contains business logic methods that need to be exposed:
public interface IService {
public void callMethodInService();
}
(2) Let the middleman in the service implement the interface class of the service:
private class MyBinder extends Binder implements IService{
// (Implementing methods in service interfaces) Calling methods in services using intermediaries
public void callMethodInService(){
methodInService();
}
}
(3) Declare the member variables of the interface in activity:
private IService myBinder;
(4) Mandatory conversion to the interface type of the service
private class MyConn implements ServiceConnection {
/**
* Call this method when the service connection is successful
*/
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// Forced conversion to the interface type of the service
myBinder = (IService) service;
}
(5) The business logic method of invoking service through member variables of interface in activity:
public void call(View view){
myBinder.callMethodInService();
}
8. Application scenarios for binding services
Application scenarios:
(1) We need to run some business logic in the background, and we need to interact with server-side data, which are written in the service.
(2) Weather forecast and stock quotation software;
9. Register Broadcast Receivers with Services
Frequently operated broadcast events are not valid if they are configurated only in the manifest configuration file. Code registration is required to take effect.
Steps:
// Registered Broadcast Receiver
// 1. The object of receiving the broadcast
ScreenBroadCastReceiver screenReceiver = new ScreenBroadCastReceiver();
// 2. Create an intentFilter object
IntentFilter filter = new IntentFilter();
// 3. Types of events registered for reception
filter.addAction("android.intent.action.SCREEN_ON");
filter.addAction("android.intent.action.SCREEN_OFF");
// 4. Registered Broadcast Receiver
this.registerReceiver(screenReceiver, filter);
10. Writing of remote service aidl (emphasis)
Local Services: Services written in the engineering of their own applications, running this service using the processes of their own applications;
Remote service: A service written in the project of another application, running the service using the process of another application (an application installed on the same mobile phone);
IPC: Inter Process Communication;
Ail: Android Interface Definition Language Android Interface Definition Language;
There are no public, protected, private modifiers in the interface class of aidl, and the default is public sharing.
Steps:
(1) Create a service interface class that contains business logic methods that need to be exposed:
(2) Let the middleman in the service implement the interface class of the service:
(3) Modify and copy the interface file:
(4) In the activity of local service engineering, binding services:
(5) The method of calling remote service through interface: