如何通过Android中的通知播放音乐?

时间:2011-11-28 06:53:46

标签: android notifications android-service

我使用了一个叫播放器服务的通知,这个播放器应该播放音乐。 但我不知道如何在后台玩?

您可以看到以下代码:

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是一个播放音乐的课程

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);
        }
    }
}

谢谢和问候,奥米德

1 个答案:

答案 0 :(得分:1)

可能你已经找到了答案,但也许对其他人有帮助。也就是说,Notification类具有sound方法,该方法需要在通知发生时想要播放的文件的路径。有关详细信息,请参阅notification examples(特别是“添加声音”段落)。