How to show notification from background service?

前端 未结 2 1984
野趣味
野趣味 2020-12-30 09:31

The project I am working on has two different apps, 1 is server and other is client. Server app has 1 service class, which initiates server thread in onStartCommand()<

2条回答
  •  鱼传尺愫
    2020-12-30 10:07

    First you need to read this article on how to use Notifications.

    Next use this to send a Notification, you can write this code in the service class at the point where you receive some data from the client.

    NotificationManager notificationManager =
        (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    int icon = R.drawable.notification_icon;
    CharSequence notiText = "Your notification from the service";
    long meow = System.currentTimeMillis();
    
    Notification notification = new Notification(icon, notiText, meow);
    
    Context context = getApplicationContext();
    CharSequence contentTitle = "Your notification";
    CharSequence contentText = "Some data has arrived!";
    Intent notificationIntent = new Intent(this, YourActivityThatYouWantToLaunch.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    
    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    
    int SERVER_DATA_RECEIVED = 1;
    notificationManager.notify(SERVER_DATA_RECEIVED, notification);
    

提交回复
热议问题