1. 程式人生 > >自定義通知欄,並註冊點選事件

自定義通知欄,並註冊點選事件

描述

如題

效果圖

這裡寫圖片描述

程式碼

/**
 * function: 自定義通知欄
 * Created by wiky on 2016/6/27.
 */
public class MyNotification {
    private static final String TAG = "ProgressNotification";
    public final static String INTENT_BUTTONID_TAG = "ButtonId";
    /**
     * 通知欄按鈕點選事件對應的ACTION(標識廣播)
     */
    public final static
String ACTION_BUTTON = "com.notification.intent.action.ButtonClick"; /** * 標識按鈕狀態:是否在播放 */ public boolean isPlay = false; /** * 通知欄按鈕廣播 */ public ButtonBroadcastReceiver receiver; /** * 播放/暫停 按鈕點選 ID */ public final static int BUTTON_PALY_ID = 1; private
final int NOTIFICATION_ID = 0xa01; private final int REQUEST_CODE = 0xb01; private Context context; private NotificationManager notificationManager; private RemoteViews contentView; private Notification notification; public MyNotification(Context context) { this.context = context; } /** * 初始化通知欄資訊,並顯示 * * @param
appName 下載的應用圖示 * @param networkSpeed 網速 * @param currentSize 當前下載進度(包大小) * @param totalSize 總的包大小 */
public void initAndNotify(String appName, String networkSpeed, String currentSize, String totalSize) { notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context); // 此處設定的圖示僅用於顯示新提醒時候出現在裝置的通知欄 mBuilder.setSmallIcon(R.mipmap.ic_launcher); notification = mBuilder.build(); // 當用戶下來通知欄時候看到的就是RemoteViews中自定義的Notification佈局 contentView = new RemoteViews(context.getPackageName(), R.layout.progress_bar_layout); //設定通知欄資訊 contentView.setTextViewText(R.id.txt_appName, appName);//應用名稱 contentView.setTextViewText(R.id.txt_network_speed, networkSpeed + "kb/s");//當前網速 StringBuffer stringBuffer = new StringBuffer(currentSize); stringBuffer.append("/"); stringBuffer.append(totalSize); stringBuffer.append("M"); contentView.setTextViewText(R.id.txt_size_progress, stringBuffer.toString());//當前下載進度 //如果版本號低於(3.0),那麼不顯示按鈕 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { contentView.setViewVisibility(R.id.btn_download, View.GONE); } else { //註冊廣播 receiver = new ButtonBroadcastReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ACTION_BUTTON); context.registerReceiver(receiver, intentFilter); //設定按鈕 contentView.setImageViewResource(R.id.btn_download, R.drawable.btn_notification_play); //設定點選的事件 Intent buttonIntent = new Intent(ACTION_BUTTON); buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_PALY_ID); PendingIntent intent_paly = PendingIntent.getBroadcast(context, BUTTON_PALY_ID, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT); contentView.setOnClickPendingIntent(R.id.btn_download, intent_paly); } notification.contentView = contentView; // 點選notification自動消失 notification.flags = Notification.FLAG_AUTO_CANCEL; // 需要注意的是,作為選項,此處可以設定MainActivity的啟動模式為singleTop,避免重複新建onCreate()。 Intent intent = new Intent(context, MainActivity.class); // 當用戶點選通知欄的Notification時候,切換回TaskDefineActivity。 PendingIntent pi = PendingIntent.getActivity(context, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT); notification.contentIntent = pi; // 傳送到手機的通知欄 notificationManager.notify(NOTIFICATION_ID, notification); } /** * (通知欄中的點選事件是通過廣播來通知的,所以在需要處理點選事件的地方註冊廣播即可) * 廣播監聽按鈕點選事件 */ public class ButtonBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(ACTION_BUTTON)) { //通過傳遞過來的ID判斷按鈕點選屬性或者通過getResultCode()獲得相應點選事件 int buttonId = intent.getIntExtra(INTENT_BUTTONID_TAG, 0); switch (buttonId) { case BUTTON_PALY_ID: Log.d(TAG, "點選播放/暫停按鈕"); onDownLoadBtnClick(); break; default: break; } } } } private void onDownLoadBtnClick() { if (isPlay) { //當前是進行中,則暫停 isPlay = false; contentView.setImageViewResource(R.id.btn_download, R.drawable.btn_notification_pause); }else { //當前暫停,則開始 isPlay = true; contentView.setImageViewResource(R.id.btn_download, R.drawable.btn_notification_play); } notificationManager.notify(NOTIFICATION_ID, notification); } /** * 關閉通知 */ public void cancel() { if (receiver != null) { context.unregisterReceiver(receiver); } if (notificationManager != null) { notificationManager.cancel(NOTIFICATION_ID); } } }

佈局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00000000"
    android:orientation="horizontal"
    android:padding="5dp">


    <ImageView
        android:id="@+id/iv_appIcon"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_margin="4dp"
        android:background="@mipmap/ic_launcher"/>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="4dp"
        android:layout_marginStart="4dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/txt_appName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="16sp"
            />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/txt_network_speed"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="12sp"
                />

            <TextView
                android:id="@+id/txt_size_progress"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="8dp"
                android:layout_marginStart="4dp"
                android:textSize="12sp"
                />
        </LinearLayout>

    </LinearLayout>

    <ImageView
        android:id="@+id/btn_download"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_margin="4dp"
       />
</LinearLayout>