美文网首页Android资源收录android系统控件Android
Android 之 Notification 必须掌握知识点

Android 之 Notification 必须掌握知识点

作者: code小生 | 来源:发表于2017-04-10 07:32 被阅读518次

    本文同步我的 CSDN 博客
    转载请注明出处
    http://blog.csdn.net/wufeng55/article/details/69791139

    创建并发送一个系统通知

    activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.mu_16jj.notificationdemo.MainActivity">
        <TextView
            android:id="@+id/tv_send_notification"
            android:layout_width="wrap_content"
            android:layout_height="35dp"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:background="@color/colorAccent"
            android:text="send notification"
            android:textSize="16sp" />
    </RelativeLayout>
    

    很简单的布局,就一个 TextView 利用其点击事件来发送通知。

    创建 Notification

    private void createNotification() {
            notification = new NotificationCompat.Builder(MainActivity.this)
                    .setContentTitle("Notification title")
                    .setTicker("Ticker method function...")
                    .setContentText("Notification content text")
                    .setSubText("subtext...")
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.mipmap.ic_launcher_round)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.large_icon))
                    .build();
        }
    

    通过 NotificationCompat.Build 来构建一个 Notification 对象,并设置一系列属性(每个属性对应的效果后面展示)。

    发送按钮监听

    notificationManager.notify(1, notification);
    

    这里需要说明的是,Notification 的发送还是由 NotificationManager 来管理的,第一个参数用来标识一个唯一的 Notification;第二个参数就是需要发送的 Notification 对象。我们在 onCreate 方法中通过以下代码初始化了通知管理器对象:

    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    

    运行效果

    技术公众号.jpg

    相关文章

      网友评论

      • 胆子哥:问下,后台推送过来的消息,跟这个通知有啥区别,没太懂这个通知有啥用途
        code小生: @郭胆子 这个属于学习,可以用于自己做下载的时候的通知,或者其他地方
      • yuyu000:写的很好 谢谢
        code小生: @yuyu000 这个头像很熟悉😁
      • Xdjm:创建的方式和okhttp,retrofit创建对象的方式一模子一样
        code小生: @C春和景明C 哈哈,链式调用,比较喜欢

      本文标题:Android 之 Notification 必须掌握知识点

      本文链接:https://www.haomeiwen.com/subject/wbnrattx.html