android o android8.0 startforegroundservice startforegroundservice did not then call

时间:2025-01-25 15:28:42

解决() did not then call ()

原因:

  1. Android 8.0 系统不允许后台应用创建后台服务,故只能使用()启动服务
  2. 创建服务后,应用必须在5秒内调用该服务的 startForeground() 显示一条可见通知,声明有服务在挂着,不然系统会停止服务 + ANR 套餐送上。
  3. Notification 要加 Channel,系统的要求。

 

解决步骤:

 

    @Override
    public void onCreate() {
        ();
        if (.SDK_INT>=Build.VERSION_CODES.O) {
            startFG();
        }
    }

    private void startFG() {
        NotificationBuilder builder = new NotificationBuilder(this);
        final Notification notification = ();
        startForeground(NotificationBuilder.NOTIFICATION_ID, notification);
    }
 
public final class NotificationBuilder {
    public static final String NOTIFICATION_CHANNEL_ID = ".CHANNEL_ID";
    public static final int NOTIFICATION_ID = 0xD660;

    private final Context mContext;
    private final NotificationManager mNotificationManager;

    public NotificationBuilder(Context context) {
        mContext = context;
        mNotificationManager = (NotificationManager) (Context.NOTIFICATION_SERVICE);
    }

    public Notification buildNotification() {
        if (shouldCreateNowPlayingChannel()) {
            createNowPlayingChannel();
        }

         builder = new (mContext, NOTIFICATION_CHANNEL_ID);

        return (.all_app_takeaway_icon)
                .setContentTitle("")
                .setContentTitle("")
                .setOnlyAlertOnce(true)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .build();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private boolean nowPlayingChannelExists() {
        return (NOTIFICATION_CHANNEL_ID) != null;
    }

    private boolean shouldCreateNowPlayingChannel() {
        return .SDK_INT >= Build.VERSION_CODES.O && !nowPlayingChannelExists();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createNowPlayingChannel() {
        final NotificationChannel channel = new NotificationChannel(
                NOTIFICATION_CHANNEL_ID,
                "当前播放",
                NotificationManager.IMPORTANCE_LOW);
        ("当前播放的电台");
        (channel);
    }
}

还要注意:

  中配置permission

<uses-permission android:name=".FOREGROUND_SERVICE" />

启动Service方法:

        //后台启动service
        if (.SDK_INT>=Build.VERSION_CODES.O) {
            Intent serviceIntent = new Intent(this, );
            startForegroundService(serviceIntent);
        } else {
            Intent serviceIntent = new Intent(this, );
            startService(serviceIntent);
        }