8

Android では、 と を使用ServiceMediaPlayerて音楽を再生します。ホームボタンを押すと音楽が流れ続けますが、アプリを「スワイプ」すると停止します。

アプリをスワイプした後、音楽の再生を続けるにはどうすればよいですか?

4

3 に答える 3

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 に答える