在Android 9版本中,移动设备上的流媒体音频问题可能是由于应用程序在后台运行时被系统限制了音频播放造成的。
以下是一个解决方法的示例代码,可以帮助解决这个问题:
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
public class AudioService extends Service {
private MediaPlayer mediaPlayer;
@Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.audio_file);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// 创建通知渠道
String channelId = "Audio_Channel";
String channelName = "Audio Channel";
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
// 创建通知
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, channelId)
.setContentTitle("Audio Service")
.setContentText("Playing audio")
.setSmallIcon(R.drawable.ic_audio)
.setContentIntent(pendingIntent)
.build();
// 将服务设置为前台服务
startForeground(1, notification);
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mediaPlayer.start();
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
mediaPlayer.stop();
mediaPlayer.release();
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
private Intent audioServiceIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audioServiceIntent = new Intent(this, AudioService.class);
startService(audioServiceIntent);
}
@Override
protected void onDestroy() {
stopService(audioServiceIntent);
super.onDestroy();
}
}
通过使用前台服务,应用程序将在后台播放音频时保持活动状态,并且不会被系统限制音频播放。