Android's Service application component basic authoring method

  • 2020-05-07 20:24:50
  • OfStack

What is Service
Service is an application component in an android system, which is about the same level as Activity, but it has no graphical interface, cannot run by itself, can only run in the background, and can interact with other components such as update ContentProvider, Intent and system notifications. It can be started in two ways: context.startService () and context.bindService (). Service is usually used to handle 1 time-consuming operation.

Service
Create a class (FirstService in this case) that inherits android.app.Service and overrides the following methods:
onBind(Intent intent) Return the communication channel to the service.
onCreate() Called by the system when the service is first created.
onStartCommand(Intent intent, int flags, int startId) Called by the system every time a client explicitly starts the service by calling startService(Intent), providing the arguments it supplied and a unique integer token representing the start request.
onDestroy() Called by the system to notify a Service that it is no longer used and is being removed.

Add service configuration
to AndroidManifest.xml file
 
<service android:name=".FirstService"></service> 

Start and stop writing Service's click events in Activity
 
class StartServiceListener implements OnClickListener { 
@Override 
public void onClick(View v) { 
Intent intent = new Intent(); 
intent.setClass(TestActivity.this, FirstService.class); 
startService(intent); 
} 
} 
class StopServiceListener implements OnClickListener { 
@Override 
public void onClick(View v) { 
Intent intent = new Intent(); 
intent.setClass(TestActivity.this, FirstService.class); 
stopService(intent); 
} 
} 

Related articles: