Introduction and use of service in Android

1. Introduction

In Android, the service (service) runs in the background without an interface. Like other components, the service runs on the main thread, so it cannot be used for time-consuming requests or actions. You can start a thread in the service and do time-consuming operations in the thread. You can start a service to play music, or to record changes in geographic location, or to start a service to run and always listen for some action.

2. Types of Service

There are generally two types of services:

1. Local service, Local Service is used inside the application.

    In the Service, you can call Context.startService() to start, and call Context.stopService() to end. Internally you can call Service.stopSelf() or Service.stopSelfResult() to stop. No matter how many times startService() is called, stopService() only needs to be called once to stop. Call the startForeground() method to run the service in the foreground and display it in the notification bar.

2. Remote service, Remote Service is used between applications within the android system.

    Interfaces can be defined and exposed for operation by other applications. The client establishes a connection to the service object and invokes the service through that connection. Call Context.bindService() to establish and start the connection, and call Context.unbindService() to close the connection. Multiple clients can bind to the same service. If the service is not loaded at this time, bindService() will load it first. Provided to be reused by other applications, such as defining a weather forecast service, and calling it with other applications.

3. Simple use of Service

1. startservice method

        (1), the custom class inherits the system Service, overwrites the life cycle method, and registers the custom service through the service tag in the AndroidManifest.xml file

/**
 * Steps to create a Service:
 * 1. Custom class inheritance system Service
 * 2. Override the life cycle method
 * 3. Register the custom service through the service tag in the AndroidManifest.xml file
 *
 * Note: Service exists in a global way in Application
 *
 */
public class MyService extends Service{
	
	/**
	 * Called when the Service is created
	 * This method will only be called once in the life cycle of a Service
	 * Generally initialize data in this method
	 */
	@Override
	public void onCreate() {
		super.onCreate();
		android.util.Log.e("danny", "MyService--onCreate");
	}
	
	/**
	 * This method is called every time startService is called
	 * @param intent is the intent object used when startingService
	 * According to the return value of this method, determine whether the created Service is a sticky service
	 * START_NOT_STICKY non-sticky service
	 * START_STICKY STICKY WITHOUT MEMORY SERVICE
	 * START_REDELIVER_INTENT sticky tape memory service
	 * Generally, threads are started in this method for time-consuming operations
	 */
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		android.util.Log.e("danny", "MyService--onStartCommand");
		
		String threadName = Thread.currentThread().getName();
		android.util.Log.e("danny", "threadName is " + threadName);
		
		new Thread(){
			public void run() {
				for(int i = 0; i < 10; i++){
					try {
						Thread.sleep(1000);
						android.util.Log.e("danny", "execute to" + i);
					} catch (InterruptedException e) {
						e.printStackTrace ();
					}
				}
				
				Intent broad = new Intent();
				broad.setAction("MyBroadcas");
				sendBroadcast (broad);
			};
		}.start();
		return START_REDELIVER_INTENT;
	}

	/**
	 * This method has nothing to do with starting the service, only the binding service
	 */
	@Override
	public IBinder onBind(Intent intent) {
		android.util.Log.e("danny", "MyService--onBind");
		return null;
	}

	/**
	 * This method is called when the Service is destroyed
	 * The situation of Service destruction;
	 * 	1 Activity.stopService
	 * 	2 Service.stopSelf()
	 */
	@Override
	public void onDestroy() {
		android.util.Log.e("danny", "MyService--onDestroy");
		super.onDestroy ();
	}
}

(2), call the startService method to start the service; when it stops, call the stopService method to stop the service

case R.id.startService:
     /*
     * startService steps to start Service
     * 1. Create an Intent object that starts the service and specify the target Service
     * 2. The Context.startServie method starts the service and passes the Intent object
     *
     * Features:
     * Services started through startService will not be bound to Activity
     * When destroying Activity, Service will not be automatically destroyed
     */
     Intent intent = new Intent(this, MyService.class);
     startService(intent);
     break;
case R.id.stopService:
     Intent stopIntent = new Intent(this, MyService.class);
     stopService(stopIntent); //Call the Context.stopService method to stop the target Service
     break;

2. bindService method

       (1), the custom class inherits the system Service, overwrites the life cycle method, and registers the custom service through the service tag in the AndroidManifest.xml file

/**
 * Services bound by bindService
 * Life cycle: onCreate onBind onUnBind onDestroy
 *
 */
public class MusicService extends Service {
	
	/**
	 * Called when the service is created, this method will only be called once in a life cycle
	 */
	@Override
	public void onCreate() {
		super.onCreate();
	}

	/**
	 * This method is called when bindService is called for the first time
	 * note: If a service is already bound, it will not be bound again
	 * @param intent Intent object passed when calling bindService
	 * @return returns to the ServiceConnection interface parameters in bindService
	 */
	@Override
	public IBinder onBind(Intent intent) {
		return new  MyBinder();
	}
	
	/**
	 * This method is called when UNBindService is called to unbind a service
	 * @param intent
	 * @return
	 */
	@Override
	public boolean onUnbind(Intent intent) {
		return super.onUnbind(intent);
	}
	
	
	/**
	 * This method is called when the service is destroyed
	 */
	@Override
	public void onDestroy() {
		super.onDestroy ();
	}
	
	private MediaPlayer player;
	
	class MyBinder extends Binder {
		/**
		 * Realize the effect of music playback
		 */
		public void play(){
			if(player == null) {
				player = MediaPlayer.create(MusicService.this, R.raw.hitta);
				player.start();
			} else if(!player.isPlaying()) {
				player.start();
			}
		}
		
		/**
		 * Realize the effect of music pause
		 */
		public void pause() {
			if(player != null && player.isPlaying()) {
				player.pause();
			}
		}
		
		/**
		 * Realize the effect of music stop
		 */
		public void stop(){
			if(player != null) {
				player.stop();
				player = null;
			}
		}
	}

}

(2) The bindService method binds the service, and calls the unbindService method to unbind the service

public class MainActivity extends Activity {
	
	private MyBinder mBinder;
	
	//Declare and create the connection callback interface of the bound service
	//This interface contains the callback function when binding the service
	private ServiceConnection conn = new ServiceConnection() {
		
		/**
		 * This method is called when the service is disconnected due to an exception
		 * parameter is the name of the service component to be bound
		 */
		@Override
		public void onServiceDisconnected(ComponentName name) {
		}
		
		/**
		 * This method is called when the binding service is connected and a specific IBinder object is returned
		 * The first parameter binds the component name of the service
		 * The second parameter is the IBinder object returned by the onBind method of the binding service
		 */
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Toast.makeText(MainActivity.this, "Service binding succeeded", Toast.LENGTH_SHORT).show();
			//Save the IBinder object returned in the onBind method of the Service
			//Subsequent calls can be made to the methods in this Binder
			mBinder = (MyBinder) service;
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView(R.layout.activity_main);
		
		/*
		 * Bind the target Service through bindService
		 * The bound service will be bound to the Activity. When the Activity is destroyed, the service bound to the Activity will also be destroyed.
		 */
		// 1 Create an Intent intent and specify the target Service
		Intent intent = new Intent(this, MusicService.class);
		bindService(intent, conn, BIND_AUTO_CREATE);
	}

	public void btnClicked(View view) {
		//Add a judgment condition to judge that the binding was successful before the service
		if(mBinder == null) {
			Toast.makeText(this, "The service is not bound", Toast.LENGTH_SHORT).show();
			return;
		}
		switch (view.getId()) {
		case R.id.play:
			mBinder.play();
			break;
		case R.id.pause:
			mBinder.pause ();
			break;
		case R.id.stop:
			mBinder.stop ();
			break;
		default:
			break;
		}
	}
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325178372&siteId=291194637