我正在尝试为Android编写音乐播放器,并使用前景服务来运行音乐播放器。我正在将UI控件从UI控件发送到服务以播放歌曲。收到意图后,立即调用OnstartCommand和Ondestroy。我不确定如何停止通话。
我尝试将未决意图更改为starterVice/contextCompat.startforegroundservice,但问题仍然存在。
服务:
import android.app.Service;
public class PlayerService extends Service{
private TransportControls transportControls;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (mediaSessionManager == null) {
initMediaSession();
}
handleIntent(intent);
return START_STICKY;
}
private initMediaSession(){
...
transportControls = mediaSession.getController().getTransportControls();
mediaSession.setCallback(new MediaSessionCompat.Callback() {
// Implement callbacks
@Override
public void onPlay() {
play();
}
...
}
handleIntent(Intent intent){
// Initial checks
if(/* action in intent is play*/) transportControls.play();
}
private void play(SongInfo songInfo){
...
buildNotificaiton(//play action);
}
private void buildNotification(){
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
this, "default").setContentIntent(intent)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setStyle(new MediaStyle()
.setMediaSession(mediaSession.getSessionToken())
.setShowActionsInCompactView(0, 1, 2))
.setContentText(StringUtils.parseArtists(songInfo.artists()))
.setContentTitle(songInfo.displayName())
.setContentInfo(songInfo.album())
.setSound(null);
NotificationManager notificationManager = (NotificationManager) getSystemService(
Context.NOTIFICATION_SERVICE);
if (notificationManager == null) {
return;
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("default",
"Bhatki media notification",
NotificationManager.IMPORTANCE_HIGH);
channel.setDescription(
"Notification displayed when music is being played. This notification is "
+ "required for the music to play.");
notificationManager.createNotificationChannel(channel);
}
// Execution is reaching this line.
startForeground(NOTIFICATION_ID, notificationBuilder.build());
}
}
活动:
Intent intent = new Intent();
intent.setClass(context, PlayerService.class);
intent.setAction(action);
intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
// one approach
ContextCompat.startForegroundService(context, intent);
// Different approach
// PendingIntent pendingIntent = PendingIntent
// .getService(serviceContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// try {
// pendingIntent.send(serviceContext, 0, intent);
// } catch (CanceledException e) {
// Log.d(TAG, "sendIntent: failed");
我还补充说,清单中的Android前景服务权限:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
我希望通知和服务能够持续。无法弄清楚为什么要称呼ondestroy。
Once the service has been created, the service must call its startForeground() method within five seconds.
针对Android 9(API级别28(或更高和使用前景服务的应用程序必须请求FOREGROUND_SERVICE
许可
前景服务
编辑:我无法从您的代码中分辨出问题,但是根据我的经验,通知块应在override fun onCreate()