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 aNotificationCompat.Builder
object, build aNotification
object from it, and issue theNotification
with the same ID you used previously. If the previous notification is still visible, the system updates it from the contents of theNotification
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:
'IT박스' 카테고리의 다른 글
부모 디렉토리 위치를 얻는 방법 (0) | 2020.07.12 |
---|---|
날짜 시간을 하루 씩 늘리는 방법은 무엇입니까? (0) | 2020.07.12 |
HTML 테이블에서 테두리를 완전히 제거하는 방법 (0) | 2020.07.12 |
C # HttpClient 4.5 멀티 파트 / 양식 데이터 업로드 (0) | 2020.07.12 |
vuejs 2 vuex에서 상점 값을 보는 방법 (0) | 2020.07.12 |