Notification的功能与使用案例

本文介绍了一个简单的Android应用如何实现发送和取消通知的功能。通过代码示例详细展示了如何使用Notification.Builder构造通知,包括设置通知图标、标题、内容等属性,并演示了如何通过PendingIntent在点击通知时启动指定的Activity。

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

Notification的主要方法的使用和解释见代码:

public class NotificationActivity extends Activity implements View.OnClickListener{
    private Button send,cancel;
    private NotificationManager nm;
    //  定义一个Notification的标识ID
    private final int NOTIFICATION_ID = 0x111;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notification);
        send = (Button) findViewById(R.id.send);
        cancel = (Button) findViewById(R.id.cancel);
        //  获得通知管理器,用于后面发送通知
        nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        send.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }
    public void send(){
        Intent intent = new Intent(NotificationActivity.this,SearchViewActivity.class);
        PendingIntent pi = PendingIntent.getActivity(NotificationActivity.this,0,intent,0);
        Notification notify = new Notification.Builder(NotificationActivity.this)
                //  设置通知点击后自动消失
                .setAutoCancel(true)
                //  设置通知状态栏提示信息
                .setTicker("新消息")
                //  设置通知的图标
                .setSmallIcon(R.mipmap.ic_launcher)
                //  设置通知内容的标题
                .setContentTitle("一条新的通知")
                //  设置通知的内容
                .setContentText("恭喜你被BAT争相聘用!!")
                //  设置通知来时的提示声音
                .setDefaults(Notification.DEFAULT_SOUND)
                //  设置点击通知要启动的程序
                .setContentIntent(pi)
                //  创建此Notification
                .build();
                //  发送通知
                nm.notify(NOTIFICATION_ID,notify);
    }

    public void cancel(){
        nm.cancel(NOTIFICATION_ID);
    }
    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.send:
                send();
                break;
            case R.id.cancel:
                cancel();
                break;
        }
    }
}
界面布局就两个Button,一个用于发送通知,一个取消通知


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值