我正在尝试为Android编写音乐播放器,并正在使用前台服务来运行音乐播放器。我正在从UI控件向该服务发送未决的Intent以播放歌曲。 收到该意图后,将立即调用onStartCommand和onDestroy。我不确定如何停止onDestroy通话。
我尝试将挂起的意图更改为startService / ContextCompat.startForegroundService,但问题仍然存在。
服务:
new Function("return value1")()
活动中:
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());
}
}
我还在清单中添加了android前台服务权限:
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");
我希望通知和服务能够继续存在。无法弄清为什么调用OnDestroy。
答案 0 :(得分:0)
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()