2016年2月3日 星期三

Android 的本地通知經驗

繼續 Android 的學習。本來在 Fragment 內顯示 AlertDialog,但搞了很久也無法正常顯示,基於結構上的考量,把顯示的部份搬到上層 Activity 看來更好。現時的結構是 Activity 包著 Fragment 再包著目前的 Fragment。那麼要怎樣通知兩層上的 Activity?我選擇了用本地通知(LocalBroadcastManager)。但明明在程式其他地方用過,執行得好好地的代碼,搬到 Fragment 內用不了?搞了兩小時,才發現原來沒有第三個參數的 send() 有一個臭蟲,會跳過執行而沒有反應:
//
//  LocalNotification.java
//  AMIGOController
//
//  Created by Pacess on 02/04/2016.
//  Copyright (c) 2016 Pacess Studio. All rights reserved.
//

//--------------------------------------------------------------------------------------------------
//  0    1         2         3         4         5         6         7         8         9
//  567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890

package com.pacess.amigocontroller.utilities;

//--------------------------------------------------------------------------------------------------
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;

//==================================================================================================
public final class LocalNotification  {

    //  Defines
    public static final String CONFIRM_LOGOUT = "com.pacess.amigocontroller.confirmLogout";
    public static final String CONFIRM_RESET_PASSWORD = "com.pacess.amigocontroller.confirmResetPassword";
    public static final String ERROR_RESPONSE_FORMAT = "com.pacess.amigocontroller.errorResponseFormat";
    public static final String ERROR_STATUS = "com.pacess.amigocontroller.errorStatus";
    public static final String FORGOTPASSWORD_DONE = "com.pacess.amigocontroller.forgotPasswordDone";
    public static final String LANGUAGE_CHANGED = "com.pacess.amigocontroller.languageChanged";
    public static final String LOGIN_DONE = "com.pacess.amigocontroller.loginDone";
    public static final String SIGNUP_DONE = "com.pacess.amigocontroller.signUpDone";
    public static final String STARTAPP_DONE = "com.pacess.amigocontroller.startAppDone";
    public static final String UPDATE_HEADER = "com.pacess.amigocontroller.updateHeader";

    //--------------------------------------------------------------------------------------------------
    //  Static functions
    //--------------------------------------------------------------------------------------------------
    public static void send(Context context, String action)  {
        send(context, action, null);
    }

    //--------------------------------------------------------------------------------------------------
    public static void send(Context context, String action, Bundle data)  {
        if (data == null)  {return;}

        Intent intent = new Intent();
        intent.setAction(action);
        intent.putExtras(data);
        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
    }
}

沒有留言: