在 Android 中,我使用Service
和MediaPlayer
来播放音乐。当我按下主页按钮时音乐继续播放,但如果我“滑动”应用程序则停止。
刷掉应用后如何继续播放音乐?
在 Android 中,我使用Service
和MediaPlayer
来播放音乐。当我按下主页按钮时音乐继续播放,但如果我“滑动”应用程序则停止。
刷掉应用后如何继续播放音乐?
您需要使用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()");
}
}
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