0

应用程序的目标是 27,我正在 android oreo 8.0 设备上进行测试。

compileSdkVersion 27
targetSdkVersion 27

当用户点击下载按钮时,app 会启动前台 Intent 服务并通过通知通知用户。在onCreateof 中IntentService,app 也履行了调用该startForeground(int id, Notification notification)方法的承诺。所以,

//On click of download button
ContextCompat.startForegroundService(context, intent);

//Within the onCreate() of IntentService()
startForeground(id, notification);

如果应用程序在前台,一切正常。但是当用户刷出并因此杀死应用程序时;我重新开始下载,它可以工作,下载开始;但 android 系统会显示一条通知 - “<#appname#> is running in background”。所以用户现在可以看到两个通知

  • 我的应用程序中的一个显示下载进度和
  • 另一个来自 android 系统,显示我的应用程序正在后台运行。

这样好吗?如何避免来自android系统的通知?

以下是我管理刷出应用程序终止的方法:

@Override
public void onTaskRemoved(Intent rootIntent) {


    Context localContext = getApplicationContext();
    Intent restartServiceIntent = new Intent(localContext,
            HandlePendingDownload.class);
    restartServiceIntent.putExtra(DMConstants.ACTION_SWIPE_OUT, Boolean.TRUE);
    restartServiceIntent.setPackage(getPackageName());
    PendingIntent restartServicePendingIntent = PendingIntent.getBroadcast(
            localContext, 1, restartServiceIntent,
            PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) localContext
            .getSystemService(Context.ALARM_SERVICE);
    if (FWCompat.isKitKat_19_OrNewer()) {
        alarmService.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + 1900,
                restartServicePendingIntent);
    } else {
        alarmService.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + 1900,
                restartServicePendingIntent);
    }
    super.onTaskRemoved(rootIntent);
}

然后稍后在onReceive()我调用:

ContextCompat.startForegroundService(context, downloadIntent);

总而言之, 一旦应用程序被杀死,如何避免从 android 系统显示应用程序在后台运行的通知?因为我已经向用户显示下载通知,所以用户知道这一点。

还有一个问题,有什么办法可以得到意图onCreate()IntentService?我需要获取下载内容的 id,它作为额外参数传入 Intent。因为基于此,我可以在其中显示通知onCreate()

到目前为止,我正在显示一个“开始下载”通知,然后onStartCommand()我清除该通知并根据内容 ID 创建一个新通知。

4

1 回答 1

0

来自 Android 文档

前台 前台服务执行一些用户可以注意到的操作。例如,音频应用程序将使用前台服务来播放音轨。前台服务必须显示通知。即使用户没有与应用程序交互,前台服务也会继续运行。

https://developer.android.com/guide/components/services.html

如果通知未正确启动,则服务将被终止。也许您正在寻找不同类型的服务。也许看看绑定服务?

绑定 当应用程序组件通过调用 bindService() 绑定到服务时,服务被绑定。绑定服务提供客户端-服务器接口,允许组件与服务交互、发送请求、接收结果,甚至通过进程间通信 (IPC) 跨进程执行此操作。绑定服务仅在另一个应用程序组件绑定到它时运行。多个组件可以一次绑定到服务,但是当所有组件都解除绑定时,服务将被销毁。

于 2018-03-14T20:38:26.890 回答