ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Android Oreo 백그라운드 서비스 제한 이전 개발
    안드로이드 2018. 9. 20. 14:29

    Oreo에서 백그라운드 서비스에 크게 제한이 걸리면서 해당 부분을 대응해야 할 필요성이 생겼습니다.


    서포트 라이브러리의 JobIntentService가 오레오와 비 오레오를 캐치해서 처리해 주기에,

    JobIntentService를 이용해 처리하는 것도 연동을 시도해 보았습니다.


    하지만 일단 JobIntentService는 루프를 돌며 지속적으로 서치하는 쪽에는 어울리지도 않고,

    무엇보다 어플리케이션이 DEAD 상태가 되면 죽어 버리더라고요.


    차라리 포그라운드 상태로 전환하는 쪽으로 판단해서 해당방식으로 진행했습니다.


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationChannel notificationChannel = new NotificationChannel("channel_id", "서비스 알람", NotificationManager.IMPORTANCE_DEFAULT);
    notificationChannel.setDescription("포그라운드 서비스에서 보내는 알람입니다.");
    notificationChannel.enableLights(true);
    notificationChannel.setLightColor(Color.GREEN);
    notificationChannel.enableVibration(true);
    notificationChannel.setVibrationPattern(new long[]{100, 200, 100, 200});
    notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
    if (notificationManager != null) {
    notificationManager.createNotificationChannel(notificationChannel);
    }
    }


    오레오에선 노티피케이션 채널이 필수이므로 어딘가에 위 코드를 등록합니다.

    어플리케이션에 하든지, 최초 액티비티의 온크리에이트에서 하든지요.



    Intent i = new Intent(this, MyService.class);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    getApplicationContext().startForegroundService(i);
    }



    포그라운드 서비스의 경우 onStartCommand 메소드 초반에 알람을 등록하지 않으면 앱이 종료됩니다. 해당 부분을 수정합니다.


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    Notification.Builder builder = new Notification.Builder(this, "channel_id")
    .setContentTitle(getString(R.string.app_name))
    .setContentText("SmartTracker Running")
    .setAutoCancel(true);
    Notification notification = builder.build();
    startForeground(100, notification);
    } else {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
    .setContentTitle(getString(R.string.app_name))
    .setContentText("SmartTracker is Running...")
    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
    .setAutoCancel(true);
    Notification notification = builder.build();
    startForeground(100, notification);
    }

    ...이후 코드..



    startForeground(100, notification);

    여기의 id값이 0이면 포그라운드 서비스가 정상 동작하지 않으므로 주의합니다.

    이렇게 하면 간단히 포그라운드 서비스로 변형할 순 있지만...

    백그라운드 서비스에 비해 UI도 다르고.

    일단 앱 상단에 항상 알람이 뜬다는 것 자체가 큰 단점입니다.


    해당 부분은 적절한 커스터마이징과 UI 재설계가 필수적일 것으로 보입니다.

Designed by Tistory.