Service Startup Mode
Service Overview
A Service represents a Service and is one of the core components of the Android system.
The essence of Service is a java class that inherits android. app. Service;
Every Service should be registered in the AndroidMainfest. xml file;
The Service is maintained by the Android system.
The Service does not have a matched user interface, which is usually used in background processing for time-consuming operations.
Time-consuming operations cannot be performed in the main thread.
The Service is running in the main thread;
Although the Service is positioned as "processing time-consuming operations", various time-consuming operations need to be completed by opening up other threads in the Service.
A component can be bound to a Service to implement Inter-Process Communication ).
Process Priority:
The Android system tries to maintain as many threads as possible. However, due to limited device performance, the Android system dynamically manages the memory.
Some low-priority processes are often terminated to release resources and ensure normal operation of high-priority processes.
Process priority classification:
1. Foreground Process)
2. Visible Process)
3. Service Process)
4. BackGround Process)
5. Empty Process)
Start Service
Developers can use Intent to activate Service components.
The following methods are used to activate Service components:
Call the startService () method defined by Context (start)
Call the bindService () method defined by Context (BIND)
Start Service Development Process
The Service development process is as follows:
1. Create a java class and inherit from android. app. Service. (The Service defines the abstract method onBlind (). This method must be overwritten, but not necessarily implemented)
2. Add under AndroidMainfest. xml Subnode,
Configure the created Service;
3. Call the startService (Intent intent) method in the Activity to start the Service;
Enable Service explicitly or implicitly
Whether it is an explicit Intent or an implicit Intent, the Service component can be activated.
To implement inter-process communication, configure an implicit intent filter for the Service component.
Stop Service
You can call the stopService (Intent intent) method of Context to stop the Service and destroy the Service component.
You can call the stopSelf () method in the Service to stop itself.
Service Lifecycle
If the Activity repeatedly calls the startService () method, the onStartCommand () method is called repeatedly in the Service.
Case:
<Button android:id="@+id/btn_start" android:layout_width="match_parent" android:layout_height="wrap_parent" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:onClick="doStart" android:text="Start Service"/> <Button android:layout_marginTop="20dp" android:id="@+id/btn_stop" android:layout_width="match_parent" android:layout_height="wrap_parent" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:onClick="doStop" android:text="Start Service"/>
public void doStart(View view){ Intent intent = new Intent(this,SampleService.class); startService(intent);}public void doStop(View view){ Intent intent = new Intent(this,SampleService.class); stopService(intent);}
Service class:
public class SampleService exteds Service{ public void onCreate(){ Log.d(tag,"onCreate") super.onCreate(); } public int onStartCommand(Intent intent,int flags,int startId){ Log.d(tag,"onStartCommand"); return super.onStartCommand(intent,flags,startId); } public void onDestroy(){ Log.d(tag,"onDestroy"); super.onDestroy(); } }
AndroidMainfest. xml
Service stickiness
Service stickiness: indicates whether the Service can be automatically restarted after the process is accidentally aborted.
By default, the Service component activated using startService () is viscous, even if the process in which it is located is accidentally aborted,
The Service will be automatically created later.
Set Service stickiness
In the Service life cycle, the return value of the onStartCommand () method determines the Service stickiness.
The return value of this method can be set:
START_STICKY: sticky. It restarts automatically after it is accidentally aborted, but the Intent originally used to activate it is lost;
START_NOT_STICKY: Non-sticky. It will not be restarted automatically after it is accidentally aborted;
START_REDELIVER_INTENT: sticky and re-Send the Intent. This means that the Service is automatically restarted after an unexpected suspension.
The component will get the Intent object used to activate it;
START_STICKY_COMPATIBILITY: compatible version of START_STICKY. it is not guaranteed that onStartCommand () will be called again.
Case:
Service to play music
You can use the system's MediaPlayer class to play music. the development procedure is as follows:
Create a MediaPlayer object. You can directly use the non-parameter constructor;
Call MediaPlaye's reset () method to reset (unnecessary );
Call the setDataSource () method of MediaPlayer to set the songs to be played;
Call the MediaPlayer prepare () method to load (buffer) songs;
Call the start () method of MediaPlayer to play a song;
Call the release () method to release resources when exiting.
The business logic of this example:
Activate the Service through Activity and create a mediaPlayer instance in the Service to play the song;
The played songs are stored in sdcard/Misic/of the simulator;
When the Activity is stopped, stop playing the Service of the song;
When the Service is stopped, the resources of the MediaPlayer are released.
Case:
MainActivity:
package com.edu.hpu.service;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}public void startMusic(View view){Intent intent = new Intent(this,PlayerMusicService.class);startService(intent);}@Overrideprotected void onDestroy() {// TODO Auto-generated method stubIntent intent = new Intent(this,PlayerMusicService.class);stopService(intent);super.onDestroy();}}
Layout:
<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"> <Button android: id = "@ + id/button1" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: layout_alignParentTop = "true" android: layout_centerHorizontal = "true" android: layout_marginTop = "136dp" android: onClick = "startMusic" android: text = "Play Music"/> </RelativeLayout>
Service class:
package com.edu.hpu.service;import java.io.IOException;import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.os.Environment;import android.os.IBinder;public class PlayerMusicService extends Service{ private MediaPlayer player; @Overridepublic void onCreate() { try { player = new MediaPlayer(); player.reset(); player.setDataSource(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Music/Groove Coverage - She.mp3"); player.prepare(); player.start();} catch (IllegalArgumentException e) {// TODO: handle exceptione.printStackTrace();}catch(SecurityException e){e.printStackTrace();} catch(IllegalStateException e){ e.printStackTrace(); } catch(IOException e){ e.printStackTrace(); }}@Overridepublic void onDestroy() {// TODO Auto-generated method stubplayer.release();player = null;super.onDestroy();}@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;}}
Configuration:
MediaPlayer supports playing mainstream audio and video files and non-local media files. MediaPlayer enables subthreads to play songs. You can use pause () to pause playing, call the seekTo () method to fast forward to the specified position to start playing. Call the prepareAsync () method to load the song, configure the OnPreparedListener, and call the MediaPlayer start () method in the listener; generally, OnCompletionListener is configured for the MediaPlayer to implement processing after playback.