Android中的通知和自定义通知布局

本文介绍了如何在Android应用中创建和使用通知,包括通过NotificationCompat创建标准通知以及自定义通知布局。通过示例展示了如何处理自定义布局中的按钮事件,使用BroadcastReceiver响应PendingIntent。
摘要由CSDN通过智能技术生成

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="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=".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="http://schemas.android.com/apk/res/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=
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值