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

描述

如題

效果圖

這裏寫圖片描述

代碼

/**
 * 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>
發佈了42 篇原創文章 · 獲贊 90 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章