在后台运行应用程序并显示进度通知

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

我正在通过aviewTask通过网络视图执行下载过程,因此下载过程将一直进行到应用程序关闭为止。再次,当用户打开应用程序时,下载过程将继续。我尝试在backgroundService中运行它,并在应用停止后启动了该服务。问题是服务正在启动,但是当我关闭应用程序时,服务停止。我还尝试在服务运行时显示通知,但是当我关闭应用程序时,服务将被终止。我提到了这个post。请向我提出一些可以解决我问题的方法,并且应该可以从Android棒棒糖开始一直运行到最新。

android android-asynctask androidx
1个回答
0
投票

我建议前台服务是答案就像在链接中只是一个通知通道一样]

所以首先检查如何使用以下方法启动服务:

    Intent intent = new Intent(this@MainActivity, YourService::class.java);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) 
        startForegroundService(intent);
    else 
        startService(intent);

然后在设置通知之前,从服务创建通知通道:

     private NotificationManager createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = NotificationChannel(
                CHANNEL_ID, "NAME", NotificationManager.IMPORTANCE_DEFAULT
            );
            NotificationManager manager = getSystemService(NotificationManager::class.java);
            manager.createNotificationChannel(serviceChannel);
            return manager;
        }
        return null;
    }

最后一次通话之后:

Notification notification = mBuilder.build();
startForeground(1, notification);

现在,只要您的应用处于启用状态,通知就应该仍然有效

如果不起作用,请在此清单中写入您的注册服务

<service
     android:name=".YourService"
     android:stopWithTask="true" />
© www.soinside.com 2019 - 2024. All rights reserved.