Wednesday, March 31, 2010

Creating a MediaPlayer in a Service

Create a class which extends Service, in that in onCreate(), create the mediaPlayer and if we need, we can provide a notification also, to notify the user that a background service is being activated.

In onStart(), start(), the mediaplayer also, set looping equals true. So that the mediaplayer will play continously

The complete code is


public class AudioService extends Service {

Mediaplayer player;
public void onCreate() {
player = MediaPlayer.create(this, R.raw.mj);
NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
nOTIFICATION NOTIFICATION = new Notification(0, "Player started", System.currentTimeMillis());
nm.notify(0, notification);
try{
player.prepare();
} catch(Exception e){
}
}

public void onStart(Intent intent, int startId) {
player.start();
player.setLooping(true);
}

public IBinder onBind(Intent intent) {
return null;
}
}

No comments:

Post a Comment

Androidians