Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 狀態列圖示實作:常駐通知與依情境切換圖示

編輯:關於 Android 程式設計

很多常駐型的小工具都會在狀態列(通知列)留一個圖示,一方面讓使用者知道程式還在跑,另一方面也方便隨時點回來。研究一輪之後會發現,真正的核心其實只有幾行程式碼。

一、把圖示掛到狀態列上

Android 的狀態列圖示,本質上就是「通知」(Notification)。透過 NotificationManager 發出一則通知,系統就會在狀態列畫上指定的圖示;而搭配特定的旗標,還能讓它變成使用者無法隨意滑掉、也不會被「清除通知」清掉的常駐項目。

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);

幾個關鍵點值得留意:


resId 決定狀態列上要畫哪一張圖;System.currentTimeMillis() 只是通知的時間戳;FLAG_ONGOING_EVENT 讓通知歸類在「進行中」;FLAG_NO_CLEAR 讓它不受清除動作影響;最後 nm.notify() 的 ID 是這則通知的身分證,同一個 ID 重複送出,系統會視為「更新」而不是新增。

二、讓狀態列圖示跟着情境改變

不需要先 cancel() 再重新發通知。只要沿用同一個通知 ID,換一個 resId 再呼叫一次 notify(),狀態列上的圖就會直接替換掉——這正是同一 ID 代表「更新」的紅利。

下面是一個完整的示範:主介面取得焦點時收起懸浮層、圖示換成 A 案;失去焦點時把懸浮層叫回來、圖示換成常駐樣式;離開畫面時則把通知移除。

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;

    private final static int NOTIFICATION_ID_ICON = 0x10000;

    @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;

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

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

    /*
     * 若不先把舊通知移除,反覆呼叫 addIconToStatusbar 畫面不會有任何變化;
     * 唯一的例外是:把 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);
    }
}

以上就是全部程式碼。當應用程式的視窗焦點改變時,狀態列上的圖片也會跟著變化。

三、給新版系統的補充提醒

上面這套寫法屬於早期 Android 的通知 API,用來理解「同一 ID 即更新」的機制非常直觀,但在新版本上會遇到兩件事:


其一,Notification 的這個建構子與 setLatestEventInfo() 都已不建議使用,實作時請改用 NotificationCompat.Builder,標題與內容透過 setContentTitle()、setContentText() 設定,並記得指定小圖示。

其二,從 Android 8.0 開始,通知必須先建立通知渠道(Notification Channel)才有辦法顯示;若只是需要一個「服務還活着」的常駐圖示,更合適的做法是改用前景服務(Foreground Service)搭配常駐通知,並在服務真正結束時呼叫 stopForeground() 收尾,避免圖示變成使用者關不掉的幽靈。

另外,懸浮層使用的 type = 2003 在新系統上也不再通用,需要改採 TYPE_APPLICATION_OVERLAY 並向使用者申請「顯示在其他應用程式上層」的權限。

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