Android O 오류 해결 Context.startForegroundService()가 Service.startForeground 에 전화 하지 않 았 습 니 다.

8387 단어 Android
원인 분석 Android 8.0 은 다음 과 같은 조정 이 있 습 니 다.Android 8.0 의 응용 시 도 는 배경 서 비 스 를 만 들 수 없 는 상황 에서 startService()함 수 를 사용 하면 이 함수 가 IllegalState Exception 을 일 으 킬 것 입 니 다.
새로운 Context.startForegroundService()함수 가 프론트 서 비 스 를 시작 합 니 다.현재 배경 에서 실행 되 더 라 도 시스템 은 Context.startForegroundService()를 호출 할 수 있 습 니 다.서 비 스 를 만 든 후 5 초 안에 이 서비스의 startForeground()함 수 를 호출 해 야 합 니 다.app 코드:
Intent intent = new Intent(this, TestService.class);
intent.putExtra("type",1);
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
     startForegroundService(intent);
 } else {
     startService(intent);
 }

TestService 코드
   private NotificationManager notificationManager;
    private static final String NOTIFICATION_ID = "channedId";
    private static final String NOTIFICATION_NAME = "channedId";
    @Override
    public void onCreate() {
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //  NotificationChannel
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            NotificationChannel channel = new NotificationChannel(NOTIFICATION_ID, NOTIFICATION_NAME, NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
        }
        startForeground(1,getNotification());       
    }
      @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    private Notification getNotification() {
        Notification.Builder builder = new Notification.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentTitle("    ")
                .setContentText("     ");
        //  Notification ChannelID,        
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId(NOTIFICATION_ID);
        }
        Notification notification = builder.build();
        return notification;
    }

좋은 웹페이지 즐겨찾기