android通知栏内添加快捷键_一个带按钮的自定义Android通知栏DEMO

本文介绍了如何在Android中创建一个带有按钮的自定义通知栏。通过使用Notification类、NotificationManager、RemoteViews和PendingIntent,可以构建一个包含按钮的自定义布局,并实现按钮点击事件以及点击通知进入应用的逻辑。最后,通过NotificationManager显示通知并注册BroadcastReceiver来处理按钮事件。
摘要由CSDN通过智能技术生成

我们知道,Android开发可使用Notification类和NotificationManager类,方便的构建系统通知栏消息,下面简单说一个带按钮的自定义通知栏的实现方法。

构建RemoteViews,R.layout.notification即自定义通知栏的布局文件;

RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification);

remoteViews.setTextViewText(R.id.tv_up, "首都机场精品无线");

remoteViews.setTextViewText(R.id.tv_down, "已免费接入");

自定义按钮点击事件处理,常见的示例为各种音乐播放器的通知栏快捷键(播放/暂停、上一首、下一首)等;

Intent intent = new Intent(ACTION_BTN);

intent.putExtra(INTENT_NAME, INTENT_BTN_LOGIN);

PendingIntent intentpi = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);

remoteViews.setOnClickPendingIntent(R.id.btn_login, intentpi);

一般通知栏还有点击进入程序页面的功能,可以按照下述方法实现:

Intent intent2 = new Intent();

intent2.setClass(this, MainActivity.class);

intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

PendingIntent intentContent = PendingIntent.getActivity(this, 0, intent2, PendingIntent.FLAG_UPDATE_CURRENT);

构建NotificationCompat.Builder,设置通知栏相关属性;

NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

builder.setOngoing(false);

builder.setAutoCancel(false);

builder.setContent(remoteViews);

builder.setTicker("正在使用首都机场无线");

builder.setSmallIcon(R.drawable.id_airport); //需注意这个属性如果不设置,在某些机型上通知栏将不会显示

Notification notification = builder.build();

notification.defaults = Notification.DEFAULT_SOUND;

notification.flags = Notification.FLAG_NO_CLEAR;

notification.contentIntent = intentContent;

构建NotificationManager,显示通知栏;

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

notificationManager.notify(0, notification);

至此,一个简单的带按钮自定义通知栏就差不多完成了,再注册实现一个BroadcastReceiver用于按钮事件的响应即可。

源码:源码

原文:http://blog.csdn.net/wxdjaqgs/article/details/44561101

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值