如何在服务启动时显示通知

时间:2018-03-15 23:35:11

标签: android

我需要一个关于如何在服务启动时显示通知的简单示例。 我在我的Activity中有这个方法,但我想在onStartCommand中使用这个方法:

public void stardNotification() {
       NotificationCompat.Builder mBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this);
       mBuilder.setSmallIcon(R.mipmap.ic_launcher);
       mBuilder.setContentTitle("Title");
       mBuilder.setContentText("Some text");
       NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
       notificationManager.notify(0, mBuilder.build());
   }

1 个答案:

答案 0 :(得分:0)

使用按钮尝试此操作。

      b1.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
        String tittle="Noti Title";
        String body="Notif Body";

        NotificationManager notif=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notify=new Notification.Builder
           (getApplicationContext()).setContentTitle(tittle).setContentText(body).setSmallIcon(R.drawable.abc).build();

           notify.flags |= Notification.FLAG_AUTO_CANCEL;
           notif.notify(0, notify);
     }
  });
相关问题