“This is the third day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021.”
Android Service practice example
Music player
Start the local service using startService and bindService respectively
Let’s start with startService
Activity
public class PlayMusic extends Activity implements OnClickListener { private static final String TAG = "PlayMusic"; private Button playBtn; private Button stopBtn; private Button pauseBtn; private Button exitBtn; private Button closeBtn; / /... @override public void onClick(View v) {int op = -1; Intent intent = new Intent("org.allin.android.musicService"); / / radio / / Intent Intent = new Intent (" org. Allin. Android. MusicReceiver "); switch (v.getId()) { case R.id.play: Log.d(TAG, "onClick: playing muic"); op = 1; break; case R.id.stop: Log.d(TAG, "onClick: stoping music"); op = 2; break; case R.id.pause: Log.d(TAG, "onClick: pausing music"); op = 3; break; case R.id.close: Log.d(TAG, "onClick: close"); this.finish(); break; case R.id.exit: Log.d(TAG, "onClick: exit"); op = 4; stopService(intent); this.finish(); break; } Bundle bundle = new Bundle(); bundle.putInt("op", op); intent.putExtras(bundle); startService(intent); // sendBroadcast(intent); }}Copy the code
We override the onClick method to control playing music:
- The various operations that play music are passed digitally to the Service via the Intent
- Constructs an Intent, ntent Intent = new Intent (org. Allin. Android. “musicService”)
- “Org. Allin. Android. MusicService” is in the AndroidManifest. The definition of XML file to the service class
<service android:enabled="true" android:name=".MusicService">
<intent-filter>
<action android:name="org.allin.android.musicService" />
</intent-filter>
</service>
Copy the code
Service
Put the operation code in the Bundle: Bundle Bundle = new Bundle(); bundle.putInt(“op”, op); intent.putExtras(bundle); Finally, use startService(Intent); Start the service.
MusicService.java
public class MusicService extends Service { private static final String TAG = "MyService"; private MediaPlayer mediaPlayer; /* * (non-Javadoc) * * @see android.app.Service#onBind(android.content.Intent) */ @Override public IBinder onBind(Intent arg0) { return null; } @Override public void onCreate() { Log.v(TAG, "onCreate"); if (mediaPlayer == null) { mediaPlayer = MediaPlayer.create(this, R.raw.tmp); mediaPlayer.setLooping(false); } } @Override public void onDestroy() { Log.v(TAG, "onDestroy"); if (mediaPlayer ! = null) { mediaPlayer.stop(); mediaPlayer.release(); } } @Override public void onStart(Intent intent, int startId) { Log.v(TAG, "onStart"); if (intent ! = null) { Bundle bundle = intent.getExtras(); if (bundle ! = null) { int op = bundle.getInt("op"); switch (op) { case 1: play(); break; case 2: stop(); break; case 3: pause(); break; } } } } public void play() { if (! mediaPlayer.isPlaying()) { mediaPlayer.start(); } } public void pause() { if (mediaPlayer ! = null && mediaPlayer.isPlaying()) { mediaPlayer.pause(); } } public void stop() { if (mediaPlayer ! = null) { mediaPlayer.stop(); Try {// Mediaplayer.prepare () should be called before the start function is used to play the game again. } catch (IOException ex) { ex.printStackTrace(); }}}}Copy the code
Use the system’s own MediaPlayer for music playback control.
When startService is called the service will first call onCreate where we initialize the MediaPlayer. Intent.getextras (); intent.getextras (); Iundle bundle = intent.getextras (); int op = bundle.getInt(“op”);
BroadcastReceiver
Sometimes a service can be started by broadcasting if it only provides a few operational interfaces.
Start by defining a Receiver and extending it from BroadcastReceiver, and then register it in androidmanifest.xml:
<receiver android:name=".MusicReceiver">
<intent-filter>
<action android:name="org.allin.android.musicReceiver" />
</intent-filter>
</receiver>
Copy the code
MusicReceiver.java
public class MusicReceiver extends BroadcastReceiver { private static final String TAG = "MusicReceiver"; @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "onReceive"); Intent it = new Intent("org.allin.android.musicService"); Bundle bundle = intent.getExtras(); it.putExtras(bundle); if(bundle ! = null){ int op = bundle.getInt("op"); if(op == 4){ context.stopService(it); }else{ context.startService(it); }}}}Copy the code
Then the onclick method of PlayMusic some transformation, the Intent to follow to the Receiver Intent Intent = new Intent (” org. Allin. Android. MusicReceiver “); If the opcodes bound to the intent remain unchanged, sendBroadcast(Intent) is called. Broadcast Intentg. When the MusicReceiver receives a broadcast, it acts according to the opcode.
Use bindService to start a Service
Activity
public class PlayBindMusic extends Activity implements OnClickListener { private static final String TAG = "PlayBindMusic"; private Button playBtn; private Button stopBtn; private Button pauseBtn; private Button exitBtn; private BindMusicService musicService; @Override public void onClick(View v) { switch (v.getId()) { case R.id.play: Log.d(TAG, "onClick: binding srvice"); musicService.play(); break; case R.id.stop: Log.d(TAG, "onClick: stoping srvice"); if(musicService ! = null){ musicService.stop(); } break; case R.id.pause: Log.d(TAG, "onClick: pausing srvice"); if(musicService ! = null){ musicService.pause(); } break; case R.id.exit: Log.d(TAG, "onClick: exit"); this.finish(); break; } } private void connection(){ Log.d(TAG, "connecting....." ); Intent intent = new Intent("org.allin.android.bindService"); bindService(intent, sc, Context.BIND_AUTO_CREATE); } private ServiceConnection sc = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { musicService = null; Log.d(TAG, "in onServiceDisconnected"); } @Override public void onServiceConnected(ComponentName name, IBinder service) { musicService = ((BindMusicService.MyBinder)(service)).getService(); if(musicService ! = null){ musicService.play(); } Log.d(TAG, "in onServiceConnected"); }}; }Copy the code
BindService (Intent, sc, context.bind_auto_create) is used; To start the service, we need to define ServiceConnectionnn and implement the method that calls the callback function in ServiceConnectionnn when the service binding is successful: Public void onServiceConnected(Interface name) Inside the callback function using musicService = ((BindMusicService. MyBinder) (service). The getService (); With BindMusicService instance objects, you can invoke various functions provided by the service to control music playback.
BindMusicService.java
public class BindMusicService extends Service { private static final String TAG = "MyService"; private MediaPlayer mediaPlayer; private final IBinder binder = new MyBinder(); public class MyBinder extends Binder { BindMusicService getService() { return BindMusicService.this; } } /* * (non-Javadoc) * * @see android.app.Service#onBind(android.content.Intent) */ @Override public IBinder onBind(Intent intent) { Log.d(TAG, "onBind"); play(); return binder; } @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate"); Toast.makeText(this, "show media player", Toast.LENGTH_SHORT).show(); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy"); Toast.makeText(this, "stop media player", Toast.LENGTH_SHORT); if(mediaPlayer ! = null){ mediaPlayer.stop(); mediaPlayer.release(); } } public void play() { if (mediaPlayer == null) { mediaPlayer = MediaPlayer.create(this, R.raw.tmp); mediaPlayer.setLooping(false); } if (! mediaPlayer.isPlaying()) { mediaPlayer.start(); } } public void pause() { if (mediaPlayer ! = null && mediaPlayer.isPlaying()) { mediaPlayer.pause(); } } public void stop() { if (mediaPlayer ! = null) { mediaPlayer.stop(); Try {// Mediaplayer.prepare () should be called before the start function is used to play the game again. } catch (IOException ex) { ex.printStackTrace(); }}}}Copy the code
You can see that a Service has an onBind method that returns an IBinder object that is called when the Service is bound to another program. The IBinder object is the same IBinder passed in to the onServiceConnected method you saw earlier. Applications and services rely on this IBinder object to communicate.
The next article will cover remote calls to services through AIDL.