Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何避免android.app.RemoteServiceException-Context.startForegroundService()然后没有调用Service.startForeground()_Java_Android_Oncreate_Android Gps - Fatal编程技术网

Java 如何避免android.app.RemoteServiceException-Context.startForegroundService()然后没有调用Service.startForeground()

Java 如何避免android.app.RemoteServiceException-Context.startForegroundService()然后没有调用Service.startForeground(),java,android,oncreate,android-gps,Java,Android,Oncreate,Android Gps,尽管事实上我正在给startForeground打电话,但我仍然看到很多这样的事故发生在野外 作为参考,我的代码如下: 在我的应用程序的主要活动onCreate中,我做的最后一件事是: Intent i = new Intent(c, myGpsService.class); if (Build.VERSION.SDK_INT >= 26) c.startForegroundService(i); else c.startService(i); 然后在MyGPS服务中:

尽管事实上我正在给startForeground打电话,但我仍然看到很多这样的事故发生在野外

作为参考,我的代码如下:

在我的应用程序的主要活动onCreate中,我做的最后一件事是:

Intent i = new Intent(c, myGpsService.class);
if (Build.VERSION.SDK_INT >= 26)
    c.startForegroundService(i);
else
    c.startService(i);
然后在MyGPS服务中:

@Override
public void onCreate() {
    super.onCreate();
    startInForeground();
}

private void startInForeground() {
    if (Build.VERSION.SDK_INT >= 26) {
        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel nc = new NotificationChannel(...);
        nc.enableLights(false);
        nc.enableVibration(false);
        if (nm != null)
            nm.createNotificationChannel(nc);
        Notification n = new Notification.Builder(this, nc.getId())
                .setContentText(...)
                .setContentTitle(...))
                .setSmallIcon(...)
                .build();
        this.startForeground(NOTIFICATION_ID, n);
    }
}
当我在我的Android上运行它时,它运行良好,服务启动,等等。对于我的大多数用户来说,它运行良好。但是我从用户那里收到了很多android.app.RemoteServiceException报告——每天几十份

startForegroundService和startForeground之间的最大ANR间隔为5秒,我认为这就是问题的原因(以及为什么它是间歇性的),但我无法确定在应用程序活动中的onCreate和服务中的onCreate之间会发生什么。是否可能在某些设备上创建通知的速度较慢?有什么技巧/建议可以最大限度地缩短这里的时间?我是否应该在创建之后再呼叫StartForegroundsService