一個帶按鈕的自訂Android通知欄DEMO,androiddemo
我們知道,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用於按鈕事件的響應即可。
源碼:源碼