8

在 Android 中,我使用ServiceMediaPlayer来播放音乐。当我按下主页按钮时音乐继续播放,但如果我“滑动”应用程序则停止。

刷掉应用后如何继续播放音乐?

4

3 回答 3

0

Android媒体播放器代码使用包含 MediaPlayer 对象的服务。即使 Activity 不在前台,这也允许播放继续。

于 2013-07-26T00:55:15.473 回答
0

您需要使用Service.START_STICKY

public int onStartCommand(Intent intent, int flags, int startId) {
    mediaPlayer.start();
    return Service.START_STICKY;
}

Service.START_STICKY:如果该服务的进程在启动时被杀死,系统将尝试重新创建该服务。

这是一个完整的例子: https ://github.com/Jorgesys/Android-Music-in-Background

public class BackgroundSoundService extends Service {

    private static final String TAG = "BackgroundSoundService";
    MediaPlayer player;

    public IBinder onBind(Intent arg0) {
        Log.i(TAG, "onBind()" );
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        player = MediaPlayer.create(this, R.raw.jorgesys_song);
        player.setLooping(true); 
        player.setVolume(100, 100);
        Toast.makeText(this, "Service started...", Toast.LENGTH_SHORT).show();
        Log.i(TAG, "onCreate() , service started...");

    }
    public int onStartCommand(Intent intent, int flags, int startId) {
        player.start();
        return Service.START_STICKY;
    }

    public IBinder onUnBind(Intent arg0) {
        Log.i(TAG, "onUnBind()");
        return null;
    }

    public void onStop() {
        Log.i(TAG, "onStop()");
    }
    public void onPause() {
        Log.i(TAG, "onPause()");
    }
    @Override
    public void onDestroy() {
        player.stop();
        player.release();
        Toast.makeText(this, "Service stopped...", Toast.LENGTH_SHORT).show();
        Log.i(TAG, "onCreate() , service stopped...");
    }

    @Override
    public void onLowMemory() {
        Log.i(TAG, "onLowMemory()");
    }
}
于 2017-04-07T20:10:25.357 回答
-1

You need to use foreground service to keep playing music when app closed

 private fun createNotification() {
        val notification = NotificationCompat.Builder(this, CHANNEL_1_ID)
            .setSmallIcon(R.drawable.ic_notify)
            .setContentTitle(titleSong)
            .setContentText(artist)
            .setLargeIcon(artwork)
            .setSound(null)
            .setShowWhen(false)
            .setColorized(true)
            .setColor(Color.BLACK)
            .setContentIntent(intentPlayer)
            .addAction(R.drawable.ic_previous, "Previous", pendingPre)
            .addAction(drawable_id, "Play", pendingPlay)
            .addAction(R.drawable.ic_next, "Next", pendingNext)
            .setDeleteIntent(pendingDelete)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setStyle(
                androidx.media.app.NotificationCompat.MediaStyle()
                    .setShowActionsInCompactView(0, 1, 2)
            )
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .build()
        startForeground(1, notification)
      
    }

call above method when app closed

于 2021-08-13T09:02:13.077 回答