到目前为止,我已经调整了我的代码ContextCompat.startForegroundService(context, intentService);
来启动我的服务.这样,它适用于android <26和android 26(Oreo).
我仍然看到一个区别,在android oreo我没有看到我的自定义前景通知(我只看到"应用程序在后台运行"通知).我还需要调整任何东西吗?
我的服务如下:
public class BaseOverlayService extends Service {
@Override
public void onCreate() {
super.onCreate();
moveToForeground();
}
private void moveToForeground() {
Notification notification = ...;
super.startForeground(NOTIFICATION_ID, notification);
}
}
Run Code Online (Sandbox Code Playgroud)
官方的例子
此示例(https://github.com/googlesamples/android-play-location/blob/master/LocationUpdatesForegroundService/app/src/main/java/com/google/android/gms/location/sample/locationupdatesforegroundservice/LocationUpdatesService.java #L200)显示为评论,我应该使用以下,但startServiceInForeground
不存在......
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O) {
NotificationManager mNotificationManager = ((NotificationManager) getSystemService(NOTIFICATION_SERVICE));
mNotificationManager.startServiceInForeground(new Intent(this, BaseOverlayService.class), NOTIFICATION_ID, notification);
} else {
startForeground(NOTIFICATION_ID, notification);
}
Run Code Online (Sandbox Code Playgroud)
编辑
我的通知是这样创建的,它正在使用API <26的数千个Android设备上工作到现在为止:
protected Notification foregroundNotification(int notificationId)
{
boolean paused = MainApp.getPrefs().sidebarServicePaused();
NotificationCompat.Builder builder = new NotificationCompat.Builder(this); …
Run Code Online (Sandbox Code Playgroud) android android-notifications foreground-service android-8.0-oreo
我在我的 Activity 的 onResume 上启动了一项服务,它在 oreo 上运行良好,但最近我看到 Android P 崩溃,上面写着“无法恢复 Activity.... 不允许启动服务意图......应用程序在后台。 .”。有没有人以前见过这个并且可以应用修复,任何输入都将不胜感激。
@Override
public void onResume() {
super.onResume();
Timber.v("onResume");
Intent intent = new Intent(context, Token.class);
intent.setAction(ACTION_FETCH_TOKEN);
context.startService(intent);
}
Run Code Online (Sandbox Code Playgroud)
只是为了添加更多上下文,我自己无法重现崩溃。