一個帶按鈕的自訂Android通知欄DEMO,androiddemo

來源:互聯網
上載者:User

一個帶按鈕的自訂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用於按鈕事件的響應即可。

源碼:源碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.