当从最近的应用程序中刷过应用程序时,前台服务将被杀死,通知将被删除

问题描述 投票:7回答:1

我有一个带有通知的foreground-service。当应用程序从最近的应用程序托盘中滑走时,服务将被终止,通知也将被删除。这是我的服务VoiceService.class的代码:

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

        showNotification();
        Toast.makeText(this, "Service Started!", Toast.LENGTH_SHORT).show();


    return START_STICKY;
}
private void showNotification() {
    new SetupTask(this).execute(); // a method in my code which works fine.
    Intent notificationIntent = new Intent(this, MainActivity.class);
    notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
            | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            notificationIntent, 0);



    Notification notification = new NotificationCompat.Builder(this)
            .setContentTitle("TutorialsFace Music Player")
            .setContentText("My song")
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentIntent(pendingIntent)
            .setOngoing(true)
            .build();
    startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE, notification);

}
 @Override
public void onDestroy() {
    super.onDestroy();
}

    @Override
public void onTaskRemoved(Intent rootIntent) {
}

我正在使用小米设备。我还在设置中启用了自动启动。我也尝试将以下代码添加到onTaskRemoved()

    Intent intent = new Intent(getApplicationContext(), VoiceService.class);
    PendingIntent pendingIntent = PendingIntent.getService(this, 1, intent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime() + 1000, pendingIntent);
    super.onTaskRemoved(rootIntent);

这些解决方案均无用。我的onStartCommand()有问题吗?

android android-service foreground-service
1个回答
0
投票

您的前台服务的通知,即您通过startForeground显示的通知,将在服务关闭后立即消失。

startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE, notification);

根据您要执行的操作,您可以随时使用其他通知渠道显示通知。如果您的服务关闭,此通知将不会消失。用户可以将其滑走,因为它不是前台服务通知,而是普通通知。

© www.soinside.com 2019 - 2024. All rights reserved.