要确定通知的音频何时停止播放,可以使用 MediaPlayer
类来控制音频的播放和停止。以下是一个示例代码,展示了如何在 Android 上实现此功能:
首先,在 AndroidManifest.xml 文件中添加以下权限:
然后,创建一个 Service 类,用于处理通知音频的播放和停止。在该 Service 类中,我们将创建一个 MediaPlayer
对象,并在通知被移除时停止音频的播放。以下是一个示例代码:
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.IBinder;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
public class MyService extends Service {
private static final String CHANNEL_ID = "ForegroundServiceChannel";
private MediaPlayer mediaPlayer;
@Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.your_audio_file);
mediaPlayer.setLooping(true);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotificationChannel();
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText("Your audio is playing")
.setSmallIcon(R.drawable.ic_notification)
.build();
startForeground(1, notification);
mediaPlayer.start();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
mediaPlayer.release();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
最后,在你的 Activity 类中,你可以使用以下代码来启动 Service 类:
Intent serviceIntent = new Intent(this, MyService.class);
startService(serviceIntent);
这样,当你的应用程序进入后台时,通知音频将继续播放,并且当通知被移除时,音频也会停止播放。