Android – Working with foreground services
This post is the second in the Background processing in Android tutorials series I am currently sharing. So after a tutorial on scheduled background tasks , we’ll follow up with foreground services. You’ll eventually see a demo for what we’ll build by the end of the tutorial, a quick introduction to foreground services and a sample in code !
What we’ll build
Foreground services
Through the previous tutorial we’ve seen that services are application components that perform certain operations without providing a user interface. But in some cases when long running operations are in progress, we would want the user to notice that progress. Music players and files downloads are two good examples of that.
An example
As the demo shows, on startServiceBtn click we’ll create and start a background service that streams a web radio by calling startService() as follows :
(findViewById(R.id.startServiceBtn)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final int lState = MyForegroundService.getState(); if (lState == Statics.STATE_SERVICE.NOT_INIT) { if (!NetworkHelper.isInternetAvailable(v.getContext())) { Toast.makeText(getApplicationContext(), "No internet access!", Toast.LENGTH_SHORT).show(); return; } Intent startIntent = new Intent(v.getContext(), MyForegroundService.class); startIntent.setAction(Statics.ACTION.START_ACTION); startService(startIntent); } else if (lState == Statics.STATE_SERVICE.PREPARE || lState == Statics.STATE_SERVICE.PLAY) { Intent lPauseIntent = new Intent(v.getContext(), MyForegroundService.class); lPauseIntent.setAction(Statics.ACTION.PAUSE_ACTION); PendingIntent lPendingPauseIntent = PendingIntent.getService(v.getContext(), 0, lPauseIntent, PendingIntent.FLAG_UPDATE_CURRENT); try { lPendingPauseIntent.send(); } catch (PendingIntent.CanceledException e) { e.printStackTrace(); } } else if (lState == Statics.STATE_SERVICE.PAUSE) { if (!NetworkHelper.isInternetAvailable(v.getContext())) { Toast.makeText(getApplicationContext(), "No internet access!", Toast.LENGTH_SHORT).show(); return; } Intent lPauseIntent = new Intent(v.getContext(), MyForegroundService.class); lPauseIntent.setAction(Statics.ACTION.PLAY_ACTION); PendingIntent lPendingPauseIntent = PendingIntent.getService(v.getContext(), 0, lPauseIntent, PendingIntent.FLAG_UPDATE_CURRENT); try { lPendingPauseIntent.send(); } catch (PendingIntent.CanceledException e) { e.printStackTrace(); } } } });
The MyForegroundService class is where we’ll define our service and build the media player. So the class comes as follows:
public class MyForegroundService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnBufferingUpdateListener { public MyForegroundService(){...} @Override public void onCreate(){...} @Override public onStartCommand(Intent intent, int flags, int startId){...} @Override public void onDestroy(){...} @Override public void onPrepared(MediaPlayer mp){...} @Override public void onBufferingUpdate(MediaPlayer mp, int percent){...}
The onStartCommand() method is where we’ll call the actual startForeground()
(or eventually stopForegroud() )to fireup that notification to the user and start the service :
@Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent == null) { stopForeground(true); stopSelf(); return START_NOT_STICKY; } switch (intent.getAction()) { case Statics.ACTION.START_ACTION: Log.i(TAG, "Received start Intent "); mStateService = Statics.STATE_SERVICE.PREPARE; startForeground(Statics.NOTIFICATION_ID_FOREGROUND_SERVICE, prepareNotification()); destroyPlayer(); initPlayer(); play(); break; case Statics.ACTION.PAUSE_ACTION: mStateService = Statics.STATE_SERVICE.PAUSE; mNotificationManager.notify(Statics.NOTIFICATION_ID_FOREGROUND_SERVICE, prepareNotification()); Log.i(TAG, "Clicked Pause"); destroyPlayer(); mHandler.postDelayed(mDelayedShutdown, Statics.DELAY_SHUTDOWN_FOREGROUND_SERVICE); break; case Statics.ACTION.PLAY_ACTION: mStateService = Statics.STATE_SERVICE.PREPARE; mNotificationManager.notify(Statics.NOTIFICATION_ID_FOREGROUND_SERVICE, prepareNotification()); Log.i(TAG, "Clicked Play"); destroyPlayer(); initPlayer(); play(); break; case Statics.ACTION.STOP_ACTION: Log.i(TAG, "Received Stop Intent"); destroyPlayer(); stopForeground(true); stopSelf(); break; default: stopForeground(true); stopSelf(); } return START_NOT_STICKY; }
One more point to point on creating and starting foreground services before I make you jump to the source code of this tutorial is that you need to define your service in app manifest by adding the following to the application tag :
<service android:name=".MyForegroundService" android:exported="false"/>
To get the full picture, check out the very basic source code here.
Recent Comments