Example usage for android.support.v4.content LocalBroadcastManager getInstance

List of usage examples for android.support.v4.content LocalBroadcastManager getInstance

Introduction

In this page you can find the example usage for android.support.v4.content LocalBroadcastManager getInstance.

Prototype

public static LocalBroadcastManager getInstance(Context context) 

Source Link

Usage

From source file:com.afrozaar.jazzfestreporting.MainActivity.java

@Override
protected void onPause() {
    super.onPause();
    if (broadcastReceiver != null) {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
    }//from  ww  w .  j av  a 2s .  c  om
    if (isFinishing()) {
        // mHandler.removeCallbacksAndMessages(null);
    }
}

From source file:ch.bfh.evoting.alljoyn.BusHandler.java

/**
 * Initialize AllJoyn//from w w w .java2s. c  om
 */
private void doInit() {
    PeerGroupListener pgListener = new PeerGroupListener() {

        @Override
        public void foundAdvertisedName(String groupName, short transport) {
            Intent i = new Intent("advertisedGroupChange");
            LocalBroadcastManager.getInstance(context).sendBroadcast(i);
        }

        @Override
        public void lostAdvertisedName(String groupName, short transport) {
            Intent i = new Intent("advertisedGroupChange");
            LocalBroadcastManager.getInstance(context).sendBroadcast(i);
        }

        @Override
        public void groupLost(String groupName) {
            if (mGroupManager.listHostedGroups().contains(groupName)
                    && mGroupManager.getNumPeers(groupName) == 1) {
                //signal was send because admin stays alone in the group
                //not necessary to manage this case for us
                Log.d(TAG, "Group destroyed event ignored");
                return;
            }
            Log.d(TAG, "Group " + groupName + " was destroyed.");
            Intent i = new Intent("groupDestroyed");
            i.putExtra("groupName", groupName);
            LocalBroadcastManager.getInstance(context).sendBroadcast(i);
        }

        @Override
        public void peerAdded(String busId, String groupName, int numParticipants) {
            Log.d(TAG, "peer added");

            if (amIAdmin) {
                Log.d(TAG, "Sending salt " + Base64.encodeToString(messageEncrypter.getSalt(), Base64.DEFAULT));
                Message msg = obtainMessage(BusHandler.PING);
                Bundle data = new Bundle();
                data.putString("groupName", lastJoinedNetwork);
                data.putString("pingString", Base64.encodeToString(messageEncrypter.getSalt(), Base64.DEFAULT));
                data.putBoolean("encrypted", false);
                data.putSerializable("type", Type.SALT);
                msg.setData(data);
                sendMessage(msg);
            }

            //update UI
            LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("participantStateUpdate"));

        }

        @Override
        public void peerRemoved(String peerId, String groupName, int numPeers) {
            //update UI
            Log.d(TAG, "peer left");
            Intent intent = new Intent("participantStateUpdate");
            intent.putExtra("action", "left");
            intent.putExtra("id", peerId);
            LocalBroadcastManager.getInstance(context).sendBroadcast(intent);

            super.peerRemoved(peerId, groupName, numPeers);
        }

    };

    ArrayList<BusObjectData> busObjects = new ArrayList<BusObjectData>();
    Handler mainHandler = new Handler(context.getMainLooper());

    Runnable myRunnable = new Runnable() {

        @Override
        public void run() {
            org.alljoyn.bus.alljoyn.DaemonInit.PrepareDaemon(context);
        }

    };
    mainHandler.post(myRunnable);

    busObjects.add(new BusObjectData(mSimpleService, "/SimpleService"));
    mGroupManager = new PeerGroupManager(SERVICE_NAME, pgListener, busObjects);
    mGroupManager.registerSignalHandlers(this);
}

From source file:ca.zadrox.dota2esportticker.service.UpdateTeamsService.java

private void updateSearchedTeams(String searchName) {

    LOGD(TAG, "starting search update");

    // actually, first, check for connectivity:
    if (!checkForConnectivity()) {
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_NO_CONNECTIVITY));
        LOGD(TAG, "returning due to no connectivity");
        return;//from w  w w.j  av a 2s .  c  om
    }

    LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_UPDATING));

    final String BASE_URL = "http://www.gosugamers.net/dota2/rankings" + "?tname="
            + searchName.replace(' ', '+') + "&tunranked=0#team";
    final String TEAM_LINK_BASE_URL = "http://www.gosugamers.net/dota2/teams/";

    try {

        String rawHtml = new OkHttpClient().newCall(new Request.Builder().url(BASE_URL).build()).execute()
                .body().string();

        String processedHtml = rawHtml.substring(rawHtml.indexOf("<div id=\"col1\" class=\"rows\">"),
                rawHtml.indexOf("<div id=\"col2\" class=\"rows\">"));

        Elements teamRows = Jsoup.parse(processedHtml).getElementsByClass("ranking-link");

        ExecutorService executorService = Executors.newFixedThreadPool(10);

        HashMap<ContentValues, Future<String>> newTeamInfo = new HashMap<ContentValues, Future<String>>();
        HashMap<ContentValues, Future<String>> updateTeamInfo = new HashMap<ContentValues, Future<String>>();

        for (Element teamRow : teamRows) {
            ContentValues contentValues = new ContentValues();

            String teamId = teamRow.attr("data-id");
            contentValues.put(MatchContract.TeamEntry._ID, teamId);

            String untrimmedTeamName = teamRow.getElementsByTag("h4").first().text();
            String teamUrl = TEAM_LINK_BASE_URL + teamId + "-"
                    + untrimmedTeamName.replaceAll("[\\W]?[\\W][\\W]*", "-").toLowerCase();
            contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_URL, teamUrl);

            String teamName = untrimmedTeamName.replaceAll(" ?\\.?\\-?-?Dot[aA][\\s]?2", "");
            contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_NAME, teamName);

            if (teamUrl.charAt(teamUrl.length() - 1) == '-') {
                teamUrl = teamUrl.substring(0, teamUrl.length() - 2);
            }

            // then, we query db for id of the team (
            Cursor cursor = getContentResolver().query(
                    MatchContract.TeamEntry.buildTeamUri(Long.parseLong(teamId)), new String[] {
                            MatchContract.TeamEntry.COLUMN_TEAM_NAME, MatchContract.TeamEntry.COLUMN_TEAM_URL },
                    null, null, null);

            // -> if present, and data remains unchanged, continue.
            // -> if present, but data is changed, add to update queue.
            if (cursor.moveToFirst()) {
                LOGD(TAG, "Team in DB, determining if values need updating");
                if (!cursor.getString(0).contentEquals(teamName)
                        || !cursor.getString(1).contentEquals(teamUrl)) {
                    LOGD(TAG, "Team has updated values, double checking logo & writing to DB");
                    updateTeamInfo.put(contentValues, executorService.submit(new TeamGetter(teamUrl)));
                }
            }
            // -> if not present, add to update queue.
            else {
                LOGD(TAG, "Team not in DB. Grabbing logo & writing to DB");
                newTeamInfo.put(contentValues, executorService.submit(new TeamGetter(teamUrl)));
            }

            //                LOGD(TAG, "\n" +
            //                        "data-id: " + teamId + "\n" +
            //                        "team-name: " + teamName + "\n" +
            //                        "team-url: " + teamUrl);
            //
            cursor.close();
        }

        executorService.shutdown();
        executorService.awaitTermination(20, TimeUnit.SECONDS);

        for (ContentValues contentValues : newTeamInfo.keySet()) {
            try {
                String teamLogo = newTeamInfo.get(contentValues).get();
                contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_LOGO_URL, teamLogo);

            } catch (ExecutionException e) {
                LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR));
                e.printStackTrace();
            }
        }

        for (ContentValues contentValues : updateTeamInfo.keySet()) {
            try {
                String teamLogo = newTeamInfo.get(contentValues).get();
                contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_LOGO_URL, teamLogo);

                String teamId = contentValues.getAsString(MatchContract.TeamEntry._ID);
                contentValues.remove(MatchContract.TeamEntry._ID);

                int updatedRows = getContentResolver().update(MatchContract.TeamEntry.CONTENT_URI,
                        contentValues,
                        MatchContract.TeamEntry.TABLE_NAME + "." + MatchContract.TeamEntry._ID + " = ?",
                        new String[] { teamId });

                LOGD(TAG, "updatedRows: " + updatedRows);

            } catch (ExecutionException e) {
                LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR));
                e.printStackTrace();
            }
        }

        getContentResolver().bulkInsert(MatchContract.TeamEntry.CONTENT_URI,
                newTeamInfo.keySet().toArray(new ContentValues[newTeamInfo.size()]));

    } catch (IOException e) {
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR));
        e.printStackTrace();
    } catch (InterruptedException e2) {
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR));
        e2.printStackTrace();
    }

    //        String[] projection = new String[]{
    //                MatchContract.TeamEntry.TABLE_NAME + "." + MatchContract.TeamEntry._ID,
    //                MatchContract.TeamEntry.COLUMN_TEAM_NAME,
    //                MatchContract.TeamEntry.COLUMN_TEAM_URL,
    //                MatchContract.TeamEntry.COLUMN_TEAM_LOGO_URL,
    //                MatchContract.TeamEntry.COLUMN_TEAM_STARRED,
    //        };
    //
    //        String sortOrder =
    //                MatchContract.TeamEntry.COLUMN_TEAM_NAME + " ASC";
    //
    //        Cursor c = getContentResolver().query(
    //                MatchContract.TeamEntry.CONTENT_URI,
    //                projection,
    //                MatchContract.TeamEntry.COLUMN_TEAM_NAME + " LIKE '%" + searchName + "%'",
    //                null,
    //                sortOrder
    //        );
    //
    //        LOGD(TAG+"/UST", "Starting Printout: ");
    //        int i = 0;
    //        while (c.moveToNext()) {
    //            String teamPrintOut =
    //                            "teamId: " + c.getInt(0) + " teamName: " + c.getString(1) + "\n" +
    //                            "teamUrl: " + c.getString(2) + "\n" +
    //                            "teamLogoUrl: " + c.getString(3) + "\n" +
    //                            "isFavourited: " + (c.getInt(4) == 0 ? "false" : "true");
    //            LOGD(TAG + "/UST", teamPrintOut);
    //            i++;
    //        }
    //        LOGD(TAG+"/UST", "Stopping Printout. Count: " + i);
    //
    //        c.close();

    // use local broadcast manager to hide loading indicator
    // and signal that cursorloader for top50 can happen.
    LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_COMPLETED));
}

From source file:co.ldln.android.sdk.LDLNSocketClient.java

@Override
public void onMessage(String s) {
    Log.d("Websocket", "Message from server! \"" + s + "\"");

    try {/*from w ww. j  av a 2s.  com*/
        JSONObject responseJsonObj = new JSONObject(s);
        String action_code = responseJsonObj.getString("action");
        Realm realm = Realm.getInstance(LDLN.getRealmConfig(mContext, LDLN.RealmLevel.GLOBAL));

        if (LDLNSocketResponseAction.SERVER_SEND_USERS.getActionKey().equals(action_code)) {
            Log.d("Websocket",
                    LDLNSocketResponseAction.SERVER_SEND_USERS.getActionKey() + " response recognized.");

            // Handle users response from the server, per the LDLN protocol.
            /*
               {
                   "action": "server_send_users",
                   "users": [
               {
                   "encrypted_kek": "abcdef1234567890",
                   "encrypted_rsa_private": "abcdef1234567890",
                   "hashed_password": "abcdef1234567890",
                   "rsa_public": "abcdef1234567890",
                   "username": "admin"
               }
                   ]
               }
             */

            // Parse the array and iterate through it, either saving or updating
            JSONArray usersJsonArray = responseJsonObj.getJSONArray("users");
            for (int i = 0; i < usersJsonArray.length(); i++) {
                JSONObject userJsonObject = usersJsonArray.getJSONObject(i);
                User user = new User(userJsonObject);
                realm.beginTransaction();
                realm.insertOrUpdate(user);
                realm.commitTransaction();
            }
        } else if (LDLNSocketResponseAction.SERVER_SEND_SCHEMAS.getActionKey().equals(action_code)) {
            Log.d("Websocket",
                    LDLNSocketResponseAction.SERVER_SEND_SCHEMAS.getActionKey() + " response recognized.");

            // Handle schemas response from the server, per the LDLN protocol.
            /*
             {
                "action": "server_send_schemas",
                "schemas": [
            {
                "object_key": "example",
                "object_label": "Example Thing",
                "schema": [
                    {
                        "label": "Attribute 1",
                        "type": "text",
                        "weight": 1
                    }
                ...
                ],
                "weight": 1
            }
                ]
            }
             */

            // Parse the array and iterate through it, either saving or updating
            JSONArray schemasJsonArray = responseJsonObj.getJSONArray("schemas");
            for (int i = 0; i < schemasJsonArray.length(); i++) {

                JSONObject schemaJsonObject = schemasJsonArray.getJSONObject(i);

                // Save the Schema object
                Schema schema = new Schema(schemaJsonObject);
                realm.beginTransaction();
                realm.insertOrUpdate(schema);
                realm.commitTransaction();

                // Save the associated SchemaField objects
                JSONArray schemaFieldsJsonArray = schemaJsonObject.getJSONArray("schema");
                for (int j = 0; j < schemaFieldsJsonArray.length(); j++) {
                    JSONObject schemaFieldJsonObject = schemaFieldsJsonArray.getJSONObject(j);
                    SchemaField schemaField = new SchemaField(schemaFieldJsonObject, schema);
                    realm.beginTransaction();
                    realm.insertOrUpdate(schemaField);
                    realm.commitTransaction();
                }
            }

        } else if (LDLNSocketResponseAction.SERVER_UPDATE_RESPONSE.getActionKey().equals(action_code)) {
            Log.d("Websocket",
                    LDLNSocketResponseAction.SERVER_UPDATE_RESPONSE.getActionKey() + " response recognized.");
            /*
             {
                "action": "server_update_response",
                "created_object_uuids": null,
                "updated_objects": [
            {
                "key_value_pairs": "XXXXXX",
                "object_type": "test",
                "time_modified_since_creation": 0,
                "uuid": "XXXXXX"
            }
                ]
            }
             */
            // TODO: Handle update response from the server, per the LDLN protocol. Perhaps this can just be a success/fail log?
        } else if (LDLNSocketResponseAction.SERVER_DIFF_RESPONSE.getActionKey().equals(action_code)) {
            Log.d("Websocket",
                    LDLNSocketResponseAction.SERVER_DIFF_RESPONSE.getActionKey() + " response recognized.");
            /*
             {
                "action": "server_diff_response",
                "client_unknown_objects": [
            {
                "key_value_pairs": "XXXXXX",
                "object_type": "test",
                "time_modified_since_creation": 0,
                "uuid": "XXXXXX"
            }
                ],
                "modified_objects": null,
                "server_unknown_object_uuids": [
            "03481600-0478-11e4-9191-0800200c9a66",
            "13481600-0477-11e4-9191-0800200c9a66"
                ]
            }
             */

            // Handling new server objects and server-updated objects here
            //   new ones get created
            //   updated ones get overwritten
            // Open database for caching plaintext objects while logged in
            Realm userRealm = Realm.getInstance(LDLN.getRealmConfig(mContext, LDLN.RealmLevel.USER));
            userRealm.beginTransaction();
            JSONArray newSyncableObjectsToPullJsonArray = (responseJsonObj.isNull("client_unknown_objects"))
                    ? new JSONArray()
                    : responseJsonObj.getJSONArray("client_unknown_objects");
            for (int i = 0; i < newSyncableObjectsToPullJsonArray.length(); i++) {

                JSONObject syncableObjectToPullJsonObject = newSyncableObjectsToPullJsonArray.getJSONObject(i);

                // Save the SyncableObject object
                SyncableObject syncableObject = new SyncableObject(syncableObjectToPullJsonObject, mContext);
                realm.beginTransaction();
                realm.insertOrUpdate(syncableObject);
                realm.commitTransaction();

                LDLN.cachePlaintextObject(userRealm, syncableObject);
            }
            JSONArray modifiedSyncableObjectsToPullJsonArray = (responseJsonObj.isNull("modified_objects"))
                    ? new JSONArray()
                    : responseJsonObj.getJSONArray("modified_objects");
            for (int i = 0; i < modifiedSyncableObjectsToPullJsonArray.length(); i++) {

                JSONObject syncableObjectToPullJsonObject = modifiedSyncableObjectsToPullJsonArray
                        .getJSONObject(i);

                // Save the SyncableObject object
                SyncableObject syncableObject = new SyncableObject(syncableObjectToPullJsonObject, mContext);
                realm.beginTransaction();
                realm.insertOrUpdate(syncableObject);
                realm.commitTransaction();

                LDLN.cachePlaintextObject(userRealm, syncableObject);
            }
            userRealm.commitTransaction();

            // Send app broadcast so views can receive a refresh notice!
            Intent intent = new Intent(LDLN.BROADCAST_KEY);
            intent.putExtra("message", LDLN.BroadcastMessageType.SYNCABLE_OBJECTS_REFRESHED);
            LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);

            // Identify the objects that the server doesn't have, and send them up
            JSONArray newSyncableObjectsToPushJsonArray = new JSONArray();
            JSONArray newSyncableObjectUuidsToPushJsonArray = (responseJsonObj
                    .isNull("server_unknown_object_uuids")) ? new JSONArray()
                            : responseJsonObj.getJSONArray("server_unknown_object_uuids");
            for (int i = 0; i < newSyncableObjectUuidsToPushJsonArray.length(); i++) {

                // Look up the object by uuid
                String syncableObjectUuidToPush = newSyncableObjectUuidsToPushJsonArray.getString(i);
                SyncableObject existingSyncableObjectToPush = realm.where(SyncableObject.class)
                        .equalTo("uuid", syncableObjectUuidToPush).findFirst();
                newSyncableObjectsToPushJsonArray.put(existingSyncableObjectToPush.getAsJson());
            }

            // If we indeed have objects to push, send them up
            if (newSyncableObjectsToPushJsonArray.length() > 0) {
                HashMap<String, JSONArray> additionalData = new HashMap<String, JSONArray>();
                additionalData.put("objects", newSyncableObjectsToPushJsonArray);
                sendRequest(LDLNSocketRequestAction.CLIENT_UPDATE_REQUEST, null, additionalData);
            }
        }
    } catch (JSONException e) {
        Log.e("Websocket", "Error parsing a LDLN socket response.");
        e.printStackTrace();
        return;
    }
}

From source file:activeng.pt.activenglab.BluetoothChatService.java

/**
 * Indicate that the connection attempt failed and notify the UI Activity.
 *///  w  w w . ja  v a2  s . c om
private void connectionFailed() {

    /*
    // Send a failure message back to the Activity
    Message msg = mHandler.obtainMessage(Constants.MESSAGE_TOAST);
    Bundle bundle = new Bundle();
    bundle.putString(Constants.TOAST, "Unable to connect device");
    msg.setData(bundle);
    mHandler.sendMessage(msg);
    */

    Intent intent = new Intent(Constants.MESSAGE_BT_FAIL).putExtra(Intent.EXTRA_TEXT,
            "Unable to connect device");
    //mContext.sendBroadcast(intent);
    LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);

    // Start the service over to restart listening mode
    BluetoothChatService.this.start();
}

From source file:br.liveo.ndrawer.ui.activity.MainActivity.java

License:asdf

@Override
public void onResume() {
    super.onResume();

    MovementProfile.status = 0;/*from w  w w. j  ava2  s  .co m*/

    LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
            new IntentFilter(QuickstartPreferences.REGISTRATION_READY));
    LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
            new IntentFilter(QuickstartPreferences.REGISTRATION_GENERATING));
    LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
            new IntentFilter(QuickstartPreferences.REGISTRATION_COMPLETE));

    if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEET_ENABLE_BT);
    } else {
        if (Build.VERSION.SDK_INT >= 21) {
            mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
            settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
        }
    }
}

From source file:com.android.managedprovisioning.DeviceOwnerProvisioningService.java

private void sendError() {
    if (DEBUG) {/*w  w w.  j ava  2 s.com*/
        ProvisionLogger.logd("Reporting Error: " + getResources().getString(mLastErrorMessage));
    }
    Intent intent = new Intent(ACTION_PROVISIONING_ERROR);
    intent.setClass(this, DeviceOwnerProvisioningActivity.ServiceMessageReceiver.class);
    intent.putExtra(EXTRA_USER_VISIBLE_ERROR_ID_KEY, mLastErrorMessage);
    intent.putExtra(EXTRA_FACTORY_RESET_REQUIRED, mFactoryResetRequired);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

From source file:com.antew.redditinpictures.library.ui.ImageViewerFragment.java

private OnPhotoTapListener getOnPhotoTapListener(final Activity activity) {
    return new OnPhotoTapListener() {

        @Override//from  w w w. j  av a 2  s .  co  m
        public void onPhotoTap(View view, float x, float y) {
            Intent intent = new Intent(Constants.Broadcast.BROADCAST_TOGGLE_FULLSCREEN);
            intent.putExtra(Constants.Extra.EXTRA_IS_SYSTEM_UI_VISIBLE,
                    mSystemUiStateProvider.isSystemUiVisible());
            LocalBroadcastManager.getInstance(activity).sendBroadcast(intent);
        }
    };
}

From source file:cn.moon.superwechat.ui.MainActivity.java

private void registerBroadcastReceiver() {
    broadcastManager = LocalBroadcastManager.getInstance(this);
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Constant.ACTION_CONTACT_CHANAGED);
    intentFilter.addAction(Constant.ACTION_GROUP_CHANAGED);
    intentFilter.addAction(RPConstant.REFRESH_GROUP_RED_PACKET_ACTION);
    broadcastReceiver = new BroadcastReceiver() {

        @Override/*from   w w w .j av  a  2s  .  c  om*/
        public void onReceive(Context context, Intent intent) {
            updateUnreadLabel();
            updateUnreadAddressLable();
            if (currentTabIndex == 0) {
                // refresh conversation list
                if (conversationListFragment != null) {
                    conversationListFragment.refresh();
                }
            } else if (currentTabIndex == 1) {
                if (contactListFragment != null) {
                    contactListFragment.refresh();
                }
            }
            String action = intent.getAction();
            if (action.equals(Constant.ACTION_GROUP_CHANAGED)) {
                if (EaseCommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
                    GroupsActivity.instance.onResume();
                }
            }
            //red packet code : ???
            if (action.equals(RPConstant.REFRESH_GROUP_RED_PACKET_ACTION)) {
                if (conversationListFragment != null) {
                    conversationListFragment.refresh();
                }
            }
            //end of red packet code
        }
    };
    broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
}

From source file:cn.ucai.wechat.ui.MainActivity.java

private void registerBroadcastReceiver() {
    broadcastManager = LocalBroadcastManager.getInstance(this);
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Constant.ACTION_CONTACT_CHANAGED);
    intentFilter.addAction(Constant.ACTION_GROUP_CHANAGED);
    intentFilter.addAction(RPConstant.REFRESH_GROUP_RED_PACKET_ACTION);
    broadcastReceiver = new BroadcastReceiver() {

        @Override/*www  .  j av a 2  s . com*/
        public void onReceive(Context context, Intent intent) {
            updateUnreadLabel();
            updateUnreadAddressLable();
            if (currentTabIndex == 0) {
                // refresh conversation list
                if (conversationListFragment != null) {
                    conversationListFragment.refresh();
                }
            } else if (currentTabIndex == 1) { // currentTabIndex=1?
                if (contactListFragment != null) {
                    contactListFragment.refresh();// ?
                }
            }
            String action = intent.getAction();
            if (action.equals(Constant.ACTION_GROUP_CHANAGED)) {
                if (EaseCommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
                    GroupsActivity.instance.onResume();
                }
            }
            //red packet code : ???
            if (action.equals(RPConstant.REFRESH_GROUP_RED_PACKET_ACTION)) {
                if (conversationListFragment != null) {
                    conversationListFragment.refresh();
                }
            }
            //end of red packet code
        }
    };
    broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
}