Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/210.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在android中通过通知播放音乐?_Android_Notifications_Android Service - Fatal编程技术网

如何在android中通过通知播放音乐?

如何在android中通过通知播放音乐?,android,notifications,android-service,Android,Notifications,Android Service,我使用了一个通知来调用播放器服务,这个播放器应该播放音乐。 但我不知道如何在后台玩 您可以在下面看到我的代码: 1.第一文件呼叫播放器服务 Intent i=new Intent(this, PlayerService.class); i.putExtra(PlayerService.EXTRA_PLAYLIST, "main"); i.putExtra(PlayerService.EXTRA_SHUFFLE, true); startService(i); 2.第二个文件是播放音乐的类

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

您可以在下面看到我的代码:

1.第一文件呼叫播放器服务

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

谢谢和问候,Omid

也许你已经找到了答案,但也许对其他人会有帮助。也就是说,通知类有一个方法,该方法要求在通知发生时要播放的文件的路径。有关更多信息,请参见(特别是“添加声音”一段)

也许你已经找到了答案,但也许对其他人会有帮助。也就是说,通知类有一个方法,该方法要求在通知发生时要播放的文件的路径。有关更多信息,请参见(特别是“添加声音”一段)