Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

把 App 圖示放進狀態欄:Notification 常駐圖示與動態換圖示實作解析

編輯:Android 開發實例

一、起念

研究「類似 360、QQ 管家那樣的懸浮窗」時我突發奇想:能不能把應用圖示也釘在狀態欄上,像手機 QQ 那樣,有新訊息時還順手換一張圖示?動手之後才發現原理相當單純。

二、把圖示送進狀態欄

核心就是 NotificationManager 加上一個 Notification 物件:

NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification n = new Notification(
        resId, "Floats Start!", System.currentTimeMillis());

// 將此通知放到通知欄的「Ongoing」即「正在運行」組中
n.flags |= Notification.FLAG_ONGOING_EVENT;
// 點擊「清除通知」後仍不刪除,常與 FLAG_ONGOING_EVENT 搭配使用
n.flags |= Notification.FLAG_NO_CLEAR;

PendingIntent pi = PendingIntent.getActivity(this, 0, getIntent(), 0);
n.contentIntent = pi;
n.setLatestEventInfo(this, "FloatsWindow", "start!", pi);
nm.notify(NOTIFICATION_ID_ICON, n);

FLAG_ONGOING_EVENT 讓通知掛在「進行中」的分組,FLAG_NO_CLEAR 則讓它不受清除鍵影響,兩者搭配就能達到近似常駐的效果。

三、更換圖示:不必先取消通知

關鍵在於「不需要 cancel 這個通知」,只要用同一個 NOTIFICATION_ID 再 notify 一次、並換上不同的 resId,圖示就會替換掉。

四、完整程式碼

package com.chris.floats.window;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.WindowManager;

public class MainActivity extends Activity {
    private static WindowManager mWindowMgr = null;
    private WindowManager.LayoutParams mWindowMgrParams = null;
    private static FloatsWindowView mFloatsWindowView = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onStop() {
        super.onStop();
        deleteIconToStatusbar();
    }

    /*
     * 顯示應用主界面時,移除懸浮層並切換狀態欄圖示
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (hasFocus) {
            if (mFloatsWindowView != null) {
                mWindowMgr.removeView(mFloatsWindowView);
                mFloatsWindowView = null;
            }
            addIconToStatusbar(R.drawable.a0);
        } else {
            getWindowLayout();
            addIconToStatusbar(R.drawable.ic_launcher);
        }
    }

    private void initParams() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        mWindowMgrParams.x = dm.widthPixels - 136;
        mWindowMgrParams.y = 300;
        mWindowMgrParams.width = 136;
        mWindowMgrParams.height = 136;
    }

    private void getWindowLayout() {
        if (mFloatsWindowView == null) {
            mWindowMgr = (WindowManager) getBaseContext()
                    .getSystemService(Context.WINDOW_SERVICE);
            mWindowMgrParams = new WindowManager.LayoutParams();

            // 2003:懸浮於所有界面之上
            // (4.0+ 位於下拉菜單之下,2.3 中則在上拉菜單之上)
            mWindowMgrParams.type = 2003;
            mWindowMgrParams.format = 1;

            // 40 = 預設屬性 32 + FLAG_NOT_FOCUSABLE 8
            mWindowMgrParams.flags = 40;
            mWindowMgrParams.gravity = Gravity.LEFT | Gravity.TOP;
            initParams();

            mFloatsWindowView = new FloatsWindowView(this);
            mWindowMgr.addView(mFloatsWindowView, mWindowMgrParams);
        }
    }

    private final static int NOTIFICATION_ID_ICON = 0x10000;

    /*
     * 若不先從狀態欄移除 ICON 就再次呼叫此方法,畫面不會有任何變化;
     * 唯一例外是把 resId 換成不同圖示,此時圖示會被替換。
     */
    private void addIconToStatusbar(int resId) {
        NotificationManager nm = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);
        Notification n = new Notification(
                resId, "Floats Start!", System.currentTimeMillis());

        n.flags |= Notification.FLAG_ONGOING_EVENT;
        n.flags |= Notification.FLAG_NO_CLEAR;

        PendingIntent pi = PendingIntent.getActivity(this, 0, getIntent(), 0);
        n.contentIntent = pi;
        n.setLatestEventInfo(this, "FloatsWindow", "start!", pi);
        nm.notify(NOTIFICATION_ID_ICON, n);
    }

    private void deleteIconToStatusbar() {
        NotificationManager nm = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);
        nm.cancel(NOTIFICATION_ID_ICON);
    }
}

程式的行為是:當應用視窗獲得焦點時切換成一個圖示,失去焦點時切換成另一個,離開時則把通知移除。

原始碼下載:https://download.csdn.net/detail/qingye_love/5506825

五、給今天的開發者一點提醒

這套寫法屬於早期 Android 的通知模型。從 API 11 起 setLatestEventInfo() 已被標記為廢棄,取而代之的是 Notification.Builder(以及後續的 NotificationChannel 機制)。此外,自 Android 8.0 起,常駐通知必須綁定通知渠道,而 SYSTEM_ALERT_WINDOW 這類懸浮視窗權限也需要引導使用者手動授予。若你在維護老專案,理解上述原理仍有價值;若是新專案,建議直接採用 NotificationCompat.Builder 搭配前台服務(foreground service)來實現「常駐圖示」的需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved