gunamkwon / TIL

Today I Learned
0 stars 0 forks source link

Android_TIL_211005 #2

Open gunamkwon opened 3 years ago

gunamkwon commented 3 years ago

Foreground Service

1. Foreground Service?

=> noticeable 할 필요가 없으면 background task 사용하는 것이 나음

[ Notification이 즉시 나타나는 경우 ]
  1. Notification이 Action Button을 포함하는 경우
  2. foregroundServiceTypemediaPlayback, mediaProjection,phoneCall인 경우 혹은 그에 관련된 경우
  3. setForegroundServiceBehavior()FOREGROUND_SERVICE_IMMEDIATE를 준다.

2. Foreground Service 시작하기

[1] AndroidManifest.xml 설정

<manifest xmlns:android="http://schemas.android.com/apk/res/android">

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

    <application ...>
        ...
    </application>
</manifest>

<mainfest> 태그 사이에 <uses-permission>을 통해 Foreground Service를 사용할 수 있게 한다.

[2] MainActivity에서 Intent 생성

        Intent intent = new Intent(getApplicationContext(), MyService.class);

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            getApplicationContext().startForegroundService(intent);
        } else {
            getApplicationContext().startService(intent);
        }

SDK 26(Android O)이상의 버전 이상에서는 서비스가 Background에서 실행되지 않기 때문에 startForegroundService()를 이용해야한다.

[3] Notification 생성

public class MyService extends Service {
    private final int NOTIFICATION_ID = 10;
    private final String CHANNEL_ID = "primary_notification_channel";

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("MyService","MyService is started");

        Log.d("MyService","startForeground");

        startForegroundService();
    }

    void startForegroundService() {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification_service);

        NotificationCompat.Builder builder;
        if(Build.VERSION.SDK_INT >= 26) {
            String CHANNEL_ID = "Test_service_channel";
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                    "Test Service Channel",
                    NotificationManager.IMPORTANCE_DEFAULT);

            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
                    .createNotificationChannel(channel);

            builder = new NotificationCompat.Builder(this, CHANNEL_ID);
        } else {
            builder = new NotificationCompat.Builder(this);
        }

        builder.setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Foreground Service")
                .setContentText("Foreground Service")
                .setContentIntent(pendingIntent);

        startForeground(1, builder.build());
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

다음과 같이 Service안에 Notification을 생성 해야한다.

[4] Service 종료

                Intent intent = new Intent(getApplicationContext(), MyService.class);
                Log.d("MyService","Stopped");
                getApplicationContext().stopService(intent);

다음과 같은 코드를 MainActivity에서 실행해야 한다.

결과

image