Android笔记(二十八)通知的使用

本文将介绍如何在Android应用中通过点击按钮发送通知,包括创建布局、设置NotificationManager实例、创建Notification对象并调用notify()方法的完整过程。
一、通知的用法

当某个应用程序希望向用户发出一些提示信息,而该应用程序又不在前台运行时,就可以借助通知来实现。相比于广播接收器和服务,在活动里创建通知的场景还是比较少的,因为一般只有当程序进入到后台的时候我们才需要使用通知。

  1. 获得NotificationManager 的实例
  2. 创建一个 Notification 对象
  3. 设定通知的布局
  4. 调用 NotificationManager 的 notify()方法
二、具体实例——通过点击按钮来发出一条通知
  1. 建立布局
<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"
    android:orientation="vertical" >

    <Button
        android:id="@+id/send_notice"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send notice" />

</LinearLayout>
  1. MainActivity
public class MainActivity extends ActionBarActivity {

    private Button button;
    private NotificationManager manager;
    private Notification.Builder builder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.send_notice);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                builder = new Notification.Builder(MainActivity.this);
                Intent intent = new Intent(MainActivity.this,
                        MainActivity.class);
                PendingIntent contentIntent = PendingIntent.getActivity(
                        MainActivity.this, 0, intent, 0);
                builder.setContentIntent(contentIntent);
                builder.setTicker("这是一个通知");
                builder.setContentTitle("通知");
                builder.setContentText("hello");
                builder.setDefaults(Notification.DEFAULT_ALL);
                builder.setSmallIcon(R.drawable.ic_launcher);
                Notification notification = builder.build();
                manager.notify(1, notification);
            }
        });
    }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值