Android 服务中显示Notification失败。

来源:互联网 发布:大闸蟹品牌 知乎 编辑:程序博客网 时间:2024/05/17 08:37

源码如下:

无论显示Notification的代码放在服务的哪里都显示不出来。

public class MyForegroundService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(getApplicationContext()).setTicker("显示于屏幕顶端状态栏的文字").setSmallIcon(R.mipmap.ic_launcher);
        Notification notification = builder.setContentTitle("这是Title").setContentText("这是文档").build();
        notificationManager.notify(10, notification);

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
//        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//        Notification.Builder builder = new Notification.Builder(getApplicationContext()).setTicker("显示于屏幕顶端状态栏的文字").setSmallIcon(R.mipmap.ic_launcher);
//        Notification notification = builder.setContentTitle("这是Title").setContentText("这是文档").build();
//        notificationManager.notify(10, notification);
        return START_STICKY;
    }

但是放在Activity中显示出来了。所以怀疑是service配置问题。

将服务配置改为

        <service
            android:name=".MyForegroundService"
            android:enabled="true">
        </service>

显示出来了。

 

0 0
原创粉丝点击