2011-11-28 110 views
1

我使用了一个通知,称为播放器服务,该播放器应播放音乐。 但我不知道如何在后台播放?如何通过android中的通知播放音乐?

你可以看到我的代码如下:

1.首先文件调用播放器服务

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

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

startService(i); 

2.Second文件是一个娱乐类音乐

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

感谢和问候,Omid

+0

请考虑改写这个问题,至少对我来说还不清楚。你到底在找什么?媒体播放器在您的应用/活动的后台播放? –

+0

我想在下载软件包时播放很长的声音。然后,在通知中都显示进度条和播放声音。 –

回答

1

大概你已经找到了答案,但也许这将是他lpfull给别人。也就是说,通知类有sound方法,它需要指向想要通知发生的文件的路径。有关更多信息,请参阅notification examples(特别是“添加声音”段落)。