[英]how to play a music by notification in android?
我使用了一个通知,通知播放器服务,并且该播放器应播放音乐。 但是我不知道怎么在后台玩吗?
您可以看到以下代码:
1.First File Call Player服务
Intent i=new Intent(this, PlayerService.class);
i.putExtra(PlayerService.EXTRA_PLAYLIST, "main");
i.putExtra(PlayerService.EXTRA_SHUFFLE, true);
startService(i);
2.第二个文件是播放音乐的类
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);
}
}
}
感谢和问候,奥米德
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.