Tutorials Face - Music Player With Notification and Lock Screen Controls
Tutorials Face - Music Player With Notification and Lock Screen Controls
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
3
Linktkhc Blogtiptheo
ToBlog
TutorialsFace
TechnicalhubforAndroidDevelopers
SUNDAY,20JULY2014
BLOGARCHIVE
2014(19)
MusicPlayerwithNotificationandLockScreenControls
October(1)
Thch
16
September(3)
August(3)
July(5)
PopupMenuinAndroidAPI8+
MakeHTTPS/HTTPRequestin
Android
MusicPlayerwithNotificationand
LockScreenCon...
BuildalltypesofNotificationsin
Android
MakeyourownCrashReporter
June(5)
May(2)
LABELS
Apps(3)Connection(1)
Customize
ActionBar(1)
Internet (2)
Inthistutorialwewilllearnhowtomakeasimplemusicplayerwithplay,pause,next,previouscontrolswithcontrollingmusic
fromnotificationandLockscreen.AudiofilespresentinSDcardwillbeplayed.
Notification(1)PopupMenu(1) Progressbar
SlidingMenu (1)
SQLite Database
StatusBar(1)
HOWTOCROPIMAGE
VIEWASCIRCLE/ROUND
INANDROID
Inthistutorialwewillmake
roundimageforbetteruser
experience.
InnovativeSliding
Menu(ResideMenu)in
android
Ifoundaveryinteresting
repositoryinGitHubby
SpecialCyCiwhichshowsainnovative
residemenu.
HOWTOADD
IMAGES/SMILEY/EMOJISIN
EDITTEXTINANDROID
Inthistutorialyouwilllearn
howtoaddsmiley/emojisin
editTextalongwithtextwhichwillbe
helpfulinchatapplicationandyouc...
DownloadSourceCodeDownload
MusicPlayerwithNotification
andLockScreenControls
Inthistutorialwewilllearn
howtomakeasimplemusic
playerwithplay,pause,
next,previouscontrolswithcontrolling
musicfromn...
CustomActionBarinAndroid
YoucanutilizetheActionBartodisplay
moreinformationbycustomizingit.
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
1/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
GradientCircularProgress
Bar(TriColor)
MorethebeautifulyourUIis,
moredownloadsyouget.In
thistutorialIwillshowyou
howyoucanmakeabeautifulTriColor
progress...
CircularProgressbarin
Android
CustomizetheProgressbar
forbetteruserexperience.
AndroidSystemBarTint
KITKAT
Android4.4(KitKat)
introducedtranslucent
systemUIstylingforstatus
andnavigationbars.
SQLITEDATABASE
INSERTTHOUSANDSOF
DATAINSECONDS(Tutorial
1)
Insertingasingledatain
databaseiseasy,butwhenwehave
1000'sofdatatobeinsertedittakeslotof
time,becauseweareca...
LIBRARIESFORANDROID
Herearesomeandroidopen
sourcelibrariesthatare
available.
TutorialsFaceTechni
534ltthch
ThchTrang
Hylngiutintrongsbnbcabn
thchnidungny
ProjectHierarchy
1)GetthelistofSongspresentinSDCard.
publicstaticArrayList<MediaItem>listOfSongs(Contextcontext){
Uriuri=MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
Cursorc=context.getContentResolver().query(uri,null,MediaStore.Audio.Media.IS_MUSIC+"
!=0",null,null)
ArrayList<MediaItem>listOfSongs=newArrayList<MediaItem>()
c.moveToFirst()
while(c.moveToNext()){
MediaItemsongData=newMediaItem()
Stringtitle=c.getString(c.getColumnIndex(MediaStore.Audio.Media.TITLE))
Stringartist=c.getString(c.getColumnIndex(MediaStore.Audio.Media.ARTIST))
Stringalbum=c.getString(c.getColumnIndex(MediaStore.Audio.Media.ALBUM))
longduration=c.getLong(c.getColumnIndex(MediaStore.Audio.Media.DURATION))
Stringdata=c.getString(c.getColumnIndex(MediaStore.Audio.Media.DATA))
longalbumId=c.getLong(c.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID))
Stringcomposer=c.getString(c.getColumnIndex(MediaStore.Audio.Media.COMPOSER))
songData.setTitle(title)
songData.setAlbum(album)
songData.setArtist(artist)
songData.setDuration(duration)
songData.setPath(data)
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
2/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
songData.setAlbumId(albumId)
songData.setComposer(composer)
listOfSongs.add(songData)
}
c.close()
Log.d("SIZE","SIZE:"+listOfSongs.size())
returnlistOfSongs
}
2)GetAlbumImage
publicstaticBitmapgetAlbumart(Contextcontext,Longalbum_id){
Bitmapbm=null
BitmapFactory.Optionsoptions=newBitmapFactory.Options()
try{
finalUrisArtworkUri=Uri.parse("content://media/external/audio/albumart")
Uriuri=ContentUris.withAppendedId(sArtworkUri,album_id)
ParcelFileDescriptorpfd=context.getContentResolver().openFileDescriptor(uri,"r")
if(pfd!=null){
FileDescriptorfd=pfd.getFileDescriptor()
bm=BitmapFactory.decodeFileDescriptor(fd,null,options)
pfd=null
fd=null
}
}catch(Erroree){}
catch(Exceptione){}
returnbm
}
AddpermissioninManifest
<usespermissionandroid:name="android.permission.READ_EXTERNAL_STORAGE"/>
3)MediaPlayerControls
mp.reset()
mp.setDataSource(songPath)
mp.prepare()
mp.start()
mp.getCurrentPosition()
mp.getDuration()
mp.pause()
mp.stop()
4)Forplayingsongafterkillingtheapplicationwehavetostartanotificationinforegroundfromserviceotherwisethe
systemstopssong.Andwewillrequirethecustomnotificationsothatwecancontrolourmusicplayerfromnotification.See
herehowtomakecustomnotificationbuildandhowwereceivewhenitbroadcast.Custombignotificationinsupportedfrom
API16+(JELLYBEAN).
<usespermissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>intNOTIFICATION_ID=
1111
publicstaticfinalStringNOTIFY_PREVIOUS="com.tutorialsface.audioplayer.previous"
publicstaticfinalStringNOTIFY_DELETE="com.tutorialsface.audioplayer.delete"
publicstaticfinalStringNOTIFY_PAUSE="com.tutorialsface.audioplayer.pause"
publicstaticfinalStringNOTIFY_PLAY="com.tutorialsface.audioplayer.play"
publicstaticfinalStringNOTIFY_NEXT="com.tutorialsface.audioplayer.next"
booleancurrentVersionSupportBigNotification=currentVersionSupportBigNotification()
publicstaticbooleancurrentVersionSupportBigNotification(){
intsdkVersion=android.os.Build.VERSION.SDK_INT
if(sdkVersion>=android.os.Build.VERSION_CODES.JELLY_BEAN){
returntrue
}
returnfalse
}
@SuppressLint("NewApi")
privatevoidnotification(){
StringsongName=PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getTitle()
StringalbumName=PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getAlbum()
RemoteViewssimpleContentView=new
RemoteViews(getApplicationContext().getPackageName(),R.layout.custom_notification)
RemoteViewsexpandedView=newRemoteViews(getApplicationContext().getPackageName(),
R.layout.big_notification)
Notificationnotification=newNotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.ic_music)
.setContentTitle(songName).build()
setListeners(simpleContentView)
setListeners(expandedView)
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
3/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
notification.contentView=simpleContentView
if(currentVersionSupportBigNotification){
notification.bigContentView=expandedView
}
try{
longalbumId=
PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getAlbumId()
BitmapalbumArt=UtilFunctions.getAlbumart(getApplicationContext(),albumId)
if(albumArt!=null){
notification.contentView.setImageViewBitmap(R.id.imageViewAlbumArt,albumArt)
if(currentVersionSupportBigNotification){
notification.bigContentView.setImageViewBitmap(R.id.imageViewAlbumArt,
albumArt)
}
}else{
notification.contentView.setImageViewResource(R.id.imageViewAlbumArt,
R.drawable.default_album_art)
if(currentVersionSupportBigNotification){
notification.bigContentView.setImageViewResource(R.id.imageViewAlbumArt,
R.drawable.default_album_art)
}
}
}catch(Exceptione){
e.printStackTrace()
}
if(PlayerConstants.SONG_PAUSED){
notification.contentView.setViewVisibility(R.id.btnPause,View.GONE)
notification.contentView.setViewVisibility(R.id.btnPlay,View.VISIBLE)
if(currentVersionSupportBigNotification){
notification.bigContentView.setViewVisibility(R.id.btnPause,View.GONE)
notification.bigContentView.setViewVisibility(R.id.btnPlay,View.VISIBLE)
}
}else{
notification.contentView.setViewVisibility(R.id.btnPause,View.VISIBLE)
notification.contentView.setViewVisibility(R.id.btnPlay,View.GONE)
if(currentVersionSupportBigNotification){
notification.bigContentView.setViewVisibility(R.id.btnPause,View.VISIBLE)
notification.bigContentView.setViewVisibility(R.id.btnPlay,View.GONE)
}
}
notification.contentView.setTextViewText(R.id.textSongName,songName)
notification.contentView.setTextViewText(R.id.textAlbumName,albumName)
if(currentVersionSupportBigNotification){
notification.bigContentView.setTextViewText(R.id.textSongName,songName)
notification.bigContentView.setTextViewText(R.id.textAlbumName,albumName)
}
notification.flags|=Notification.FLAG_ONGOING_EVENT
startForeground(NOTIFICATION_ID,notification)
}
publicvoidsetListeners(RemoteViewsview){
Intentprevious=newIntent(NOTIFY_PREVIOUS)
Intentdelete=newIntent(NOTIFY_DELETE)
Intentpause=newIntent(NOTIFY_PAUSE)
Intentnext=newIntent(NOTIFY_NEXT)
Intentplay=newIntent(NOTIFY_PLAY)
PendingIntentpPrevious=PendingIntent.getBroadcast(getApplicationContext(),0,previous,
PendingIntent.FLAG_UPDATE_CURRENT)
view.setOnClickPendingIntent(R.id.btnPrevious,pPrevious)
PendingIntentpDelete=PendingIntent.getBroadcast(getApplicationContext(),0,delete,
PendingIntent.FLAG_UPDATE_CURRENT)
view.setOnClickPendingIntent(R.id.btnDelete,pDelete)
PendingIntentpPause=PendingIntent.getBroadcast(getApplicationContext(),0,pause,
PendingIntent.FLAG_UPDATE_CURRENT)
view.setOnClickPendingIntent(R.id.btnPause,pPause)
PendingIntentpNext=PendingIntent.getBroadcast(getApplicationContext(),0,next,
PendingIntent.FLAG_UPDATE_CURRENT)
view.setOnClickPendingIntent(R.id.btnNext,pNext)
PendingIntentpPlay=PendingIntent.getBroadcast(getApplicationContext(),0,play,
PendingIntent.FLAG_UPDATE_CURRENT)
view.setOnClickPendingIntent(R.id.btnPlay,pPlay)
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
4/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
5)LockscreencontrolsareavailablefromAPI14+(ICS)andwewillrequire
i)AudioManager
ii)ComponentName
iii)RemoteControlClient
iv)SetIntentFilteractionofyourbroadcastReceiverinManifest
<actionandroid:name="android.intent.action.MEDIA_BUTTON"/>
i)implementsAudioManager.OnAudioFocusChangeListener
FirstlyregisterRemoteControlClient
privateComponentNameremoteComponentName
privateRemoteControlClientremoteControlClient
AudioManageraudioManager
BitmapmDummyAlbumArt
@SuppressLint("NewApi")
privatevoidRegisterRemoteClient(){
remoteComponentName=newComponentName(getApplicationContext(),new
NotificationBroadcast().ComponentName())
try{
if(remoteControlClient==null){
audioManager.registerMediaButtonEventReceiver(remoteComponentName)
IntentmediaButtonIntent=newIntent(Intent.ACTION_MEDIA_BUTTON)
mediaButtonIntent.setComponent(remoteComponentName)
PendingIntentmediaPendingIntent=PendingIntent.getBroadcast(this,0,
mediaButtonIntent,0)
remoteControlClient=newRemoteControlClient(mediaPendingIntent)
audioManager.registerRemoteControlClient(remoteControlClient)
}
remoteControlClient.setTransportControlFlags(
RemoteControlClient.FLAG_KEY_MEDIA_PLAY|
RemoteControlClient.FLAG_KEY_MEDIA_PAUSE|
RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE|
RemoteControlClient.FLAG_KEY_MEDIA_STOP|
RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS|
RemoteControlClient.FLAG_KEY_MEDIA_NEXT)
}catch(Exceptionex){
}
}
6)ForupdatingLockScreenUIwewillcall
@SuppressLint("NewApi")
privatevoidUpdateMetadata(MediaItemdata){
if(remoteControlClient==null)
return
MetadataEditormetadataEditor=remoteControlClient.editMetadata(true)
metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_ALBUM,data.getAlbum())
metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST,data.getArtist())
metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_TITLE,data.getTitle())
mDummyAlbumArt=UtilFunctions.getAlbumart(getApplicationContext(),data.getAlbumId())
if(mDummyAlbumArt==null){
mDummyAlbumArt=BitmapFactory.decodeResource(getResources(),
R.drawable.default_album_art)
}
metadataEditor.putBitmap(RemoteControlClient.MetadataEditor.BITMAP_KEY_ARTWORK,
mDummyAlbumArt)
metadataEditor.apply()
audioManager.requestAudioFocus(this,AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN)
}
7)IfsongisplayingsetPlayBackstateasPLAYSTATE_PLAYINGandwhensongispausedsetittoPLAYSTATE_PAUSED
remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING)
remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PAUSED)
NowallcomponentsareclearwewilluseHandlerforinteractionbetweenServiceandActivity.
ForupdatingSongprogressbarwewillusetimeras
privatestaticTimertimer
timer=newTimer()
timer.scheduleAtFixedRate(newMainTask(),0,100)
privateclassMainTaskextendsTimerTask{
publicvoidrun(){
handler.sendEmptyMessage(0)
}
}
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
5/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
privatefinalHandlerhandler=newHandler(){
@Override
publicvoidhandleMessage(Messagemsg){
if(mp!=null){
intprogress=(mp.getCurrentPosition()*100)/mp.getDuration()
Integeri[]=newInteger[3]
i[0]=mp.getCurrentPosition()
i[1]=mp.getDuration()
i[2]=progress
try{
PlayerConstants.PROGRESSBAR_HANDLER.sendMessage(PlayerConstants.PROGRESSBAR_HANDLER.obtainMessage(0,
i))
}catch(Exceptione){}
}
}
}
A)com.tutorialsface.audioplayer.utilpackagefiles
MediaItem.java
packagecom.tutorialsface.audioplayer.util
publicclassMediaItem{
Stringtitle
Stringartist
Stringalbum
Stringpath
longduration
longalbumId
Stringcomposer
@Override
publicStringtoString(){
returntitle
}
publicStringgetTitle(){
returntitle
}
publicvoidsetTitle(Stringtitle){
this.title=title
}
publicStringgetArtist(){
returnartist
}
publicvoidsetArtist(Stringartist){
this.artist=artist
}
publicStringgetAlbum(){
returnalbum
}
publicvoidsetAlbum(Stringalbum){
this.album=album
}
publicStringgetPath(){
returnpath
}
publicvoidsetPath(Stringpath){
this.path=path
}
publiclonggetDuration(){
returnduration
}
publicvoidsetDuration(longduration){
this.duration=duration
}
publiclonggetAlbumId(){
returnalbumId
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
6/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
}
publicvoidsetAlbumId(longalbumId){
this.albumId=albumId
}
publicStringgetComposer(){
returncomposer
}
publicvoidsetComposer(Stringcomposer){
this.composer=composer
}
}
PlayerConstants.java
packagecom.tutorialsface.audioplayer.util
importjava.util.ArrayList
importandroid.os.Handler
publicclassPlayerConstants{
//ListofSongs
publicstaticArrayList<MediaItem>SONGS_LIST=newArrayList<MediaItem>()
//songnumberwhichisplayingrightnowfromSONGS_LIST
publicstaticintSONG_NUMBER=0
//songisplayingorpaused
publicstaticbooleanSONG_PAUSED=true
//songchanged(next,previous)
publicstaticbooleanSONG_CHANGED=false
//handlerforsongchanged(next,previous)definedinservice(SongService)
publicstaticHandlerSONG_CHANGE_HANDLER
//handlerforsongplay/pausedefinedinservice(SongService)
publicstaticHandlerPLAY_PAUSE_HANDLER
//handlerforshowingsongprogressdefinedinActivities(MainActivity,AudioPlayerActivity)
publicstaticHandlerPROGRESSBAR_HANDLER
}
UtilFunctions.java
packagecom.tutorialsface.audioplayer.util
importjava.io.FileDescriptor
importjava.util.ArrayList
importcom.tutorialsface.audioplayer.R
importandroid.app.ActivityManager
importandroid.app.ActivityManager.RunningServiceInfo
importandroid.content.ContentUris
importandroid.content.Context
importandroid.database.Cursor
importandroid.graphics.Bitmap
importandroid.graphics.BitmapFactory
importandroid.net.Uri
importandroid.os.ParcelFileDescriptor
importandroid.provider.MediaStore
importandroid.util.Log
publicclassUtilFunctions{
staticStringLOG_CLASS="UtilFunctions"
/**
*Checkifserviceisrunningornot
*@paramserviceName
*@paramcontext
*@return
*/
publicstaticbooleanisServiceRunning(StringserviceName,Contextcontext){
ActivityManagermanager=(ActivityManager)
context.getSystemService(Context.ACTIVITY_SERVICE)
for(RunningServiceInfoservice:manager.getRunningServices(Integer.MAX_VALUE)){
if(serviceName.equals(service.service.getClassName())){
returntrue
}
}
returnfalse
}
/**
*Readthesongspresentinexternalstorage
*@paramcontext
*@return
*/
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
7/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
publicstaticArrayList<MediaItem>listOfSongs(Contextcontext){
Uriuri=MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
Cursorc=context.getContentResolver().query(uri,null,
MediaStore.Audio.Media.IS_MUSIC+"!=0",null,null)
ArrayList<MediaItem>listOfSongs=newArrayList<MediaItem>()
c.moveToFirst()
while(c.moveToNext()){
MediaItemsongData=newMediaItem()
Stringtitle=c.getString(c.getColumnIndex(MediaStore.Audio.Media.TITLE))
Stringartist=c.getString(c.getColumnIndex(MediaStore.Audio.Media.ARTIST))
Stringalbum=c.getString(c.getColumnIndex(MediaStore.Audio.Media.ALBUM))
longduration=c.getLong(c.getColumnIndex(MediaStore.Audio.Media.DURATION))
Stringdata=c.getString(c.getColumnIndex(MediaStore.Audio.Media.DATA))
longalbumId=c.getLong(c.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID))
Stringcomposer=c.getString(c.getColumnIndex(MediaStore.Audio.Media.COMPOSER))
songData.setTitle(title)
songData.setAlbum(album)
songData.setArtist(artist)
songData.setDuration(duration)
songData.setPath(data)
songData.setAlbumId(albumId)
songData.setComposer(composer)
listOfSongs.add(songData)
}
c.close()
Log.d("SIZE","SIZE:"+listOfSongs.size())
returnlistOfSongs
}
/**
*GetthealbumimagefromalbumId
*@paramcontext
*@paramalbum_id
*@paramresize
*@return
*/
publicstaticBitmapgetAlbumart(Contextcontext,Longalbum_id){
Bitmapbm=null
BitmapFactory.Optionsoptions=newBitmapFactory.Options()
try{
finalUrisArtworkUri=Uri.parse("content://media/external/audio/albumart")
Uriuri=ContentUris.withAppendedId(sArtworkUri,album_id)
ParcelFileDescriptorpfd=context.getContentResolver().openFileDescriptor(uri,"r")
if(pfd!=null){
FileDescriptorfd=pfd.getFileDescriptor()
bm=BitmapFactory.decodeFileDescriptor(fd,null,options)
pfd=null
fd=null
}
}catch(Erroree){}
catch(Exceptione){}
returnbm
}
/**
*@paramcontext
*@return
*/
publicstaticBitmapgetDefaultAlbumArt(Contextcontext){
Bitmapbm=null
BitmapFactory.Optionsoptions=newBitmapFactory.Options()
try{
bm=BitmapFactory.decodeResource(context.getResources(),R.drawable.default_album_art,
options)
}catch(Erroree){}
catch(Exceptione){}
returnbm
}
/**
*Convertmillisecondsintotimehh:mm:ss
*@parammilliseconds
*@returntimeinString
*/
publicstaticStringgetDuration(longmilliseconds){
longsec=(milliseconds/1000)%60
longmin=(milliseconds/(60*1000))%60
longhour=milliseconds/(60*60*1000)
Strings=(sec<10)?"0"+sec:""+sec
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
8/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
Stringm=(min<10)?"0"+min:""+min
Stringh=""+hour
Stringtime=""
if(hour>0){
time=h+":"+m+":"+s
}else{
time=m+":"+s
}
returntime
}
publicstaticbooleancurrentVersionSupportBigNotification(){
intsdkVersion=android.os.Build.VERSION.SDK_INT
if(sdkVersion>=android.os.Build.VERSION_CODES.JELLY_BEAN){
returntrue
}
returnfalse
}
publicstaticbooleancurrentVersionSupportLockScreenControls(){
intsdkVersion=android.os.Build.VERSION.SDK_INT
if(sdkVersion>=android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH){
returntrue
}
returnfalse
}
}
B)com.tutorialsface.audioplayerpackagefiles
MainActivity.java
packagecom.tutorialsface.audioplayer
importandroid.app.Activity
importandroid.content.Context
importandroid.content.Intent
importandroid.graphics.Bitmap
importandroid.graphics.PorterDuff.Mode
importandroid.graphics.drawable.BitmapDrawable
importandroid.os.Bundle
importandroid.os.Handler
importandroid.os.Message
importandroid.util.Log
importandroid.view.View
importandroid.view.View.OnClickListener
importandroid.widget.AdapterView
importandroid.widget.Button
importandroid.widget.ImageView
importandroid.widget.LinearLayout
importandroid.widget.ListView
importandroid.widget.ProgressBar
importandroid.widget.TextView
importcom.tutorialsface.audioplayer.adapter.CustomAdapter
importcom.tutorialsface.audioplayer.controls.Controls
importcom.tutorialsface.audioplayer.service.SongService
importcom.tutorialsface.audioplayer.util.MediaItem
importcom.tutorialsface.audioplayer.util.PlayerConstants
importcom.tutorialsface.audioplayer.util.UtilFunctions
publicclassMainActivityextendsActivity{
StringLOG_CLASS="MainActivity"
CustomAdaptercustomAdapter=null
staticTextViewplayingSong
ButtonbtnPlayer
staticButtonbtnPause,btnPlay,btnNext,btnPrevious
ButtonbtnStop
LinearLayoutmediaLayout
staticLinearLayoutlinearLayoutPlayingSong
ListViewmediaListView
ProgressBarprogressBar
TextViewtextBufferDuration,textDuration
staticImageViewimageViewAlbumArt
staticContextcontext
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState)
getActionBar().hide()
setContentView(R.layout.activity_main)
context=MainActivity.this
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
9/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
init()
}
privatevoidinit(){
getViews()
setListeners()
playingSong.setSelected(true)
progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.white),
Mode.SRC_IN)
if(PlayerConstants.SONGS_LIST.size()<=0){
PlayerConstants.SONGS_LIST=UtilFunctions.listOfSongs(getApplicationContext())
}
setListItems()
}
privatevoidsetListItems(){
customAdapter=newCustomAdapter(this,R.layout.custom_list,PlayerConstants.SONGS_LIST)
mediaListView.setAdapter(customAdapter)
mediaListView.setFastScrollEnabled(true)
}
privatevoidgetViews(){
playingSong=(TextView)findViewById(R.id.textNowPlaying)
btnPlayer=(Button)findViewById(R.id.btnMusicPlayer)
mediaListView=(ListView)findViewById(R.id.listViewMusic)
mediaLayout=(LinearLayout)findViewById(R.id.linearLayoutMusicList)
btnPause=(Button)findViewById(R.id.btnPause)
btnPlay=(Button)findViewById(R.id.btnPlay)
linearLayoutPlayingSong=(LinearLayout)findViewById(R.id.linearLayoutPlayingSong)
progressBar=(ProgressBar)findViewById(R.id.progressBar)
btnStop=(Button)findViewById(R.id.btnStop)
textBufferDuration=(TextView)findViewById(R.id.textBufferDuration)
textDuration=(TextView)findViewById(R.id.textDuration)
imageViewAlbumArt=(ImageView)findViewById(R.id.imageViewAlbumArt)
btnNext=(Button)findViewById(R.id.btnNext)
btnPrevious=(Button)findViewById(R.id.btnPrevious)
}
privatevoidsetListeners(){
mediaListView.setOnItemClickListener(newAdapterView.OnItemClickListener(){
@Override
publicvoidonItemClick(AdapterView<?>parent,Viewitem,intposition,longid){
Log.d("TAG","TAGTappedINOUT(IN)")
PlayerConstants.SONG_PAUSED=false
PlayerConstants.SONG_NUMBER=position
booleanisServiceRunning=
UtilFunctions.isServiceRunning(SongService.class.getName(),getApplicationContext())
if(!isServiceRunning){
Intenti=newIntent(getApplicationContext(),SongService.class)
startService(i)
}else{
PlayerConstants.SONG_CHANGE_HANDLER.sendMessage(PlayerConstants.SONG_CHANGE_HANDLER.obtainMessage())
}
updateUI()
changeButton()
Log.d("TAG","TAGTappedINOUT(OUT)")
}
})
btnPlayer.setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
Intenti=newIntent(MainActivity.this,AudioPlayerActivity.class)
startActivity(i)
}
})
btnPlay.setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
Controls.playControl(getApplicationContext())
}
})
btnPause.setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
Controls.pauseControl(getApplicationContext())
}
})
btnNext.setOnClickListener(newOnClickListener(){
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
10/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
@Override
publicvoidonClick(Viewv){
Controls.nextControl(getApplicationContext())
}
})
btnPrevious.setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
Controls.previousControl(getApplicationContext())
}
})
btnStop.setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
Intenti=newIntent(getApplicationContext(),SongService.class)
stopService(i)
linearLayoutPlayingSong.setVisibility(View.GONE)
}
})
imageViewAlbumArt.setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
Intenti=newIntent(MainActivity.this,AudioPlayerActivity.class)
startActivity(i)
}
})
}
@Override
protectedvoidonResume(){
super.onResume()
try{
booleanisServiceRunning=UtilFunctions.isServiceRunning(SongService.class.getName(),
getApplicationContext())
if(isServiceRunning){
updateUI()
}else{
linearLayoutPlayingSong.setVisibility(View.GONE)
}
changeButton()
PlayerConstants.PROGRESSBAR_HANDLER=newHandler(){
@Override
publicvoidhandleMessage(Messagemsg){
Integeri[]=(Integer[])msg.obj
textBufferDuration.setText(UtilFunctions.getDuration(i[0]))
textDuration.setText(UtilFunctions.getDuration(i[1]))
progressBar.setProgress(i[2])
}
}
}catch(Exceptione){}
}
publicstaticvoidupdateUI(){
try{
MediaItemdata=PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER)
playingSong.setText(data.getTitle()+""+data.getArtist()+""+data.getAlbum())
BitmapalbumArt=UtilFunctions.getAlbumart(context,data.getAlbumId())
if(albumArt!=null){
imageViewAlbumArt.setBackgroundDrawable(newBitmapDrawable(albumArt))
}else{
imageViewAlbumArt.setBackgroundDrawable(newBitmapDrawable(UtilFunctions.getDefaultAlbumArt(context)))
}
linearLayoutPlayingSong.setVisibility(View.VISIBLE)
}catch(Exceptione){}
}
publicstaticvoidchangeButton(){
if(PlayerConstants.SONG_PAUSED){
btnPause.setVisibility(View.GONE)
btnPlay.setVisibility(View.VISIBLE)
}else{
btnPause.setVisibility(View.VISIBLE)
btnPlay.setVisibility(View.GONE)
}
}
publicstaticvoidchangeUI(){
updateUI()
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
11/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
changeButton()
}
}
AudioPlayerActivity.java
importandroid.app.Activity
importandroid.content.Context
importandroid.graphics.Bitmap
importandroid.graphics.PorterDuff.Mode
importandroid.graphics.drawable.BitmapDrawable
importandroid.os.Bundle
importandroid.os.Handler
importandroid.os.Message
importandroid.view.View
importandroid.view.View.OnClickListener
importandroid.widget.Button
importandroid.widget.LinearLayout
importandroid.widget.ProgressBar
importandroid.widget.TextView
importcom.tutorialsface.audioplayer.controls.Controls
importcom.tutorialsface.audioplayer.service.SongService
importcom.tutorialsface.audioplayer.util.PlayerConstants
importcom.tutorialsface.audioplayer.util.UtilFunctions
publicclassAudioPlayerActivityextendsActivity{
ButtonbtnBack
staticButtonbtnPause
ButtonbtnNext
staticButtonbtnPlay
staticTextViewtextNowPlaying
staticTextViewtextAlbumArtist
staticTextViewtextComposer
staticLinearLayoutlinearLayoutPlayer
ProgressBarprogressBar
staticContextcontext
TextViewtextBufferDuration,textDuration
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState)
getActionBar().hide()
setContentView(R.layout.audio_player)
context=this
init()
}
privatevoidinit(){
getViews()
setListeners()
progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.white),
Mode.SRC_IN)
PlayerConstants.PROGRESSBAR_HANDLER=newHandler(){
@Override
publicvoidhandleMessage(Messagemsg){
Integeri[]=(Integer[])msg.obj
textBufferDuration.setText(UtilFunctions.getDuration(i[0]))
textDuration.setText(UtilFunctions.getDuration(i[1]))
progressBar.setProgress(i[2])
}
}
}
privatevoidsetListeners(){
btnBack.setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
Controls.previousControl(getApplicationContext())
}
})
btnPause.setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
Controls.pauseControl(getApplicationContext())
}
})
btnPlay.setOnClickListener(newOnClickListener(){
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
12/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
@Override
publicvoidonClick(Viewv){
Controls.playControl(getApplicationContext())
}
})
btnNext.setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
Controls.nextControl(getApplicationContext())
}
})
}
publicstaticvoidchangeUI(){
updateUI()
changeButton()
}
privatevoidgetViews(){
btnBack=(Button)findViewById(R.id.btnBack)
btnPause=(Button)findViewById(R.id.btnPause)
btnNext=(Button)findViewById(R.id.btnNext)
btnPlay=(Button)findViewById(R.id.btnPlay)
textNowPlaying=(TextView)findViewById(R.id.textNowPlaying)
linearLayoutPlayer=(LinearLayout)findViewById(R.id.linearLayoutPlayer)
textAlbumArtist=(TextView)findViewById(R.id.textAlbumArtist)
textComposer=(TextView)findViewById(R.id.textComposer)
progressBar=(ProgressBar)findViewById(R.id.progressBar)
textBufferDuration=(TextView)findViewById(R.id.textBufferDuration)
textDuration=(TextView)findViewById(R.id.textDuration)
textNowPlaying.setSelected(true)
textAlbumArtist.setSelected(true)
}
@Override
protectedvoidonResume(){
super.onResume()
booleanisServiceRunning=UtilFunctions.isServiceRunning(SongService.class.getName(),
getApplicationContext())
if(isServiceRunning){
updateUI()
}
changeButton()
}
publicstaticvoidchangeButton(){
if(PlayerConstants.SONG_PAUSED){
btnPause.setVisibility(View.GONE)
btnPlay.setVisibility(View.VISIBLE)
}else{
btnPause.setVisibility(View.VISIBLE)
btnPlay.setVisibility(View.GONE)
}
}
privatestaticvoidupdateUI(){
try{
StringsongName=
PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getTitle()
Stringartist=
PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getArtist()
Stringalbum=PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getAlbum()
Stringcomposer=
PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getComposer()
textNowPlaying.setText(songName)
textAlbumArtist.setText(artist+""+album)
if(composer!=null&&composer.length()>0){
textComposer.setVisibility(View.VISIBLE)
textComposer.setText(composer)
}else{
textComposer.setVisibility(View.GONE)
}
}catch(Exceptione){
e.printStackTrace()
}
try{
longalbumId=
PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getAlbumId()
BitmapalbumArt=UtilFunctions.getAlbumart(context,albumId)
if(albumArt!=null){
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
13/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
linearLayoutPlayer.setBackgroundDrawable(newBitmapDrawable(albumArt))
}else{
linearLayoutPlayer.setBackgroundDrawable(newBitmapDrawable(UtilFunctions.getDefaultAlbumArt(context)))
}
}catch(Exceptione){
e.printStackTrace()
}
}
}
C)com.tutorialsface.audioplayer.controlspackagefiles
AudioPlayerActivity.java
packagecom.tutorialsface.audioplayer.controls
importandroid.content.Context
importcom.tutorialsface.audioplayer.R
importcom.tutorialsface.audioplayer.service.SongService
importcom.tutorialsface.audioplayer.util.PlayerConstants
importcom.tutorialsface.audioplayer.util.UtilFunctions
publicclassControls{
staticStringLOG_CLASS="Controls"
publicstaticvoidplayControl(Contextcontext){
sendMessage(context.getResources().getString(R.string.play))
}
publicstaticvoidpauseControl(Contextcontext){
sendMessage(context.getResources().getString(R.string.pause))
}
publicstaticvoidnextControl(Contextcontext){
booleanisServiceRunning=UtilFunctions.isServiceRunning(SongService.class.getName(),
context)
if(!isServiceRunning)
return
if(PlayerConstants.SONGS_LIST.size()>0){
if(PlayerConstants.SONG_NUMBER<(PlayerConstants.SONGS_LIST.size()1)){
PlayerConstants.SONG_NUMBER++
PlayerConstants.SONG_CHANGE_HANDLER.sendMessage(PlayerConstants.SONG_CHANGE_HANDLER.obtainMessage())
}else{
PlayerConstants.SONG_NUMBER=0
PlayerConstants.SONG_CHANGE_HANDLER.sendMessage(PlayerConstants.SONG_CHANGE_HANDLER.obtainMessage())
}
}
PlayerConstants.SONG_PAUSED=false
}
publicstaticvoidpreviousControl(Contextcontext){
booleanisServiceRunning=UtilFunctions.isServiceRunning(SongService.class.getName(),
context)
if(!isServiceRunning)
return
if(PlayerConstants.SONGS_LIST.size()>0){
if(PlayerConstants.SONG_NUMBER>0){
PlayerConstants.SONG_NUMBER
PlayerConstants.SONG_CHANGE_HANDLER.sendMessage(PlayerConstants.SONG_CHANGE_HANDLER.obtainMessage())
}else{
PlayerConstants.SONG_NUMBER=PlayerConstants.SONGS_LIST.size()1
PlayerConstants.SONG_CHANGE_HANDLER.sendMessage(PlayerConstants.SONG_CHANGE_HANDLER.obtainMessage())
}
}
PlayerConstants.SONG_PAUSED=false
}
privatestaticvoidsendMessage(Stringmessage){
try{
PlayerConstants.PLAY_PAUSE_HANDLER.sendMessage(PlayerConstants.PLAY_PAUSE_HANDLER.obtainMessage(0,
message))
}catch(Exceptione){}
}
}
D)com.tutorialsface.audioplayer.adapterpackagefiles
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
14/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
CustomAdapter.java
packagecom.tutorialsface.audioplayer.adapter
importjava.util.ArrayList
importandroid.content.Context
importandroid.view.LayoutInflater
importandroid.view.View
importandroid.view.ViewGroup
importandroid.widget.ArrayAdapter
importandroid.widget.TextView
importcom.tutorialsface.audioplayer.R
importcom.tutorialsface.audioplayer.util.MediaItem
importcom.tutorialsface.audioplayer.util.UtilFunctions
publicclassCustomAdapterextendsArrayAdapter<MediaItem>{
ArrayList<MediaItem>listOfSongs
Contextcontext
LayoutInflaterinflator
publicCustomAdapter(Contextcontext,intresource,ArrayList<MediaItem>listOfSongs){
super(context,resource,listOfSongs)
this.listOfSongs=listOfSongs
this.context=context
inflator=LayoutInflater.from(context)
}
privateclassViewHolder{
TextViewtextViewSongName,textViewArtist,textViewDuration
}
ViewHolderholder
@Override
publicViewgetView(intposition,ViewconvertView,ViewGroupparent){
ViewmyView=convertView
if(convertView==null){
myView=inflator.inflate(R.layout.custom_list,parent,false)
holder=newViewHolder()
holder.textViewSongName=(TextView)myView.findViewById(R.id.textViewSongName)
holder.textViewArtist=(TextView)myView.findViewById(R.id.textViewArtist)
holder.textViewDuration=(TextView)myView.findViewById(R.id.textViewDuration)
myView.setTag(holder)
}else{
holder=(ViewHolder)myView.getTag()
}
MediaItemdetail=listOfSongs.get(position)
holder.textViewSongName.setText(detail.toString())
holder.textViewArtist.setText(detail.getAlbum()+""+detail.getArtist())
holder.textViewDuration.setText(UtilFunctions.getDuration(detail.getDuration()))
returnmyView
}
}
E)com.tutorialsface.audioplayer.receiverpackagefiles
NotificationBroadcast.java
packagecom.tutorialsface.audioplayer.receiver
importandroid.content.BroadcastReceiver
importandroid.content.Context
importandroid.content.Intent
importandroid.util.Log
importandroid.view.KeyEvent
importcom.tutorialsface.audioplayer.MainActivity
importcom.tutorialsface.audioplayer.controls.Controls
importcom.tutorialsface.audioplayer.service.SongService
importcom.tutorialsface.audioplayer.util.PlayerConstants
publicclassNotificationBroadcastextendsBroadcastReceiver{
@Override
publicvoidonReceive(Contextcontext,Intentintent){
if(intent.getAction().equals(Intent.ACTION_MEDIA_BUTTON)){
KeyEventkeyEvent=(KeyEvent)intent.getExtras().get(Intent.EXTRA_KEY_EVENT)
if(keyEvent.getAction()!=KeyEvent.ACTION_DOWN)
return
switch(keyEvent.getKeyCode()){
caseKeyEvent.KEYCODE_HEADSETHOOK:
caseKeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
15/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
if(!PlayerConstants.SONG_PAUSED){
Controls.pauseControl(context)
}else{
Controls.playControl(context)
}
break
caseKeyEvent.KEYCODE_MEDIA_PLAY:
break
caseKeyEvent.KEYCODE_MEDIA_PAUSE:
break
caseKeyEvent.KEYCODE_MEDIA_STOP:
break
caseKeyEvent.KEYCODE_MEDIA_NEXT:
Log.d("TAG","TAG:KEYCODE_MEDIA_NEXT")
Controls.nextControl(context)
break
caseKeyEvent.KEYCODE_MEDIA_PREVIOUS:
Log.d("TAG","TAG:KEYCODE_MEDIA_PREVIOUS")
Controls.previousControl(context)
break
}
}else{
if(intent.getAction().equals(SongService.NOTIFY_PLAY)){
Controls.playControl(context)
}elseif(intent.getAction().equals(SongService.NOTIFY_PAUSE)){
Controls.pauseControl(context)
}elseif(intent.getAction().equals(SongService.NOTIFY_NEXT)){
Controls.nextControl(context)
}elseif(intent.getAction().equals(SongService.NOTIFY_DELETE)){
Intenti=newIntent(context,SongService.class)
context.stopService(i)
Intentin=newIntent(context,MainActivity.class)
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(in)
}elseif(intent.getAction().equals(SongService.NOTIFY_PREVIOUS)){
Controls.previousControl(context)
}
}
}
publicStringComponentName(){
returnthis.getClass().getName()
}
}
F)com.tutorialsface.audioplayer.servicepackagefiles
SongService.java
packagecom.tutorialsface.audioplayer.service
importjava.io.IOException
importjava.util.Timer
importjava.util.TimerTask
importandroid.annotation.SuppressLint
importandroid.app.Notification
importandroid.app.PendingIntent
importandroid.app.Service
importandroid.content.ComponentName
importandroid.content.Intent
importandroid.graphics.Bitmap
importandroid.graphics.BitmapFactory
importandroid.media.AudioManager
importandroid.media.MediaMetadataRetriever
importandroid.media.MediaPlayer
importandroid.media.MediaPlayer.OnCompletionListener
importandroid.media.RemoteControlClient
importandroid.media.RemoteControlClient.MetadataEditor
importandroid.os.Handler
importandroid.os.Handler.Callback
importandroid.os.IBinder
importandroid.os.Message
importandroid.support.v4.app.NotificationCompat
importandroid.util.Log
importandroid.view.View
importandroid.widget.RemoteViews
importcom.tutorialsface.audioplayer.AudioPlayerActivity
importcom.tutorialsface.audioplayer.MainActivity
importcom.tutorialsface.audioplayer.R
importcom.tutorialsface.audioplayer.controls.Controls
importcom.tutorialsface.audioplayer.receiver.NotificationBroadcast
importcom.tutorialsface.audioplayer.util.MediaItem
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
16/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
importcom.tutorialsface.audioplayer.util.PlayerConstants
importcom.tutorialsface.audioplayer.util.UtilFunctions
publicclassSongServiceextendsServiceimplementsAudioManager.OnAudioFocusChangeListener{
StringLOG_CLASS="SongService"
privateMediaPlayermp
intNOTIFICATION_ID=1111
publicstaticfinalStringNOTIFY_PREVIOUS="com.tutorialsface.audioplayer.previous"
publicstaticfinalStringNOTIFY_DELETE="com.tutorialsface.audioplayer.delete"
publicstaticfinalStringNOTIFY_PAUSE="com.tutorialsface.audioplayer.pause"
publicstaticfinalStringNOTIFY_PLAY="com.tutorialsface.audioplayer.play"
publicstaticfinalStringNOTIFY_NEXT="com.tutorialsface.audioplayer.next"
privateComponentNameremoteComponentName
privateRemoteControlClientremoteControlClient
AudioManageraudioManager
BitmapmDummyAlbumArt
privatestaticTimertimer
privatestaticbooleancurrentVersionSupportBigNotification=false
privatestaticbooleancurrentVersionSupportLockScreenControls=false
@Override
publicIBinderonBind(Intentintent){
returnnull
}
@Override
publicvoidonCreate(){
mp=newMediaPlayer()
audioManager=(AudioManager)getSystemService(AUDIO_SERVICE)
currentVersionSupportBigNotification=UtilFunctions.currentVersionSupportBigNotification()
currentVersionSupportLockScreenControls=
UtilFunctions.currentVersionSupportLockScreenControls()
timer=newTimer()
mp.setOnCompletionListener(newOnCompletionListener(){
@Override
publicvoidonCompletion(MediaPlayermp){
Controls.nextControl(getApplicationContext())
}
})
super.onCreate()
}
/**
*Sendmessagefromtimer
*@authorjonty.ankit
*/
privateclassMainTaskextendsTimerTask{
publicvoidrun(){
handler.sendEmptyMessage(0)
}
}
privatefinalHandlerhandler=newHandler(){
@Override
publicvoidhandleMessage(Messagemsg){
if(mp!=null){
intprogress=(mp.getCurrentPosition()*100)/mp.getDuration()
Integeri[]=newInteger[3]
i[0]=mp.getCurrentPosition()
i[1]=mp.getDuration()
i[2]=progress
try{
PlayerConstants.PROGRESSBAR_HANDLER.sendMessage(PlayerConstants.PROGRESSBAR_HANDLER.obtainMessage(0,
i))
}catch(Exceptione){}
}
}
}
@SuppressLint("NewApi")
@Override
publicintonStartCommand(Intentintent,intflags,intstartId){
try{
if(PlayerConstants.SONGS_LIST.size()<=0){
PlayerConstants.SONGS_LIST=
UtilFunctions.listOfSongs(getApplicationContext())
}
MediaItemdata=PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER)
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
17/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
if(currentVersionSupportLockScreenControls){
RegisterRemoteClient()
}
StringsongPath=data.getPath()
playSong(songPath,data)
newNotification()
PlayerConstants.SONG_CHANGE_HANDLER=newHandler(newCallback(){
@Override
publicbooleanhandleMessage(Messagemsg){
MediaItemdata=
PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER)
StringsongPath=data.getPath()
newNotification()
try{
playSong(songPath,data)
MainActivity.changeUI()
AudioPlayerActivity.changeUI()
}catch(Exceptione){
e.printStackTrace()
}
returnfalse
}
})
PlayerConstants.PLAY_PAUSE_HANDLER=newHandler(newCallback(){
@Override
publicbooleanhandleMessage(Messagemsg){
Stringmessage=(String)msg.obj
if(mp==null)
returnfalse
if(message.equalsIgnoreCase(getResources().getString(R.string.play))){
PlayerConstants.SONG_PAUSED=false
if(currentVersionSupportLockScreenControls){
remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING)
}
mp.start()
}else
if(message.equalsIgnoreCase(getResources().getString(R.string.pause))){
PlayerConstants.SONG_PAUSED=true
if(currentVersionSupportLockScreenControls){
remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PAUSED)
}
mp.pause()
}
newNotification()
try{
MainActivity.changeButton()
AudioPlayerActivity.changeButton()
}catch(Exceptione){}
Log.d("TAG","TAGPressed:"+message)
returnfalse
}
})
}catch(Exceptione){
e.printStackTrace()
}
returnSTART_STICKY
}
/**
*Notification
*CustomBignotificationisavailablefromAPI16
*/
@SuppressLint("NewApi")
privatevoidnewNotification(){
StringsongName=
PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getTitle()
StringalbumName=
PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getAlbum()
RemoteViewssimpleContentView=new
RemoteViews(getApplicationContext().getPackageName(),R.layout.custom_notification)
RemoteViewsexpandedView=newRemoteViews(getApplicationContext().getPackageName(),
R.layout.big_notification)
Notificationnotification=newNotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.ic_music)
.setContentTitle(songName).build()
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
18/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
setListeners(simpleContentView)
setListeners(expandedView)
notification.contentView=simpleContentView
if(currentVersionSupportBigNotification){
notification.bigContentView=expandedView
}
try{
longalbumId=
PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getAlbumId()
BitmapalbumArt=UtilFunctions.getAlbumart(getApplicationContext(),albumId)
if(albumArt!=null){
notification.contentView.setImageViewBitmap(R.id.imageViewAlbumArt,
albumArt)
if(currentVersionSupportBigNotification){
notification.bigContentView.setImageViewBitmap(R.id.imageViewAlbumArt,
albumArt)
}
}else{
notification.contentView.setImageViewResource(R.id.imageViewAlbumArt,
R.drawable.default_album_art)
if(currentVersionSupportBigNotification){
notification.bigContentView.setImageViewResource(R.id.imageViewAlbumArt,
R.drawable.default_album_art)
}
}
}catch(Exceptione){
e.printStackTrace()
}
if(PlayerConstants.SONG_PAUSED){
notification.contentView.setViewVisibility(R.id.btnPause,View.GONE)
notification.contentView.setViewVisibility(R.id.btnPlay,View.VISIBLE)
if(currentVersionSupportBigNotification){
notification.bigContentView.setViewVisibility(R.id.btnPause,View.GONE)
notification.bigContentView.setViewVisibility(R.id.btnPlay,View.VISIBLE)
}
}else{
notification.contentView.setViewVisibility(R.id.btnPause,View.VISIBLE)
notification.contentView.setViewVisibility(R.id.btnPlay,View.GONE)
if(currentVersionSupportBigNotification){
notification.bigContentView.setViewVisibility(R.id.btnPause,View.VISIBLE)
notification.bigContentView.setViewVisibility(R.id.btnPlay,View.GONE)
}
}
notification.contentView.setTextViewText(R.id.textSongName,songName)
notification.contentView.setTextViewText(R.id.textAlbumName,albumName)
if(currentVersionSupportBigNotification){
notification.bigContentView.setTextViewText(R.id.textSongName,songName)
notification.bigContentView.setTextViewText(R.id.textAlbumName,albumName)
}
notification.flags|=Notification.FLAG_ONGOING_EVENT
startForeground(NOTIFICATION_ID,notification)
}
/**
*Notificationclicklisteners
*@paramview
*/
publicvoidsetListeners(RemoteViewsview){
Intentprevious=newIntent(NOTIFY_PREVIOUS)
Intentdelete=newIntent(NOTIFY_DELETE)
Intentpause=newIntent(NOTIFY_PAUSE)
Intentnext=newIntent(NOTIFY_NEXT)
Intentplay=newIntent(NOTIFY_PLAY)
PendingIntentpPrevious=PendingIntent.getBroadcast(getApplicationContext(),0,
previous,PendingIntent.FLAG_UPDATE_CURRENT)
view.setOnClickPendingIntent(R.id.btnPrevious,pPrevious)
PendingIntentpDelete=PendingIntent.getBroadcast(getApplicationContext(),0,delete,
PendingIntent.FLAG_UPDATE_CURRENT)
view.setOnClickPendingIntent(R.id.btnDelete,pDelete)
PendingIntentpPause=PendingIntent.getBroadcast(getApplicationContext(),0,pause,
PendingIntent.FLAG_UPDATE_CURRENT)
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
19/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
view.setOnClickPendingIntent(R.id.btnPause,pPause)
PendingIntentpNext=PendingIntent.getBroadcast(getApplicationContext(),0,next,
PendingIntent.FLAG_UPDATE_CURRENT)
view.setOnClickPendingIntent(R.id.btnNext,pNext)
PendingIntentpPlay=PendingIntent.getBroadcast(getApplicationContext(),0,play,
PendingIntent.FLAG_UPDATE_CURRENT)
view.setOnClickPendingIntent(R.id.btnPlay,pPlay)
}
@Override
publicvoidonDestroy(){
if(mp!=null){
mp.stop()
mp=null
}
super.onDestroy()
}
/**
*Playsong,UpdateLockscreenfields
*@paramsongPath
*@paramdata
*/
@SuppressLint("NewApi")
privatevoidplaySong(StringsongPath,MediaItemdata){
try{
if(currentVersionSupportLockScreenControls){
UpdateMetadata(data)
remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING)
}
mp.reset()
mp.setDataSource(songPath)
mp.prepare()
mp.start()
timer.scheduleAtFixedRate(newMainTask(),0,100)
}catch(IOExceptione){
e.printStackTrace()
}
}
@SuppressLint("NewApi")
privatevoidRegisterRemoteClient(){
remoteComponentName=newComponentName(getApplicationContext(),new
NotificationBroadcast().ComponentName())
try{
if(remoteControlClient==null){
audioManager.registerMediaButtonEventReceiver(remoteComponentName)
IntentmediaButtonIntent=newIntent(Intent.ACTION_MEDIA_BUTTON)
mediaButtonIntent.setComponent(remoteComponentName)
PendingIntentmediaPendingIntent=PendingIntent.getBroadcast(this,0,
mediaButtonIntent,0)
remoteControlClient=newRemoteControlClient(mediaPendingIntent)
audioManager.registerRemoteControlClient(remoteControlClient)
}
remoteControlClient.setTransportControlFlags(
RemoteControlClient.FLAG_KEY_MEDIA_PLAY|
RemoteControlClient.FLAG_KEY_MEDIA_PAUSE|
RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE|
RemoteControlClient.FLAG_KEY_MEDIA_STOP|
RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS|
RemoteControlClient.FLAG_KEY_MEDIA_NEXT)
}catch(Exceptionex){
}
}
@SuppressLint("NewApi")
privatevoidUpdateMetadata(MediaItemdata){
if(remoteControlClient==null)
return
MetadataEditormetadataEditor=remoteControlClient.editMetadata(true)
metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_ALBUM,data.getAlbum())
metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST,data.getArtist())
metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_TITLE,data.getTitle())
mDummyAlbumArt=UtilFunctions.getAlbumart(getApplicationContext(),data.getAlbumId())
if(mDummyAlbumArt==null){
mDummyAlbumArt=BitmapFactory.decodeResource(getResources(),
R.drawable.default_album_art)
}
metadataEditor.putBitmap(RemoteControlClient.MetadataEditor.BITMAP_KEY_ARTWORK,
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
20/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
mDummyAlbumArt)
metadataEditor.apply()
audioManager.requestAudioFocus(this,AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN)
}
@Override
publicvoidonAudioFocusChange(intfocusChange){}
}
UIxml
activity_main.xml
<?xmlversion="1.0"encoding="utf8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayoutMusicList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:background="@drawable/default_album_art_thumb"
android:orientation="vertical">
<ListView
android:id="@+id/listViewMusic"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="@android:color/transparent"/>
<LinearLayout
android:id="@+id/linearLayoutPlayingSong"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/orange"
android:gravity="center"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@android:color/darker_gray"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|bottom"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageViewAlbumArt"
android:layout_width="@dimen/small_image_art_width"
android:layout_height="@dimen/small_image_art_width"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/textNowPlaying"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ellipsize="marquee"
android:gravity="center_horizontal"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
android:text="@string/empty_text"
android:textColor="@color/white"
android:textSize="15dp"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal">
<Button
android:id="@+id/btnPrevious"
android:layout_width="@dimen/small_button_width"
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
21/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
android:layout_height="@dimen/small_button_width"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@drawable/ic_action_previous"/>
<Button
android:id="@+id/btnPlay"
android:layout_width="@dimen/small_button_width"
android:layout_height="@dimen/small_button_width"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@drawable/ic_action_play"
android:visibility="gone"/>
<Button
android:id="@+id/btnPause"
android:layout_width="@dimen/small_button_width"
android:layout_height="@dimen/small_button_width"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@drawable/ic_action_pause"/>
<Button
android:id="@+id/btnStop"
android:layout_width="@dimen/small_button_width"
android:layout_height="@dimen/small_button_width"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@drawable/ic_action_stop"/>
<Button
android:id="@+id/btnNext"
android:layout_width="@dimen/small_button_width"
android:layout_height="@dimen/small_button_width"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@drawable/ic_action_next"/>
<Button
android:id="@+id/btnMusicPlayer"
android:layout_width="@dimen/small_button_width"
android:layout_height="@dimen/small_button_width"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@drawable/ic_music"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="horizontal">
<TextView
android:id="@+id/textBufferDuration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="@color/white"/>
<TextView
android:id="@+id/textDuration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:textColor="@color/white"/>
</LinearLayout>
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp"
android:layout_marginLeft="10dp"
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
22/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
android:layout_marginRight="10dp"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
audio_player.xml
<?xmlversion="1.0"encoding="utf8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayoutPlayer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/default_album_art"
android:gravity="center"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#70000000"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/textNowPlaying"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:gravity="center_horizontal"
android:marqueeRepeatLimit="marquee_forever"
android:paddingLeft="5dp"
android:paddingTop="20dp"
android:singleLine="true"
android:text="@string/idle"
android:textColor="@color/white"
android:textSize="30dp"/>
<TextView
android:id="@+id/textAlbumArtist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:gravity="center_horizontal"
android:marqueeRepeatLimit="marquee_forever"
android:paddingLeft="5dp"
android:singleLine="true"
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
23/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
android:textColor="@color/white"
android:textSize="15dp"/>
<TextView
android:id="@+id/textComposer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:paddingLeft="5dp"
android:textColor="@color/white"
android:textSize="15dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="horizontal">
<TextView
android:id="@+id/textBufferDuration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="@color/white"/>
<TextView
android:id="@+id/textDuration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:textColor="@color/white"/>
</LinearLayout>
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@android:color/darker_gray"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center|bottom"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:background="@color/orange"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="@+id/btnBack"
android:layout_width="@dimen/button_width"
android:layout_height="@dimen/button_width"
android:layout_margin="10dp"
android:background="@drawable/ic_action_previous"/>
<View
android:layout_width="1dp"
android:layout_height="@dimen/button_width"
android:background="@android:color/darker_gray"/>
<Button
android:id="@+id/btnPause"
android:layout_width="@dimen/button_width"
android:layout_height="@dimen/button_width"
android:layout_margin="10dp"
android:background="@drawable/ic_action_pause"
android:visibility="gone"/>
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
24/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
<Button
android:id="@+id/btnPlay"
android:layout_width="@dimen/button_width"
android:layout_height="@dimen/button_width"
android:layout_margin="10dp"
android:background="@drawable/ic_action_play"/>
<View
android:layout_width="1dp"
android:layout_height="@dimen/button_width"
android:background="@android:color/darker_gray"/>
<Button
android:id="@+id/btnNext"
android:layout_width="@dimen/button_width"
android:layout_height="@dimen/button_width"
android:layout_margin="10dp"
android:background="@drawable/ic_action_next"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
custom_list.xml
<?xmlversion="1.0"encoding="utf8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:orientation="vertical">
<TextView
android:id="@+id/textViewSongName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:singleLine="true"
android:textColor="@android:color/white"
android:textSize="22dp"/>
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
25/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/textViewArtist"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:layout_weight="1"
android:textColor="@android:color/white"
android:textSize="15dp"/>
<TextView
android:id="@+id/textViewDuration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:layout_marginLeft="10dp"
android:textSize="12dp"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
Notificationxml
custom_notification.xml
<?xmlversion="1.0"encoding="utf8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageViewAlbumArt"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="@drawable/ic_launcher"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="@+id/textSongName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:selectAllOnFocus="true"
android:singleLine="true"
android:textColor="@android:color/white"
android:textSize="20dp"/>
<TextView
android:id="@+id/textAlbumName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:gravity="center_vertical"
android:marqueeRepeatLimit="marquee_forever"
android:selectAllOnFocus="true"
android:singleLine="true"
android:textColor="#C0C0C0"
android:textSize="15dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
26/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
android:layout_height="wrap_content"
android:layout_weight="1.5"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="@+id/btnPause"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_margin="5dp"
android:background="@drawable/ic_action_pause"/>
<Button
android:id="@+id/btnPlay"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_margin="5dp"
android:background="@drawable/ic_action_play"
android:visibility="gone"/>
<Button
android:id="@+id/btnNext"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_margin="5dp"
android:background="@drawable/ic_action_next"/>
</LinearLayout>
<Button
android:id="@+id/btnDelete"
android:layout_width="28dp"
android:layout_height="28dp"
android:layout_marginLeft="5dp"
android:background="@drawable/ic_action_remove"/>
</LinearLayout>
</LinearLayout>
big_notification.xml
<?xmlversion="1.0"encoding="utf8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageViewAlbumArt"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/ic_launcher"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:padding="5dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/textSongName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical"
android:singleLine="true"
android:textColor="@android:color/white"
android:textSize="20dp"/>
<Button
android:id="@+id/btnDelete"
android:layout_width="28dp"
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
27/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
android:layout_height="28dp"
android:layout_marginLeft="5dp"
android:background="@drawable/ic_action_remove"/>
</LinearLayout>
<TextView
android:id="@+id/textAlbumName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:singleLine="true"
android:textColor="#C0C0C0"
android:textSize="15dp"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:divider="@drawable/mydivider"
android:dividerPadding="12.0dip"
android:gravity="center"
android:orientation="horizontal"
android:showDividers="middle">
<Button
android:id="@+id/btnPrevious"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_margin="5dp"
android:background="@drawable/ic_action_previous"/>
<Button
android:id="@+id/btnPause"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_margin="5dp"
android:background="@drawable/ic_action_pause"/>
<Button
android:id="@+id/btnPlay"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_margin="5dp"
android:background="@drawable/ic_action_play"
android:visibility="gone"/>
<Button
android:id="@+id/btnNext"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_margin="5dp"
android:background="@drawable/ic_action_next"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
strings.xml
<resources>
<stringname="app_name">MusicPlayer</string>
<stringname="back">Back</string>
<stringname="pause">Pause</string>
<stringname="play">Play</string>
<stringname="player">AudioPlayer</string>
<stringname="next">Next</string>
<stringname="open_playlist">OpenPlaylist</string>
<stringname="idle">Idle</string>
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
28/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
<stringname="empty_text">Selectsongfrombelowtoplay</string>
<stringname="player_button">AlbumArtScreen</string>
<colorname="orange">#ff3d00</color>
<colorname="white">#ffffff</color>
<colorname="opaque">#70000000</color>
<dimenname="button_width">32dp</dimen>
<dimenname="small_button_width">28dp</dimen>
<dimenname="small_image_art_width">85dp</dimen>
</resources>
AndroidManifest.xml
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutorialsface.audioplayer"
android:versionCode="1"
android:versionName="1.0">
<usessdk
android:minSdkVersion="11"
android:targetSdkVersion="19"/>
<usespermissionandroid:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name="com.tutorialsface.audioplayer.MainActivity"
android:launchMode="singleTask"
android:screenOrientation="portrait">
<intentfilter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intentfilter>
</activity>
<activity
android:name="com.tutorialsface.audioplayer.AudioPlayerActivity"
android:excludeFromRecents="true"
android:launchMode="singleTask"
android:screenOrientation="portrait">
</activity>
<service
android:name="com.tutorialsface.audioplayer.service.SongService"
android:exported="true"
android:enabled="true"/>
<receiverandroid:name="com.tutorialsface.audioplayer.receiver.NotificationBroadcast">
<intentfilter>
<actionandroid:name="com.tutorialsface.audioplayer.delete"/>
<actionandroid:name="com.tutorialsface.audioplayer.pause"/>
<actionandroid:name="com.tutorialsface.audioplayer.next"/>
<actionandroid:name="com.tutorialsface.audioplayer.play"/>
<actionandroid:name="com.tutorialsface.audioplayer.previous"/>
<actionandroid:name="android.intent.action.MEDIA_BUTTON"/>
</intentfilter>
</receiver>
</application>
</manifest>
PostedbyAnkitKumarat11:29
Labels:Apps,MusicPlayer
14comments:
cpot 6December2014at07:49
Thiscommenthasbeenremovedbytheauthor.
Reply
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
29/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
RahulAgarwal 18December2014at21:54
HI,Iamusing'rtsp'streamingandgettingaissuei.e.PlayerisgettingstuckforsometimeonRemoteControlClientand
NotificationUpdate.
Reply
stasp77 26January2015at12:54
Hi,Brillianttutorial,Thankyou.
IamwonderinghowIcouldgoaboutupdatingthelistoffiles.
WhatIamtryingtodoisdownloadafile,andhavetheapplicationupdatethelist.
So
far,
I
have
the
app
calling
the
"PlayerConstants.SONGS_LIST
=
utilFunctions.listOfSongs(getActivity().getApplicationContext())",butthisdoesnotreturnnewitems(onlyreturnsthesame
itemsagain),UNLESSthedeviceisrestarted.
HowcanIhavethelistupdatewithoutfirstrestartingthedeviceandrelaunchingtheapp?
Thankyou.
Reply
Replies
stasp77 26January2015at13:08
Justafterposting,IfoundthatIneedtocallMediaScannertorescanthelibrary.
Anyone with similar problem, read here: http://stackoverflow.com/questions/2170214/imagesavedtosdcard
doesntappearinandroidsgalleryapp
Sorryaboutthis.
Reply
brianmigel 15May2015at04:32
hey thanx for this gr8 tutorial... i would love some help though on how to organise the music according to artists and
albums
Reply
Replies
AnkitKumar
16May2015at02:57
https://www.dropbox.com/s/jgjd94xqdicr221/LibMedia.java?dl=0
brianmigel 20May2015at03:00
Hey Kumar. thanx for the help. was wondering if you mind helping me with your sample code for the whole
player.Pleaaseebemyhero,andthanxinadvance.
brianmigel 20May2015at03:17
orjusttheLogUtilsclass.thankyouverymuch
brianmigel 21May2015at00:48
[email protected]
brianmigel 25May2015at03:38
Hey Ankit thank you for the help but was still wondering if you could help me with the LogUtils class and the
customadapterclasses.thankyouagaininadvance
JoywinMissier 21June2015at00:25
howtogetthesongsfromonlineie)likegaana
AnkitKumar
21June2015at03:50
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
30/31
13/8/2015
TutorialsFace:MusicPlayerwithNotificationandLockScreenControls
GaanahaveitsownAPI.YoucantryRdio.
Reply
IrisLouis 7July2015at05:59
Thiscommenthasbeenremovedbytheauthor.
Reply
JatinKumar 16July2015at04:39
awesome
Reply
Enteryourcomment...
Commentas:
Publish
Unknown(Google)
Signout
Notifyme
Preview
NewerPost
Home
OlderPost
Subscribeto:PostComments(Atom)
PictureWindowtemplate.TemplateimagesbyDeejpilot.PoweredbyBlogger.
http://tutorialsface.blogspot.com/2014/07/musicplayerwithnotificationandlock.html
31/31