Example usage for android.content BroadcastReceiver BroadcastReceiver

List of usage examples for android.content BroadcastReceiver BroadcastReceiver

Introduction

In this page you can find the example usage for android.content BroadcastReceiver BroadcastReceiver.

Prototype

public BroadcastReceiver() 

Source Link

Usage

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

License:asdf

public void registBroadcastReceiver() {
    Log.i("?", "?");
    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override/*from  w  w w . ja  v  a 2s  .c o  m*/
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action.equals(QuickstartPreferences.REGISTRATION_READY)) {

            } else if (action.equals(QuickstartPreferences.REGISTRATION_GENERATING)) {

            } else if (action.equals(QuickstartPreferences.REGISTRATION_COMPLETE)) {
                String token = intent.getStringExtra("token");
                Log.i("token", token);

                prefs = getSharedPreferences("PrefName", MODE_PRIVATE);
                SharedPreferences.Editor edit = prefs.edit();
                edit.putString("token", token);
                edit.commit();
                String useremail = prefs.getString("useremail", "");

                try {
                    String url = "http://125.131.73.198:3000/token";
                    RequestClass rc = new RequestClass(url);
                    rc.AddParam("useremail", useremail);
                    rc.AddParam("token", token);

                    rc.Execute(1);
                    String response = rc.getResponse();

                    if (response.length() == 0) {

                    } else {

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        }
    };
}

From source file:com.nxt.yn.app.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);
    broadcastReceiver = new BroadcastReceiver() {

        @Override/*from w  w w .  j  av a2  s .  com*/
        public void onReceive(Context context, Intent intent) {
            updateUnreadLabel();
            // updateUnreadAddressLable();
            if (currentTabIndex == 1) {
                System.out.println("conversationListFragment refresh-------------->");

                // ??????
                if (conversationListFragment != null) {
                    conversationListFragment.refresh();
                }
                //                } else if (currentTabIndex == 1) {
                ////                    if(conversationListFragment != null) {
                ////                        conversationListFragment.refresh();
                ////                    }
            }
            String action = intent.getAction();
            if (action.equals(Constant.ACTION_GROUP_CHANAGED)) {
                if (EaseCommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
                    GroupsActivity.instance.onResume();
                }
            }
        }
    };
    broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
}

From source file:com.smithdtyler.prettygoodmusicplayer.NowPlaying.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent originIntent = getIntent();//from  w  ww  . java  2s .co  m
    if (originIntent.getBooleanExtra("From_Notification", false)) {

        String artistName = originIntent.getStringExtra(ArtistList.ARTIST_NAME);
        String artistAbsPath = originIntent.getStringExtra(ArtistList.ARTIST_ABS_PATH_NAME);
        if (artistName != null && artistAbsPath != null) {
            Log.i(TAG, "Now Playing was launched from a notification, setting up its back stack");
            // Reference: https://developer.android.com/reference/android/app/TaskStackBuilder.html
            TaskStackBuilder tsb = TaskStackBuilder.create(this);
            Intent intent = new Intent(this, ArtistList.class);
            tsb.addNextIntent(intent);

            intent = new Intent(this, AlbumList.class);
            intent.putExtra(ArtistList.ARTIST_NAME, artistName);
            intent.putExtra(ArtistList.ARTIST_ABS_PATH_NAME, artistAbsPath);
            tsb.addNextIntent(intent);

            String albumName = originIntent.getStringExtra(AlbumList.ALBUM_NAME);
            if (albumName != null) {
                intent = new Intent(this, SongList.class);
                intent.putExtra(AlbumList.ALBUM_NAME, albumName);
                intent.putExtra(ArtistList.ARTIST_NAME, artistName);
                intent.putExtra(ArtistList.ARTIST_ABS_PATH_NAME, artistAbsPath);
                tsb.addNextIntent(intent);
            }
            intent = new Intent(this, NowPlaying.class);
            tsb.addNextIntent(intent);
            tsb.startActivities();
        }

    }

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    String theme = sharedPref.getString("pref_theme", getString(R.string.light));
    String size = sharedPref.getString("pref_text_size", getString(R.string.medium));
    Log.i(TAG, "got configured theme " + theme);
    Log.i(TAG, "got configured size " + size);

    // These settings were fixed in english for a while, so check for old style settings as well as language specific ones.
    if (theme.equalsIgnoreCase(getString(R.string.dark)) || theme.equalsIgnoreCase("dark")) {
        Log.i(TAG, "setting theme to " + theme);
        if (size.equalsIgnoreCase(getString(R.string.small)) || size.equalsIgnoreCase("small")) {
            setTheme(R.style.PGMPDarkSmall);
        } else if (size.equalsIgnoreCase(getString(R.string.medium)) || size.equalsIgnoreCase("medium")) {
            setTheme(R.style.PGMPDarkMedium);
        } else {
            setTheme(R.style.PGMPDarkLarge);
        }
    } else if (theme.equalsIgnoreCase(getString(R.string.light)) || theme.equalsIgnoreCase("light")) {
        Log.i(TAG, "setting theme to " + theme);
        if (size.equalsIgnoreCase(getString(R.string.small)) || size.equalsIgnoreCase("small")) {
            setTheme(R.style.PGMPLightSmall);
        } else if (size.equalsIgnoreCase(getString(R.string.medium)) || size.equalsIgnoreCase("medium")) {
            setTheme(R.style.PGMPLightMedium);
        } else {
            setTheme(R.style.PGMPLightLarge);
        }
    }

    boolean fullScreen = sharedPref.getBoolean("pref_full_screen_now_playing", false);
    currentFullScreen = fullScreen;
    if (fullScreen) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    } else {
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
    setContentView(R.layout.activity_now_playing);

    if (savedInstanceState == null) {
        doBindService(true);
        startPlayingRequired = true;
    } else {
        doBindService(false);
        startPlayingRequired = false;
    }

    // Get the message from the intent
    Intent intent = getIntent();
    if (intent.getBooleanExtra(KICKOFF_SONG, false)) {
        desiredArtistName = intent.getStringExtra(ArtistList.ARTIST_NAME);
        desiredAlbumName = intent.getStringExtra(AlbumList.ALBUM_NAME);
        desiredArtistAbsPath = intent.getStringExtra(ArtistList.ARTIST_ABS_PATH_NAME);
        desiredSongAbsFileNames = intent.getStringArrayExtra(SongList.SONG_ABS_FILE_NAME_LIST);
        desiredAbsSongFileNamesPosition = intent.getIntExtra(SongList.SONG_ABS_FILE_NAME_LIST_POSITION, 0);
        desiredSongProgress = intent.getIntExtra(MusicPlaybackService.TRACK_POSITION, 0);

        Log.d(TAG,
                "Got song names " + desiredSongAbsFileNames + " position " + desiredAbsSongFileNamesPosition);

        TextView et = (TextView) findViewById(R.id.artistName);
        et.setText(desiredArtistName);

        et = (TextView) findViewById(R.id.albumName);
        et.setText(desiredAlbumName);
    }

    // The song name field will be set when we get our first update update from the service.

    final ImageButton pause = (ImageButton) findViewById(R.id.playPause);
    pause.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            playPause();
        }

    });

    ImageButton previous = (ImageButton) findViewById(R.id.previous);
    previous.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            previous();
        }

    });

    previous.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            jumpBack();
            return true;
        }
    });

    ImageButton next = (ImageButton) findViewById(R.id.next);
    next.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            next();
        }
    });

    final ImageButton shuffle = (ImageButton) findViewById(R.id.shuffle);
    shuffle.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            toggleShuffle();
        }
    });

    final ImageButton jumpback = (ImageButton) findViewById(R.id.jumpback);
    jumpback.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            jumpBack();
        }
    });

    SeekBar seekBar = (SeekBar) findViewById(R.id.songProgressBar);
    seekBar.setEnabled(true);
    seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

        private int requestedProgress;

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                Log.v(TAG, "drag location updated..." + progress);
                this.requestedProgress = progress;
                updateSongProgressLabel(progress);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            NowPlaying.this.userDraggingProgress = true;

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            Message msg = Message.obtain(null, MusicPlaybackService.MSG_SEEK_TO);
            msg.getData().putInt(MusicPlaybackService.TRACK_POSITION, requestedProgress);
            try {
                Log.i(TAG, "Sending a request to seek!");
                mService.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            NowPlaying.this.userDraggingProgress = false;
        }

    });

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("com.smithdtyler.ACTION_EXIT");
    exitReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "Received exit request, shutting down...");
            Intent msgIntent = new Intent(getBaseContext(), MusicPlaybackService.class);
            msgIntent.putExtra("Message", MusicPlaybackService.MSG_STOP_SERVICE);
            startService(msgIntent);
            finish();
        }

    };
    registerReceiver(exitReceiver, intentFilter);
}

From source file:com.hichinaschool.flashcards.anki.StudyOptionsActivity.java

/**
 * Show/dismiss dialog when sd card is ejected/remounted (collection is saved by SdCardReceiver)
 *///from   w  ww .  j a va  2  s. c  om
private void registerExternalStorageListener() {
    if (mUnmountReceiver == null) {
        mUnmountReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(SdCardReceiver.MEDIA_EJECT)) {
                    mNotMountedDialog = StyledOpenCollectionDialog.show(StudyOptionsActivity.this,
                            getResources().getString(R.string.sd_card_not_mounted), new OnCancelListener() {

                                @Override
                                public void onCancel(DialogInterface arg0) {
                                    finish();
                                }
                            });
                } else if (intent.getAction().equals(SdCardReceiver.MEDIA_MOUNT)) {
                    if (mNotMountedDialog != null && mNotMountedDialog.isShowing()) {
                        mNotMountedDialog.dismiss();
                    }
                    mCurrentFragment.reloadCollection();
                }
            }
        };
        IntentFilter iFilter = new IntentFilter();
        iFilter.addAction(SdCardReceiver.MEDIA_EJECT);
        iFilter.addAction(SdCardReceiver.MEDIA_MOUNT);
        registerReceiver(mUnmountReceiver, iFilter);
    }
}

From source file:com.facebook.internal.LikeActionController.java

private static void registerSessionBroadcastReceivers() {
    LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(applicationContext);

    IntentFilter filter = new IntentFilter();
    filter.addAction(Session.ACTION_ACTIVE_SESSION_UNSET);
    filter.addAction(Session.ACTION_ACTIVE_SESSION_CLOSED);
    filter.addAction(Session.ACTION_ACTIVE_SESSION_OPENED);

    broadcastManager.registerReceiver(new BroadcastReceiver() {
        @Override//from  w ww . j a  va  2s  .  c  o m
        public void onReceive(Context receiverContext, Intent intent) {
            if (isPendingBroadcastReset) {
                return;
            }

            String action = intent.getAction();
            final boolean shouldClearDisk = Utility.areObjectsEqual(Session.ACTION_ACTIVE_SESSION_UNSET, action)
                    || Utility.areObjectsEqual(Session.ACTION_ACTIVE_SESSION_CLOSED, action);

            isPendingBroadcastReset = true;
            // Delaying sending the broadcast to reset, because we might get many successive calls from Session
            // (to UNSET, SET & OPEN) and a delay would prevent excessive chatter.
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // Bump up the objectSuffix so that we don't have a filename collision between a cache-clear and
                    // and a cache-read/write.
                    //
                    // NOTE: We know that onReceive() was called on the main thread. This means that even this code
                    // is running on the main thread, and therefore, there aren't synchronization issues with
                    // incrementing the objectSuffix and clearing the caches here.
                    if (shouldClearDisk) {
                        objectSuffix = (objectSuffix + 1) % MAX_OBJECT_SUFFIX;
                        applicationContext
                                .getSharedPreferences(LIKE_ACTION_CONTROLLER_STORE, Context.MODE_PRIVATE).edit()
                                .putInt(LIKE_ACTION_CONTROLLER_STORE_OBJECT_SUFFIX_KEY, objectSuffix).apply();

                        // Only clearing the actual caches. The MRU index will self-clean with usage.
                        // Clearing the caches is necessary to prevent leaking like-state across sessions.
                        cache.clear();
                        controllerDiskCache.clearCache();
                    }

                    broadcastAction(null, ACTION_LIKE_ACTION_CONTROLLER_DID_RESET);
                    isPendingBroadcastReset = false;
                }
            }, 100);
        }
    }, filter);
}

From source file:com.commontime.plugin.LocationManager.java

private void initBluetoothListener() {

    //check access
    if (!hasBlueToothPermission()) {
        debugWarn("Cannot listen to Bluetooth service when BLUETOOTH permission is not added");
        return;/*  w  w  w.ja va 2 s.c  o  m*/
    }

    //check device support
    try {
        iBeaconManager.checkAvailability();
    } catch (Exception e) {
        //if device does not support iBeacons an error is thrown
        debugWarn("Cannot listen to Bluetooth service: " + e.getMessage());
        return;
    }

    if (broadcastReceiver != null) {
        debugWarn("Already listening to Bluetooth service, not adding again");
        return;
    }

    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();

            // Only listen for Bluetooth server changes
            if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {

                final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
                final int oldState = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE,
                        BluetoothAdapter.ERROR);

                debugLog("Bluetooth Service state changed from " + getStateDescription(oldState) + " to "
                        + getStateDescription(state));

                switch (state) {
                case BluetoothAdapter.ERROR:
                    beaconServiceNotifier.didChangeAuthorizationStatus("AuthorizationStatusNotDetermined");
                    break;
                case BluetoothAdapter.STATE_OFF:
                case BluetoothAdapter.STATE_TURNING_OFF:
                    if (oldState == BluetoothAdapter.STATE_ON)
                        beaconServiceNotifier.didChangeAuthorizationStatus("AuthorizationStatusDenied");
                    break;
                case BluetoothAdapter.STATE_ON:
                    beaconServiceNotifier.didChangeAuthorizationStatus("AuthorizationStatusAuthorized");
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    break;
                }
            }
        }

        private String getStateDescription(int state) {
            switch (state) {
            case BluetoothAdapter.ERROR:
                return "ERROR";
            case BluetoothAdapter.STATE_OFF:
                return "STATE_OFF";
            case BluetoothAdapter.STATE_TURNING_OFF:
                return "STATE_TURNING_OFF";
            case BluetoothAdapter.STATE_ON:
                return "STATE_ON";
            case BluetoothAdapter.STATE_TURNING_ON:
                return "STATE_TURNING_ON";
            }
            return "ERROR" + state;
        }
    };

    // Register for broadcasts on BluetoothAdapter state change
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    cordova.getActivity().registerReceiver(broadcastReceiver, filter);
}

From source file:com.zentri.otademo.OTAActivity.java

private void initBroadcastReceiver() {
    mBroadcastReceiver = new BroadcastReceiver() {
        @Override/*from   www . j  a va  2  s  .co  m*/
        public void onReceive(Context context, Intent intent) {
            if (intent == null) {
                Log.e(TAG, "Received null intent!");
                return;
            }

            String action = intent.getAction();

            Log.d(TAG, "Received event " + action);
            switch (action) {
            case ZentriOSBLEService.ACTION_CURRENT_VERSION_UPDATE:
                setVersionFromIntent(mCurrentVersion, intent);
                break;

            case ZentriOSBLEService.ACTION_UPDATE_VERSION_UPDATE:
                setVersionFromIntent(mUpdateVersion, intent);
                break;

            case ZentriOSBLEService.ACTION_PROGRESS_MAX_UPDATE:
                mProgressBar.setMax(getProgressFromIntent(intent));
                break;

            case ZentriOSBLEService.ACTION_PROGRESS_UPDATE:
                mProgressBar.setProgress(getProgressFromIntent(intent));
                break;

            case ZentriOSBLEService.ACTION_STATUS_UPDATE:
                setStatusFromIntent(mStatus, intent);
                break;

            case ZentriOSBLEService.ACTION_CONNECTED:
                Log.d(TAG, "Got connected event");
                //ZentriOSBLEService re-inits OTAManager and reads version etc
                break;

            case ZentriOSBLEService.ACTION_DISCONNECTED:
                Log.d(TAG, "Got disconnected event");
                OTAActivity.this.finish();
                break;

            case ZentriOSBLEService.ACTION_ERROR:
                onError(getErrorFromIntent(intent), getFinishOnCloseFromIntent(intent));
                break;
            }
        }
    };
}

From source file:com.arctech.stikyhive.ChattingActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    recipientStkid = getIntent().getExtras().getString("recipientStkid");
    chatRecipient = getIntent().getExtras().getString("chatRecipient");
    chatRecipientUrl = getIntent().getExtras().getString("chatRecipientUrl");
    senderToken = getIntent().getExtras().getString("senderToken");
    recipientToken = getIntent().getExtras().getString("recipientToken");
    noti = getIntent().getExtras().getBoolean("noti");
    message = getIntent().getExtras().getString("message");
    rows = getIntent().getExtras().getInt("rows");

    pref = PreferenceManager.getDefaultSharedPreferences(this);
    ws = new JsonWebService();
    dbHelper = new DBHelper(this);
    dialog = new ProgressDialog(this);
    listChatContact = new ArrayList<>();
    listChatContact = dbHelper.getChatContact();
    Log.i(" Chat Contact ", " " + listChatContact.size());
    //to change font
    faceSemi_bold = Typeface.createFromAsset(getAssets(), fontOSSemi_bold);
    Typeface faceLight = Typeface.createFromAsset(getAssets(), fontOSLight);
    faceRegular = Typeface.createFromAsset(getAssets(), fontOSRegular);

    imageLoader = ImageLoader.getInstance();
    if (!imageLoader.isInited()) {
        imageLoader.init(ImageLoaderConfiguration.createDefault(this));
    }/*from  w  w  w  .jav  a 2 s . com*/

    start = new Date();
    SimpleDateFormat oFormat = new SimpleDateFormat("dd MMM HH:mm");
    timeSend = oFormat.format(start);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat);

    txtUserName = (TextView) findViewById(R.id.txtChatName);
    edTxtMsg = (EditText) findViewById(R.id.edTxtMsg);
    imgViewProfile = (ImageView) findViewById(R.id.imgViewChat);
    imgViewAddCon = (ImageView) findViewById(R.id.imgAddContact);
    lv = (ListView) findViewById(R.id.listView1);
    layoutLabel = (LinearLayout) findViewById(R.id.layoutLabel);
    txtLabel1 = (TextView) findViewById(R.id.txtLabel1);
    txtLabel2 = (TextView) findViewById(R.id.txtLabel2);
    txtLabel3 = (TextView) findViewById(R.id.txtLabel3);
    txtLabel2.setText(" " + chatRecipient + " ");
    txtLabel1.setTypeface(faceLight);
    txtLabel2.setTypeface(faceRegular);
    txtLabel3.setTypeface(faceLight);
    // lv.smoothScrollToPosition(adapter.getCount() - 1);

    for (ChatContact contact : listChatContact) {
        if (contact.getContactId().equals(recipientStkid)) {
            imgViewAddCon.setVisibility(View.INVISIBLE);
            layoutLabel.setVisibility(View.GONE);
            break;
        }
    }
    Log.i(TAG, " come back again");
    adapter = new ChatArrayAdapter(getApplicationContext(), R.layout.messaging_listview, faceSemi_bold,
            faceRegular);
    lv.setAdapter(adapter);
    // adapter.add(new StikyChat(chatRecipientUrl, "Hello", false, "12.10.2015", "12.1.2014"));

    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
    // BEGIN_INCLUDE (change_colors)
    // Set the color scheme of the SwipeRefreshLayout by providing 4 color resource ids
    swipeRefreshLayout.setColorScheme(R.color.swipe_color_1, R.color.swipe_color_2, R.color.swipe_color_3,
            R.color.swipe_color_4);
    limitMsg = 7;
    // END_INCLUDE (change_colors)
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            Log.i(" Refresh Layout ", "onRefresh called from SwipeRefreshLayout");
            if (limitMsg < rows) {
                Log.i("Limit Message ", " " + limitMsg);
                limitMsg *= 2;
                fetchRecords();
            } else if (limitMsg > rows && (limitMsg - rows < 7)) {
                fetchRecords();
            } else {
                Log.i("No data ", "to refresh");
                swipeRefreshLayout.setRefreshing(false);
                Toast.makeText(getApplicationContext(), "No data to refresh!", Toast.LENGTH_SHORT).show();
            }

            // initiateRefresh();
        }
    });

    LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    LinearLayout headerLayout = (LinearLayout) findViewById(R.id.header);
    View header = inflator.inflate(R.layout.header, null);

    TextView textView = (TextView) header.findViewById(R.id.textView1);
    textView.setText("StikyChat");
    textView.setTypeface(faceSemi_bold);
    textView.setVisibility(View.VISIBLE);
    headerLayout.addView(header);
    LinearLayout layoutRight = (LinearLayout) header.findViewById(R.id.layoutRight);
    layoutRight.setVisibility(View.GONE);

    txtUserName.setText(chatRecipient);
    Log.i(TAG, "Activity Name " + txtUserName.getText().toString());
    txtUserName.setTypeface(faceSemi_bold);

    String url = "";
    if (chatRecipientUrl.contains("http")) {
        url = chatRecipientUrl;
    } else {
        url = this.getResources().getString(R.string.url) + "/" + chatRecipientUrl;
    }
    addAndroidUniversalImageLoader(imgViewProfile, url);
    //        if (noti && (!message.equals(""))) {
    //            adapter.add(new StikyChat(chatRecipientUrl, message, true, timeSend, ""));
    //            lv.smoothScrollToPosition(adapter.getCount() - 1);
    //        }

    //to show history chats between two users(sender & recipient)
    dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    dateFormat2 = new SimpleDateFormat("dd MMM HH:mm");
    listHistory = dbHelper.getStikyChat();
    if (listHistory.size() > 0) {
        Collections.reverse(listHistory);
        for (StikyChatTb chatTb : listHistory) {
            String getDate = chatTb.getSendDate();
            String fromStikyBee = chatTb.getSender();
            try {
                String createDate = dateFormat2.format(dateFormat.parse(getDate));
                if (fromStikyBee.equals(pref.getString("stkid", ""))) {
                    adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), false, createDate, ""));
                } else {
                    adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), true, createDate, ""));
                }
                lv.smoothScrollToPosition(adapter.getCount() - 1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    mRegistrationBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            messageGCM = sharedPreferences.getString("message", "");
            recipientProfileGCM = sharedPreferences.getString("chatRecipientUrl", "");
            recipientNameGCM = sharedPreferences.getString("chatRecipientName", "");
            recipientStkidGCM = sharedPreferences.getString("recipientStkid", "");
            recipientTokenGCM = sharedPreferences.getString("recipientToken", "");
            senderTokenGCM = sharedPreferences.getString("senderToken", "");

            Log.i(TAG, "..." + recipientStkidGCM.trim() + " STKID " + recipientStkid.trim() + ":");
            if (firstConnect) {
                if (recipientStkidGCM.trim() == recipientStkid.trim()
                        || recipientStkidGCM.equals(recipientStkid)) {
                    MyGcmListenerService.flagSendNoti = false;
                    Log.i(TAG, " " + message);
                    // (1) get today's date
                    start = new Date();
                    SimpleDateFormat oFormat = new SimpleDateFormat("dd MMM HH:mm");
                    timeSend = oFormat.format(start);

                    Log.i(TAG, "First connect " + firstConnect);
                    StikyChat stikyChat = new StikyChat(recipientProfileGCM, messageGCM, true, timeSend, "");
                    Log.i(TAG, " First " + message + " " + recipientProfileGCM + " " + timeSend);
                    Log.i(TAG, "User " + txtUserName.getText().toString());
                    //txtUserName.setText(message);
                    Log.i(TAG, "User 2 " + txtUserName.getText().toString());
                    adapter.add(stikyChat);
                    adapter.notifyDataSetChanged();
                    //new regTask2().execute("Obj ");
                    lv.smoothScrollToPosition(adapter.getCount() - 1);
                } else {
                    Log.i(TAG, "..." + recipientStkidGCM.trim());
                    Log.i(TAG, "&&&" + recipientStkid.trim());
                    Log.i(TAG, "else casee");
                    //notificaton send
                    flagNotifi = true;
                    new regTask2().execute("Notification");
                }
                firstConnect = false;
            }
        }
    };
}

From source file:com.lchtime.safetyexpress.ui.chat.hx.activity.HXMainActivity.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  .  ja  v a  2s . c  o m
        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(HXMainActivity.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:com.mbientlab.metawear.api.MetaWearBleService.java

/**
 * Get the broadcast receiver for MetaWear intents.  An Activity using the MetaWear service 
 * will need to register this receiver to trigger its callback functions.
 * @return MetaWear specific broadcast receiver
 *///ww  w .j av a2 s . c  o  m
public static BroadcastReceiver getMetaWearBroadcastReceiver() {
    if (mwBroadcastReceiver == null) {
        mwBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                BluetoothDevice device = intent.getExtras().getParcelable(Extra.BLUETOOTH_DEVICE);

                if (device != null && metaWearStates.containsKey(device)) {
                    MetaWearState mwState = metaWearStates.get(device);

                    switch (intent.getAction()) {
                    case Action.GATT_ERROR:
                        int gattStatus = intent.getIntExtra(Extra.STATUS, -1);
                        DeviceCallbacks.GattOperation gattOp = (GattOperation) intent.getExtras()
                                .get(Extra.GATT_OPERATION);
                        for (DeviceCallbacks it : mwState.deviceCallbacks) {
                            it.receivedGattError(gattOp, gattStatus);
                        }
                        break;
                    case Action.NOTIFICATION_RECEIVED:
                        final byte[] data = (byte[]) intent.getExtras().get(Extra.CHARACTERISTIC_VALUE);
                        if (data.length > 1) {
                            byte moduleOpcode = data[0], registerOpcode = (byte) (0x7f & data[1]);
                            Collection<ModuleCallbacks> callbacks;
                            if (mwState.moduleCallbackMap.containsKey(moduleOpcode)
                                    && (callbacks = mwState.moduleCallbackMap.get(moduleOpcode)) != null) {
                                Module.lookupModule(moduleOpcode).lookupRegister(registerOpcode)
                                        .notifyCallbacks(callbacks, data);
                            }
                        }
                        break;
                    case Action.DEVICE_CONNECTED:
                        for (DeviceCallbacks it : mwState.deviceCallbacks) {
                            it.connected();
                        }
                        break;
                    case Action.DEVICE_DISCONNECTED:
                        for (DeviceCallbacks it : mwState.deviceCallbacks) {
                            it.disconnected();
                        }
                        if (!mwState.retainState) {
                            mwState.resetState();
                            metaWearStates.remove(mwState.mwBoard);
                        }
                        break;
                    case Action.CHARACTERISTIC_READ:
                        UUID serviceUuid = (UUID) intent.getExtras().get(Extra.SERVICE_UUID),
                                charUuid = (UUID) intent.getExtras().get(Extra.CHARACTERISTIC_UUID);
                        GATTCharacteristic characteristic = GATTService.lookupGATTService(serviceUuid)
                                .getCharacteristic(charUuid);
                        for (DeviceCallbacks it : mwState.deviceCallbacks) {
                            it.receivedGATTCharacteristic(characteristic,
                                    (byte[]) intent.getExtras().get(Extra.CHARACTERISTIC_VALUE));
                        }
                        break;
                    case Action.RSSI_READ:
                        int rssi = intent.getExtras().getInt(Extra.RSSI);
                        for (DeviceCallbacks it : mwState.deviceCallbacks) {
                            it.receivedRemoteRSSI(rssi);
                        }
                        break;
                    }
                }
            }
        };
    }
    return mwBroadcastReceiver;
}