Android创建通知栏Notification(使用新API)

安卓创建Notification(通知栏)通知,网上搜出来的API都比较陈旧,在IDE中提示过期,虽然也能实现功能吧,但是我们得跟上时代对不?
目前来说,新的未过时,兼容性好的API使用代码:

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context)
                        .setSmallIcon(R.mipmap.ic_luncher)
                        .setContentTitle("标题")
                        .setContentText("内容");
        // Creates an explicit intent for an Activity in your app
        Intent resultIntent = new Intent(context, SplashActivity.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 application to the Home screen.
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        // Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(SplashActivity.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) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = mBuilder.build();
        // 通知来时震动或者响铃
        // notification.sound
        // notification.vibrate
        //使用系统默认声音用下面这条
        notification.defaults = Notification.DEFAULT_SOUND;
        // 点击以后消失
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        // mId allows you to update the notification later on.
        mNotificationManager.notify(0, notification);

使用tips:导包时,选择v4包。如果设置成通知来时震动,记得声明震动的权限啊……

<uses-permission android:name="android.permission.VIBRATE" />

彩蛋:通知栏的更多玩法(显示进度,自定义布局等),请访问安卓开发的官网,查看官方api文档,嗯,它是中文的……

安卓开发官网

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值