android 服务中未显示通知

android notification not showing from service

我有这项服务可以连接到服务器并获取通知 但不幸的是它没有显示任何通知 这是服务 class :

public class NotificationService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    public void startNotificationListener()
    {
      //start's a new thread
    new Thread(new Runnable() {
        @Override
        public void run() {
          //fetching notifications from server
         //if there is notifications then call this method
        ShowNotification();
        }
    }).start();
    @Override
    public void onCreate()
    {
        startNotificationListener();
        super.onCreate();
    }
    @Override
    public int onStartCommand(Intent intent,int flags,int startId)
    {
        return super.onStartCommand(intent,flags,startId);
    }
    @Override
    public void onDestroy()
    {
        super.onDestroy();
    }
    public void ShowNotification()
    {
      NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
            Notification notification = new NotificationCompat.Builder(getBaseContext(),"notification_id")
                    .setSmallIcon(R.drawable.icon)
                    .setContentTitle("title")
                    .setContentText("content")
                    .setDefaults(NotificationCompat.DEFAULT_SOUND)
                    .build();
            notificationManager.notify(0, notification);
       //the notification is not showing

    }
}

调用 ShowNotification 时通知没有显示,我试过将 ShowNotification 的代码粘贴到主要 activity 的 oncreate 中,就像那样

@Override
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
          NotificationManager notificationManager =
                (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
        Notification notification = new NotificationCompat.Builder(getBaseContext(),"n")
                .setSmallIcon(R.drawable.icon)
                .setContentTitle("Title")
                .setContentText("Content Text"))
                .setDefaults(NotificationCompat.DEFAULT_SOUND)
                .build();
        notificationManager.notify(0, notification);
    }

而且有效。

我是否总是需要从 activity 创建通知? 如果没有,如何从服务创建通知?

P.S: the service will run even if the app is not running

是的,您可以根据您的代码从 service.but 创建通知 startNotificationListener() 的右括号在下面的代码后丢失

new Thread(new Runnable() { @Override public void run() { //fetching notifications from server //if there is notifications then call this method ShowNotification(); } }).start();

并且您必须在 </application> 之前在 AndroidManifest.Xml 文件中注册服务。

<service android:name=".NotificationService"/>

之后,您必须按照以下方式从您的 activity 开始服务。

startService(new Intent(this,NotificationService.class));

有您的服务代码:

public class NotificationService extends Service {

public void startNotificationListener() {
    //start's a new thread
    new Thread(new Runnable() {
        @Override
        public void run() {
            //fetching notifications from server
            //if there is notifications then call this method
            ShowNotification();
        }
    }).start();
}
@Override
public void onCreate()
{
    startNotificationListener();
    super.onCreate();
}
@Override
public int onStartCommand(Intent intent,int flags,int startId)
{
    return super.onStartCommand(intent,flags,startId);
}
@Override
public void onDestroy()
{
    super.onDestroy();
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

public void ShowNotification()
{
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
    Notification notification = new NotificationCompat.Builder(getBaseContext(),"notification_id")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("title")
            .setContentText("content")
            .setDefaults(NotificationCompat.DEFAULT_SOUND)
            .build();
    notificationManager.notify(0, notification);
    //the notification is not showing

}

}

您将获得 notification.please 检查屏幕截图

尝试使用通知渠道...可能就是问题所在。

Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel or it will not appear.

https://developer.android.com/guide/topics/ui/notifiers/notifications.html#ManageChannels

        // The id of the channel.
        String CHANNEL_ID = "my_channel_01";
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(MainActivity.this).setChannel(CHANNEL_ID)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("My notification")
                        .setContentText("Hello World!");
        // Creates an explicit intent for an Activity in your app
        Intent resultIntent = new Intent(this, MainActivity.class);

        // The stack builder object will contain an artificial back stack for the
        // started Activity.
        // This ensures that navigating backward from the Activity leads out of
        // your app to the Home screen.
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        // Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(MainActivity.class);
        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // mNotificationId is a unique integer your app uses to identify the
        // notification. For example, to cancel the notification, you can pass its ID
        // number to NotificationManager.cancel().
        mNotificationManager.notify(0, mBuilder.build());

https://github.com/fida1989/NotificationDemo