【问题标题】:Running application in background with progress notification在后台运行应用程序并通知进度
【发布时间】:2020-06-17 23:54:23
【问题描述】:
我正在通过 web 视图使用 asyncTask 进行下载过程,这样下载过程将一直进行,直到应用程序关闭。同样,当用户打开应用程序时,下载过程继续进行。我尝试在 backgroundService 中运行它,并在应用程序停止后启动该服务。问题是服务正在启动,但是当我关闭应用程序时,服务停止。我也尝试在服务运行时显示通知,但是当我关闭应用程序时,服务将被终止。我提到了这个post。请建议我一些可以解决我问题的方法,并且应该从 Android lollipop 到最新版本都可以使用。
【问题讨论】:
标签:
android
android-asynctask
androidx
【解决方案1】:
我建议前台服务是答案
就像在链接中一样,只是附加了一个通知渠道
首先检查如何启动服务:
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" />