【Android 开发】:通知之 Status Bar Notifications

本文介绍了Android中状态栏通知的使用,包括其基本用法、代码实现和程序运行结果。通过示例展示了如何从Activity、Service和Broadcast触发通知,并提供自定义通知布局的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    在上一讲中,我们讲解了 Toast Notifications 通知的使用,这一讲我们来讲一下通知的另外一种使用方式:状态栏的通知的使用方式。在我们学习的四大组件当中,Activity, Service, Broadcast 都可以去触发一个通知。

1. Status Bar Notifications 介绍

   查看一下Notifications api文档,这一讲我们主要来学习一下 Status Bar Notifications 通知的使用
   状态栏通知会在手机的系统通知栏里面添加一个图标(或者可选的一条ticker-text(短暂的信息))。它用户选择了通知,系统会触发一个Notification定义(通常是在Activity中发出)的Intent来指定动作。你可以通过定义一个声音,震动或者设备的闪光灯来通知用户。
   状态栏的通知主要是用在后台的service中,它会提示用户对一个事件的到来进行响应。后台的服务不会去加载一个Activity来得到焦点从而获得用户的交互,它应该是以创建一个状态栏通知的形式让用户去选择从而进入相应Activity。这是比较一种友好的交互方式。
   【注意】:1. 状态栏通知允许通知用户事件,当不会打断当前Activity的运行
           2. 你可以在通知里面设置Intent,允许用户点击通知来触发进入某种动作。

2. 基本的使用方法

   1). Activity 和 Service 都能发布一个状态栏的通知,因为Activity都是在前端并且获取用户焦点的,通常的做法是在从Service创建状态栏通知,然后在Activity中显示通知。创建一个通知,必须使用到 Nofifaction 和 NotificationManager 。
     Notification 是用来创建通知,使用 Notification 的实例来定义状态栏通知的属性,比如状态栏通知图标,通知消息和一些额外的设置,如播放声音等。
     NotificationManager是用来管理通知. 它是Android的服务,所以会执行和管理所有状态栏的通知,你不需要直接实例化NotificationManager,可以通过getSystemService()方法来得到一个NotificationManager的引用,如果你想通知用户,调用Notification 的 notify()方法
   2). 状态栏通知需要一下几个设置
     1. 状态栏图标
     2. 状态栏标题和信息,除非是自定义的通知布局
     3. PendingIntent,是为了当用户选择通知时所触发的事件
   3). 查看 Notification 类,我们需要使用 Notification.Builder 来构造一个通知
   4). 【设置自定义布局】:使用自定义的通知必须使用 RemoteViews 来加载自定义的布局

3. 代码实现

1) 布局文件 activity_main.xml 主要是定义了两个Button,用来显示状态栏通知和显示状态栏自定义通知,这里就不贴出来了。

2) 自定义布局 custom_notification.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="10dp" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/image" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/title"
        android:layout_toRightOf="@id/image" />

</RelativeLayout>
3) 主程序文件 MainActivity.java

package com.android.notificationdemo;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RemoteViews;

public class MainActivity extends Activity {

    private Button button, button2;
    private NotificationManager manager;
    // 查看 NotificationCompat.Builder 类,这个类里面可以设置通知的一些属性,如图标,信息等。
    private Notification.Builder builder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initComponent();
        // 创建一个通知的引用
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        builder = new Notification.Builder(MainActivity.this);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 这个表示通知是在当前这个Activitiy来活动的。
                Intent intent = new Intent(MainActivity.this, MainActivity.class);
                /*
                 * PendingIntent.getActivity的参数依次为:Context,发送者的请求码(可以填0),
                 * 用于系统发送的Intent,标志位。
                 */
                PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, 0,
                        intent, 0);
                builder.setContentIntent(contentIntent);
                builder.setContentTitle("new notification");
                builder.setContentText("Hello AHuier!");
                builder.setSmallIcon(R.drawable.ic_launcher);

                /*
                 * builder.setDefaults(Notification.DEFAULT_ALL); setDefaluts
                 * 设置系统的默认的一些值,这些值在 Notification 类中 DEFAULT_ALL : 默认全部
                 * DEFAULT_LIGHTS : 默认的闪光灯 DEFAULT_SOUND : 默认的声音 DEFAULT_VIBRATE
                 * : 默认的震动 [注意]:要去调用默认震动,需要在AndroidManifest.xml文件中定义授权
                 * android:permission.VIBRATE.
                 */

                /*
                 * 获取SDcar卡的音乐作为铃声,提示用户可以自定义设置铃声 Uri uri =
                 * Uri.parse("file:///mnt/sdcard/xxx.mp3");
                 * builder.setSound(uri); 在低版本中要这样设置
                 * notification.defaults=Notification.DEFAULT_SOUND;
                 */
                // setTicker 第一次发布时候会短暂的显示提示内容。
                builder.setTicker("There is a Notification");
                Notification notification = builder.build(); // 仅仅限于在高版本4.1中使用
                // 1000是id号,表示通知的唯一标示符,后面会根据这个通知来进行更新
                manager.notify(1000, notification);
            }
        });
        button2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                RemoteViews contentViews = new RemoteViews(getPackageName(),
                        R.layout.custom_notification);
                contentViews.setImageViewResource(R.id.image, R.drawable.ic_launcher);
                contentViews.setTextViewText(R.id.title, "自定义通知的标题");
                contentViews.setTextViewText(R.id.text, "自定义通知的内容");

                Intent intent = new Intent(MainActivity.this, MainActivity.class);
                PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0,
                        intent, 0);
                builder.setContentIntent(pendingIntent);
                //加载指定的自定义布局
                builder.setContent(contentViews);
                Notification notification = builder.build();
                manager.notify(1001, notification);

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private void initComponent() {
        button = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
    }

}

4. 程序运行结果

           


【注意】以上程序运行环境最低在 Android Level 16以上,所以这里使用模拟器来实现以上功能。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值