通知和自定义通知布局"/>
Android中的通知和自定义通知布局
Android中的通知(Notification)是Android中的重要一部分,应用程序通过通知来提醒用户或者向用户传达信息,下面让我们来看一下怎么在我们的程序中使用通知和自定义通知的布局。
首先我们来看一下怎么向通知栏中发送一个通知。由于各个版本的Android在通知方面都有一些改动,所以很难找到一个标准的创建及使用通知的方法,但是程序设计出来总归是给用户使用的,那么我们可以采用兼容性最好的那个API来创建通知:我们可以使用NotificationCompat 这个类来进行通知的创建及设置属性,具体步骤如下:
1、获取系统的通知管理服务,通过:
(NotificationManager)getSystemService(
Context.NOTIFICATION_SERVICE)
方法来获取,注意要强制转换类型。
2、创建我们需要的通知并且设置对应属性:
Notification notification = new NotificationCompat.Builder(this).setContentTitle("通知1") // 创建通知的标题.setContentText("这是第一个通知") // 创建通知的内容.setSmallIcon(R.drawable.small_icon) // 创建通知的小图标 .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher)) // 创建通知的大图标/** 首先,无论是使用自定义视图还是系统提供的视图,上面4的属性一定要设置,不然这个通知显示不出来*/
3、调用通知管理服务的notify方法发送通知
我们依然通过一个例子来看一下:
新建一个Android工程:
activity_main.xml:
<LinearLayout xmlns:android=""xmlns:tools=""android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity" ><Button
android:id="@+id/button1NotifyNotification"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="发送第一种通知" /><Button android:id="@+id/button2NotifyNotification"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="发送第二种通知"/></LinearLayout>
布局中的两个按钮分别用来发送系统布局的通知和我们自定义布局的通知,接下来是我们自定义的通知布局,新建一个布局文件notification.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""android:id="@+id/notificationLayout"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#FFFFAADD"android:orientation="horizontal" ><ImageView android:id="@+id/notificationImageView"android:layout_width="wrap_content"android:layout_height=
更多推荐
Android中的通知和自定义通知布局
发布评论