通知未显示 Android 7.0 但显示在 Android 6.0

Notification not showing Android 7.0 but showing in Android 6.0

我有一个显示通知的服务,该通知在 Android 6.0 和更早版本中有效,但在 7.0 中不显示。

相关代码:

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    PendingIntent pendingIntentMain = PendingIntent.getActivity(this, 0, intent_main, PendingIntent.FLAG_CANCEL_CURRENT);
    Notification notificationPopup = new Notification.Builder(this).setContentTitle("Alarm is ON!").setContentText("Click here")
            .setContentIntent(pendingIntentMain).setAutoCancel(true).setSmallIcon(R.drawable.acd).setPriority(Notification.PRIORITY_MAX)
            .setDefaults(Notification.DEFAULT_ALL).build();
    notificationManager.notify(0, notificationPopup);

请按照此步骤操作,让我知道它是否有效 从电池优化中删除 6ya:

1.Go 设置电池。

2.Click 电池页面上的菜单,然后选择电池优化。

3.Clicked 未优化并转到所有应用程序。

4.On所有应用程序找到6ya应用程序并点击它。

5.It 将显示优化和不优化的弹出窗口。

6.Click 不要优化并点击完成。

7.6ya 应该位于未优化的文件夹中。

8.All 设置 - 重启 phone.

恐怕我无法重现您遇到的问题。

在我的测试中,此代码在 Android 5.1、6.0、7.0 和 7.1.1 上成功创建并显示了通知:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

    }
}

MyService.java

public class MyService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        // create and display a notification
        Intent intent_main = new Intent(this, MainActivity.class);
        PendingIntent pendingIntentMain = PendingIntent.getActivity(this, 0, intent_main, PendingIntent.FLAG_CANCEL_CURRENT);
        Notification notificationPopup = new Notification.Builder(this)
                .setContentTitle("Alarm is ON!")
                .setContentText("Click here")
                .setContentIntent(pendingIntentMain)
                .setAutoCancel(true)
                .setSmallIcon(android.R.drawable.ic_lock_idle_alarm)
                .setPriority(Notification.PRIORITY_MAX)
                .setDefaults(Notification.DEFAULT_ALL)
                .build();

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(0, notificationPopup);

        return super.onStartCommand(intent, flags, startId);
    }
}