Omid Nazifi
Omid Nazifi

Reputation: 5234

how to play a music by notification in android?

I used a notification that call a player service and this player should play a music. But I don't know how to play in background?

you can see my code the following :

1.First File call player service

Intent i=new Intent(this, PlayerService.class);

i.putExtra(PlayerService.EXTRA_PLAYLIST, "main");
i.putExtra(PlayerService.EXTRA_SHUFFLE, true);

startService(i);

2.Second file is a class for play a music

public class PlayerService extends Service {
    public static final String EXTRA_PLAYLIST="EXTRA_PLAYLIST";
    public static final String EXTRA_SHUFFLE="EXTRA_SHUFFLE";
    private boolean isPlaying=false;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String playlist=intent.getStringExtra(EXTRA_PLAYLIST);
        boolean useShuffle=intent.getBooleanExtra(EXTRA_SHUFFLE, false);

        play(playlist, useShuffle);       
        return(START_NOT_STICKY);
    }

    @Override
    public void onDestroy() {
        stop();
    }

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

    private void play(String playlist, boolean useShuffle) {
        if (!isPlaying) {
            Log.w(getClass().getName(), "Got to play()!");
            isPlaying=true;

            Notification note=new Notification(R.drawable.stat_notify_chat, "Can you hear the music?", System.currentTimeMillis());
            Intent i=new Intent(this, FakePlayer.class);
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_SINGLE_TOP);

            PendingIntent pi=PendingIntent.getActivity(this, 0,i, 0);

            note.setLatestEventInfo(this, "Fake Player","Now Playing: \"Ummmm, Nothing\"", pi);
            note.flags|=Notification.FLAG_NO_CLEAR;

            startForeground(1337, note);
        }
    }
    private void stop() {
        if (isPlaying) {
            Log.w(getClass().getName(), "Got to stop()!");
            isPlaying=false;
            stopForeground(true);
        }
    }
}

Thanks and Regards, Omid

Upvotes: 1

Views: 989

Answers (1)

Krzysztow
Krzysztow

Reputation: 781

Probably You have already found the answer, but maybe it will be helpfull to someone else. Namely, Notification class has sound method, that requires path to the file one wants to play on notification occurence. See notification examples (expecially "Adding a sound" paragraph) for more information.

Upvotes: 1

Related Questions