我们知道,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