IT박스

Android에서 포 그라운드 서비스의 알림 텍스트를 어떻게 업데이트합니까?

itboxs 2020. 7. 12. 10:23
반응형

Android에서 포 그라운드 서비스의 알림 텍스트를 어떻게 업데이트합니까?


Android에서 포 그라운드 서비스 설정이 있습니다. 알림 텍스트를 업데이트하고 싶습니다. 아래와 같이 서비스를 만들고 있습니다.

이 포 그라운드 서비스 내에 설정된 알림 텍스트를 어떻게 업데이트합니까? 알림을 업데이트하는 가장 좋은 방법은 무엇입니까? 모든 샘플 코드를 주시면 감사하겠습니다.

public class NotificationService extends Service {

    private static final int ONGOING_NOTIFICATION = 1;

    private Notification notification;

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

        this.notification = new Notification(R.drawable.statusbar, getText(R.string.app_name), System.currentTimeMillis());
        Intent notificationIntent = new Intent(this, AbList.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        this.notification.setLatestEventInfo(this, getText(R.string.app_name), "Update This Text", pendingIntent);

        startForeground(ONGOING_NOTIFICATION, this.notification);

    }

아래와 같이 주요 활동에서 서비스를 만들고 있습니다.

    // Start Notification Service
    Intent serviceIntent = new Intent(this, NotificationService.class);
    startService(serviceIntent);

이 시나리오를 시도하지는 않았지만 startForeground()동일한 고유 ID와 Notification새 정보를 사용하여 다시 호출하면 효과가 있다고 생각합니다 .

업데이트 : 설명에 따라 NotifcationManager를 사용하여 알림을 업데이트해야하며 서비스는 계속 포 그라운드 모드로 유지됩니다. 아래 답변을보십시오.


startForeground ()로 설정된 알림을 업데이트하려면 새 알림을 작성한 다음 NotificationManager를 사용하여 알림을 보내십시오.

핵심은 동일한 알림 ID를 사용하는 것입니다.

알림을 업데이트하기 위해 startForeground ()를 반복적으로 호출하는 시나리오를 테스트하지는 않았지만 NotificationManager.notify를 사용하는 것이 더 좋을 것이라고 생각합니다.

알림을 업데이트해도 포 그라운드 상태에서 서비스가 제거되지는 않습니다 (stopForground 호출로만 수행 할 수 있음).

예:

private static final int NOTIF_ID=1;

@Override
public void onCreate (){
    this.startForeground();
}

private void startForeground() {
    startForeground(NOTIF_ID, getMyActivityNotification(""));
}

private Notification getMyActivityNotification(String text){
    // The PendingIntent to launch our activity if the user selects
    // this notification
    CharSequence title = getText(R.string.title_activity);
    PendingIntent contentIntent = PendingIntent.getActivity(this,
            0, new Intent(this, MyActivity.class), 0);

    return new Notification.Builder(this)
            .setContentTitle(title)
            .setContentText(text)
            .setSmallIcon(R.drawable.ic_launcher_b3)
            .setContentIntent(contentIntent).getNotification();     
}

/**
 * This is the method that can be called to update the Notification
 */
private void updateNotification() {
    String text = "Some text that will update the notification";

    Notification notification = getMyActivityNotification(text);

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(NOTIF_ID, notification);
}

문서의 상태

To set up a notification so it can be updated, issue it with a notification ID by calling NotificationManager.notify(). To update this notification after you've issued it, update or create a NotificationCompat.Builder object, build a Notification object from it, and issue the Notification with the same ID you used previously. If the previous notification is still visible, the system updates it from the contents of the Notification object. If the previous notification has been dismissed, a new notification is created instead.


Improving on Luca Manzo answer in android 8.0+ when updating the notification it will make sound and show as Heads-up.
to prevent that you need to add setOnlyAlertOnce(true)

so the code is:

private static final int NOTIF_ID=1;

@Override
public void onCreate(){
        this.startForeground();
}

private void startForeground(){
        startForeground(NOTIF_ID,getMyActivityNotification(""));
}

private Notification getMyActivityNotification(String text){
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
        ((NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(
        NotificationChannel("timer_notification","Timer Notification",NotificationManager.IMPORTANCE_HIGH))
}

        // The PendingIntent to launch our activity if the user selects
        // this notification
        PendingIntent contentIntent=PendingIntent.getActivity(this,
        0,new Intent(this,MyActivity.class),0);

        return new NotificationCompat.Builder(this,"my_channel_01")
        .setContentTitle("some title")
        .setContentText(text)
        .setOnlyAlertOnce(true) // so when data is updated don't make sound and alert in android 8.0+
        .setOngoing(true)
        .setSmallIcon(R.drawable.ic_launcher_b3)
        .setContentIntent(contentIntent)
        .build();
}

/**
 * This is the method that can be called to update the Notification
 */
private void updateNotification(){
        String text="Some text that will update the notification";

        Notification notification=getMyActivityNotification(text);

        NotificationManager mNotificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(NOTIF_ID,notification);
}

here's the code to do so in your service. Create a new notification, but ask notification manager to notify the same notification id you used in startForeground.

Notification notify = createNotification();
final NotificationManager notificationManager = (NotificationManager) getApplicationContext()
    .getSystemService(getApplicationContext().NOTIFICATION_SERVICE);

notificationManager.notify(ONGOING_NOTIFICATION, notify);

for full sample codes, you can check here:

https://github.com/plateaukao/AutoScreenOnOff/blob/master/src/com/danielkao/autoscreenonoff/SensorMonitorService.java

참고URL : https://stackoverflow.com/questions/5528288/how-do-i-update-the-notification-text-for-a-foreground-service-in-android

반응형