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文档,嗯,它是中文的……

安卓开发官网

发布了32 篇原创文章 · 获赞 39 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/zengd0/article/details/52300739