Notification不起作用

今天在学习安卓Notification的时候,按照书上的代码写了一个简单的案例,但是由于没有书上的图片资源,所以注掉.setSmallIcon(R.drawable.abc)这一行代码

NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    Intent intent = new Intent(MainActivity.this,SecondeActivity.class);
    PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);
    Notification notification =new Notification.Builder(this)
        //.setSmallIcon(R.drawable.abc)
        .setAutoCancel(true)
        .setTicker("有新消息")
        .setWhen(System.currentTimeMillis())
        .setContentTitle("新消息来啦").setContentText("gggggg    ").setContentIntent(pi).
                build();
nm.notify(0x222,notification);

结果通知栏部分没有通知出现。

后来一个一个尝试后发现必须要有setSmallIcon(),哪怕仅仅只有setSmallIcon()都可以显示通知。通过查看NotificationManager.notify()代码发现在方法里面有判断过otification.getSmallIcon() == null,如果getSmallIcon为Null 会抛异常。

public void notifyAsUser(String tag, int id, Notification notification, UserHandle user)
    {
        int[] idOut = new int[1];
        INotificationManager service = getService();
        String pkg = mContext.getPackageName();
        // Fix the notification as best we can.
        Notification.addFieldsFromContext(mContext, notification);
        if (notification.sound != null) {
            notification.sound = notification.sound.getCanonicalUri();
            if (StrictMode.vmFileUriExposureEnabled()) {
                notification.sound.checkFileUriExposed("Notification.sound");
            }
        }
        fixLegacySmallIcon(notification, pkg);
        if (mContext.getApplicationInfo().targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
        //如果没有setSmallIcon ,此处会抛异常
            if (notification.getSmallIcon() == null) {
                throw new IllegalArgumentException("Invalid notification (no valid small icon): "
                        + notification);
            }
        }
        if (localLOGV) Log.v(TAG, pkg + ": notify(" + id + ", " + notification + ")");
        final Notification copy = Builder.maybeCloneStrippedForDelivery(notification);
        try {
            service.enqueueNotificationWithTag(pkg, mContext.getOpPackageName(), tag, id,
                    copy, idOut, user.getIdentifier());
            if (id != idOut[0]) {
                Log.w(TAG, "notify: id corrupted: sent " + id + ", got back " + idOut[0]);
            }
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    }
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值