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:com.supremainc.biostar2.base.BaseActivity.java

@SuppressLint("ShowToast")
@Override/*from w w w.j  a v a  2  s.c  o m*/
protected void onCreate(Bundle savedInstanceState) {
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    super.onCreate(savedInstanceState);
    mContext = this;
    mResouce = mContext.getResources();
    mPopup = new Popup(mContext);
    mToastPopup = new ToastPopup(mContext);
    mUserDataProvider = UserDataProvider.getInstance(mContext);
    mDeviceDataProvider = DeviceDataProvider.getInstance(mContext);
    mDoorDataProvider = DoorDataProvider.getInstance(mContext);
    mEventDataProvider = EventDataProvider.getInstance(mContext);
    mAccessGroupDataProvider = AccessGroupDataProvider.getInstance(mContext);
    mAccessLevelDataProvider = AccessLevelDataProvider.getInstance(mContext);
    mPermissionDataProvider = PermissionDataProvider.getInstance(mContext);
    mCommonDataProvider = CommonDataProvider.getInstance(mContext);
    mPushProvider = PushDataProvider.getInstance(this);
    mAppDataProvider = AppDataProvider.getInstance(mContext);
    if (BuildConfig.DEBUG) {
        if (savedInstanceState == null) {
            Log.e(TAG, "onCreate savedInstanceState is null");
        } else {
            Log.e(TAG, "onCreate savedInstanceState is not null");
        }
    }

    if (!mCommonDataProvider.isValidLogin() && !mIsResumCheckSkip) {
        if (BuildConfig.DEBUG) {
            Log.e(TAG, "onCreate memory is cleard");
        }
        //      mPopup.show(PopupType.ALERT, getString(R.string.info),getString(R.string.login_expire), popupListener, getString(R.string.ok), null);

    }

    if (mClearReceiver == null) {
        mClearReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (isFinishing()) {
                    return;
                }
                final String action = intent.getAction();
                if (BuildConfig.DEBUG) {
                    Log.e(TAG, "receive:" + action);
                }
                if (action.equals(Setting.BROADCAST_CLEAR) || action.equals(Setting.BROADCAST_ALL_CLEAR)) {
                    finish();
                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Setting.BROADCAST_CLEAR);
        intentFilter.addAction(Setting.BROADCAST_ALL_CLEAR);
        LocalBroadcastManager.getInstance(this).registerReceiver(mClearReceiver, intentFilter);
    }

}

From source file:elbauldelprogramador.com.gpsqr.MapsActivity.java

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

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    SupportStreetViewPanoramaFragment streetViewPanoramaFragment = (SupportStreetViewPanoramaFragment) getSupportFragmentManager()
            .findFragmentById(R.id.streetviewpanorama);
    streetViewPanoramaFragment.getStreetViewPanoramaAsync(this);

    mAct = this;/* ww  w.ja  va2  s.  c o m*/
    mRequestingLocationUpdates = true;

    final ActionButton ab = (ActionButton) findViewById(R.id.action_button);

    ab.setImageResource(R.drawable.ic_qr);
    ab.setShowAnimation(ActionButton.Animations.JUMP_FROM_DOWN);
    ab.setHideAnimation(ActionButton.Animations.JUMP_TO_DOWN);
    ab.setButtonColor(getResources().getColor(R.color.fab_material_amber_500));
    ab.setButtonColorPressed(getResources().getColor(R.color.fab_material_amber_900));

    ab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ab.hide();
            new IntentIntegrator(mAct).initiateScan();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    ab.show();
                }
            }, 1000);
        }
    });

    mLocationReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            mPreviousLocation = mCurrentLocation;
            mCurrentLocation = intent.getParcelableExtra(LocationUpdaterService.COPA_MESSAGE);
            updateMap();
            mLocationsList.add(mCurrentLocation);

            if (BuildConfig.DEBUG) {
                Log.d(TAG, "LocationList size: " + mLocationsList.size());
            }
        }
    };

    mRequestLocationIntent = new Intent(this, LocationUpdaterService.class);
    startService(mRequestLocationIntent);

    // Update values using data stored in the Bundle.
    updateValuesFromBundle(savedInstanceState);
}

From source file:com.ai.ui.partybuild.message.HyphenateMainActivity.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/* ww w  .ja va2s.  c o m*/
        public void onReceive(Context context, Intent intent) {
            updateUnreadLabel();
            if (currentTabIndex == 0) {
                // refresh conversation list
                if (conversationListFragment != null) {
                    conversationListFragment.refresh();
                }
            }
            String action = intent.getAction();
            if (action.equals(Constant.ACTION_GROUP_CHANAGED)) {
                GroupFragment.instance.onResume();
            }
        }
    };
    broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
}

From source file:com.nononsenseapps.feeder.ui.FeedFragment.java

public FeedFragment() {
    // Listens on sync broadcasts
    mSyncReceiver = new BroadcastReceiver() {
        @Override/*  w ww .j a v a2 s  . c  o m*/
        public void onReceive(Context context, Intent intent) {
            if (RssSyncAdapter.SYNC_BROADCAST.equals(intent.getAction())) {
                onSyncBroadcast(intent.getBooleanExtra(RssSyncAdapter.SYNC_BROADCAST_IS_ACTIVE, false));
            }
        }
    };
}

From source file:com.supremainc.biostar2.door.DoorListFragment.java

protected void registerBroadcast() {
    if (mReceiver == null) {
        mReceiver = new BroadcastReceiver() {
            @Override//from ww w .  j av a2 s . co m
            public void onReceive(Context context, Intent intent) {
                if (mIsDestroy) {
                    return;
                }
                String action = intent.getAction();
                if (action.equals(Setting.BROADCAST_UPDATE_DOOR)) {
                    if (isResumed()) {
                        if (mDoorAdapter != null) {
                            mDoorAdapter.getItems(mSearchText);
                            mDoorAdapter.setPostReceiveToLastPosition();
                        }
                    } else {
                        mIsDataReceived = false;
                        mTotal = -1;
                    }
                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Setting.BROADCAST_UPDATE_DOOR);
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver, intentFilter);
    }
}

From source file:com.mobilyzer.MeasurementScheduler.java

@Override
public void onCreate() {
    Logger.d("MeasurementScheduler -> onCreate called");
    PhoneUtils.setGlobalContext(this.getApplicationContext());

    phoneUtils = PhoneUtils.getPhoneUtils();
    phoneUtils.registerSignalStrengthListener();

    this.measurementExecutor = Executors.newSingleThreadExecutor();
    this.mainQueue = new PriorityBlockingQueue<MeasurementTask>(Config.MAX_TASK_QUEUE_SIZE,
            new TaskComparator());
    this.waitingTasksQueue = new PriorityBlockingQueue<MeasurementTask>(Config.MAX_TASK_QUEUE_SIZE,
            new WaitingTasksComparator());
    this.pendingTasks = new ConcurrentHashMap<MeasurementTask, Future<MeasurementResult[]>>();
    this.tasksStatus = new ConcurrentHashMap<String, MeasurementScheduler.TaskStatus>();
    this.alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    this.resourceCapManager = new ResourceCapManager(Config.DEFAULT_BATTERY_THRESH_PRECENT, this);

    this.serverTasks = new HashMap<String, Date>();
    // this.currentSchedule = new HashMap<String, MeasurementTask>();

    this.idToClientKey = new ConcurrentHashMap<String, String>();

    messenger = new Messenger(new APIRequestHandler(this));

    gcmManager = new GCMManager(this.getApplicationContext());

    this.setCurrentTask(null);
    this.setCurrentTaskStartTime(null);

    this.checkin = new Checkin(this);
    this.checkinRetryIntervalSec = Config.MIN_CHECKIN_RETRY_INTERVAL_SEC;
    this.checkinRetryCnt = 0;
    this.checkinTask = new CheckinTask();

    this.batteryThreshold = -1;
    this.checkinIntervalSec = -1;
    this.dataUsageProfile = DataUsageProfile.NOTASSIGNED;

    //    loadSchedulerState();//TODO(ASHKAN)

    // Register activity specific BroadcastReceiver here
    IntentFilter filter = new IntentFilter();
    filter.addAction(UpdateIntent.CHECKIN_ACTION);
    filter.addAction(UpdateIntent.CHECKIN_RETRY_ACTION);
    filter.addAction(UpdateIntent.MEASUREMENT_ACTION);
    filter.addAction(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION);
    filter.addAction(UpdateIntent.GCM_MEASUREMENT_ACTION);
    filter.addAction(UpdateIntent.PLT_MEASUREMENT_ACTION);

    broadcastReceiver = new BroadcastReceiver() {

        @Override/*from   ww w .j a v a 2  s .c  om*/
        public void onReceive(Context context, Intent intent) {
            Logger.d(intent.getAction() + " RECEIVED");
            if (intent.getAction().equals(UpdateIntent.MEASUREMENT_ACTION)) {
                handleMeasurement();

            } else if (intent.getAction().equals(UpdateIntent.GCM_MEASUREMENT_ACTION)) {
                try {
                    JSONObject json = new JSONObject(
                            intent.getExtras().getString(UpdateIntent.MEASUREMENT_TASK_PAYLOAD));
                    Logger.d("MeasurementScheduler -> GCMManager: json task Value is " + json);
                    if (json != null && MeasurementTask.getMeasurementTypes().contains(json.get("type"))) {

                        try {
                            MeasurementTask task = MeasurementJsonConvertor.makeMeasurementTaskFromJson(json);
                            task.getDescription().priority = MeasurementTask.GCM_PRIORITY;
                            task.getDescription().startTime = new Date(System.currentTimeMillis() - 1000);
                            task.getDescription().endTime = new Date(System.currentTimeMillis() + (600 * 1000));
                            task.generateTaskID();
                            task.getDescription().key = Config.SERVER_TASK_CLIENT_KEY;
                            submitTask(task);
                        } catch (IllegalArgumentException e) {
                            Logger.w("MeasurementScheduler -> GCM : Could not create task from JSON: " + e);
                        }
                    }

                } catch (JSONException e) {
                    Logger.e(
                            "MeasurementSchedule -> GCMManager : Got exception during converting GCM json to MeasurementTask",
                            e);
                }

            } else if (intent.getAction().equals(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION)) {
                String taskid = intent.getStringExtra(UpdateIntent.TASKID_PAYLOAD);
                String taskKey = intent.getStringExtra(UpdateIntent.CLIENTKEY_PAYLOAD);
                int priority = intent.getIntExtra(UpdateIntent.TASK_PRIORITY_PAYLOAD,
                        MeasurementTask.INVALID_PRIORITY);

                Logger.e(
                        intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD) + " " + taskid + " " + taskKey);
                if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD).equals(Config.TASK_FINISHED)) {
                    tasksStatus.put(taskid, TaskStatus.FINISHED);
                    Parcelable[] results = intent.getParcelableArrayExtra(UpdateIntent.RESULT_PAYLOAD);
                    if (results != null) {
                        sendResultToClient(results, priority, taskKey, taskid);

                        for (Object obj : results) {
                            try {
                                MeasurementResult result = (MeasurementResult) obj;
                                /**
                                 * Nullify the additional parameters in MeasurmentDesc, or the results won't be
                                 * accepted by GAE server
                                 */
                                result.getMeasurementDesc().parameters = null;
                                String jsonResult = MeasurementJsonConvertor.encodeToJson(result).toString();
                                saveResultToFile(jsonResult);
                            } catch (JSONException e) {
                                Logger.e("Error converting results to json format", e);
                            }
                        }
                    }
                    handleMeasurement();
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD).equals(Config.TASK_PAUSED)) {
                    tasksStatus.put(taskid, TaskStatus.PAUSED);
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD)
                        .equals(Config.TASK_STOPPED)) {
                    tasksStatus.put(taskid, TaskStatus.SCHEDULED);
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD)
                        .equals(Config.TASK_CANCELED)) {
                    tasksStatus.put(taskid, TaskStatus.CANCELLED);
                    Parcelable[] results = intent.getParcelableArrayExtra(UpdateIntent.RESULT_PAYLOAD);
                    if (results != null) {
                        sendResultToClient(results, priority, taskKey, taskid);
                    }
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD)
                        .equals(Config.TASK_STARTED)) {
                    tasksStatus.put(taskid, TaskStatus.RUNNING);
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD)
                        .equals(Config.TASK_RESUMED)) {
                    tasksStatus.put(taskid, TaskStatus.RUNNING);
                }
            } else if (intent.getAction().equals(UpdateIntent.CHECKIN_ACTION)
                    || intent.getAction().equals(UpdateIntent.CHECKIN_RETRY_ACTION)) {
                Logger.d("Checkin intent received");
                handleCheckin();
            }
        }
    };
    this.registerReceiver(broadcastReceiver, filter);
}

From source file:com.example.bluetooth.RFduinoService.java

private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) {
    if (UUID_RECEIVE.equals(characteristic.getUuid())) {
        final Intent intent = new Intent(action);
        intent.putExtra(EXTRA_DATA, characteristic.getValue());
        //sendBroadcast(intent, Manifest.permission.BLUETOOTH); // Left it, to avoid modify BluetoothActivty due to time constraints
        mServiceStart = true;//from   www.  j a v  a 2s. c  o m
        intent.putExtra(ACTION_DATA_TAG, true);
        sendOrderedBroadcast(intent, Manifest.permission.BLUETOOTH, new BroadcastReceiver() {
            @Override
            public void onReceive(Context pContext, Intent pIntent) {
                //String pResultData = getResultData();
                if (getResultData() != null && getResultData().equals("Tag_Activity")) {
                    mServiceStart = false;
                    Log.wtf(TAG, "StartService false");
                }

                // Trigger Reminder Service
                if (mServiceStart) {
                    final Intent mReminderIntent = new Intent(getApplicationContext(), ReminderService.class);
                    mReminderIntent.putExtra(ACTION_DATA_SERVICE, true);
                    mReminderIntent.putExtra(EXTRA_DATA, characteristic.getValue());
                    getApplicationContext().startService(mReminderIntent);
                }

            }
        }, null, Activity.RESULT_OK, null, null);
        Log.w(TAG, "BTLE Data received and Broadcasted");

        //            // Trigger Reminder Service
        //            if(mServiceStart) {
        //                final Intent mReminderIntent = new Intent(getApplicationContext(), ReminderService.class);
        //                mReminderIntent.putExtra(ACTION_DATA_SERVICE, true);
        //                mReminderIntent.putExtra(EXTRA_DATA, characteristic.getValue());
        //                getApplicationContext().startService(mReminderIntent);
        //            }
    }
}

From source file:is.hello.buruberi.bluetooth.stacks.android.NativeBluetoothStack.java

@Override
@RequiresPermission(allOf = { Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN, })
public Observable<Void> turnOn() {
    if (adapter == null) {
        return Observable.error(new ChangePowerStateException());
    }//from  w  ww . j  a v  a2s.  co m

    final ReplaySubject<Void> turnOnMirror = ReplaySubject.createWithSize(1);
    final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final int oldState = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE,
                    BluetoothAdapter.ERROR);
            final int newState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
            if (oldState == BluetoothAdapter.STATE_OFF && newState == BluetoothAdapter.STATE_TURNING_ON) {
                logger.info(LOG_TAG, "Bluetooth turning on");
            } else if (oldState == BluetoothAdapter.STATE_TURNING_ON && newState == BluetoothAdapter.STATE_ON) {
                logger.info(LOG_TAG, "Bluetooth turned on");

                applicationContext.unregisterReceiver(this);

                turnOnMirror.onNext(null);
                turnOnMirror.onCompleted();
            } else {
                logger.info(LOG_TAG, "Bluetooth failed to turn on");

                applicationContext.unregisterReceiver(this);

                turnOnMirror.onError(new ChangePowerStateException());
            }
        }
    };
    applicationContext.registerReceiver(receiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
    if (!adapter.enable()) {
        applicationContext.unregisterReceiver(receiver);
        return Observable.error(new ChangePowerStateException());
    }

    return turnOnMirror;
}

From source file:com.andreadec.musicplayer.MusicService.java

/**
 * Called when the service is created./*w ww.j a va  2s. co m*/
 */
@Override
public void onCreate() {
    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MusicServiceWakelock");

    // Initialize the telephony manager
    telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    phoneStateListener = new MusicPhoneStateListener();
    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    // Initialize pending intents
    quitPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.andreadec.musicplayer.quit"), 0);
    previousPendingIntent = PendingIntent.getBroadcast(this, 0,
            new Intent("com.andreadec.musicplayer.previous"), 0);
    playpausePendingIntent = PendingIntent.getBroadcast(this, 0,
            new Intent("com.andreadec.musicplayer.playpause"), 0);
    nextPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.andreadec.musicplayer.next"), 0);
    pendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP),
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Read saved user preferences
    preferences = PreferenceManager.getDefaultSharedPreferences(this);

    // Initialize the media player
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK); // Enable the wake lock to keep CPU running when the screen is switched off

    shuffle = preferences.getBoolean(Constants.PREFERENCE_SHUFFLE, Constants.DEFAULT_SHUFFLE);
    repeat = preferences.getBoolean(Constants.PREFERENCE_REPEAT, Constants.DEFAULT_REPEAT);
    repeatAll = preferences.getBoolean(Constants.PREFERENCE_REPEATALL, Constants.DEFAULT_REPEATALL);
    try { // This may fail if the device doesn't support bass boost
        bassBoost = new BassBoost(1, mediaPlayer.getAudioSessionId());
        bassBoost.setEnabled(
                preferences.getBoolean(Constants.PREFERENCE_BASSBOOST, Constants.DEFAULT_BASSBOOST));
        setBassBoostStrength(preferences.getInt(Constants.PREFERENCE_BASSBOOSTSTRENGTH,
                Constants.DEFAULT_BASSBOOSTSTRENGTH));
        bassBoostAvailable = true;
    } catch (Exception e) {
        bassBoostAvailable = false;
    }
    try { // This may fail if the device doesn't support equalizer
        equalizer = new Equalizer(1, mediaPlayer.getAudioSessionId());
        equalizer.setEnabled(
                preferences.getBoolean(Constants.PREFERENCE_EQUALIZER, Constants.DEFAULT_EQUALIZER));
        setEqualizerPreset(
                preferences.getInt(Constants.PREFERENCE_EQUALIZERPRESET, Constants.DEFAULT_EQUALIZERPRESET));
        equalizerAvailable = true;
    } catch (Exception e) {
        equalizerAvailable = false;
    }
    random = new Random(System.nanoTime()); // Necessary for song shuffle

    shakeListener = new ShakeListener(this);
    if (preferences.getBoolean(Constants.PREFERENCE_SHAKEENABLED, Constants.DEFAULT_SHAKEENABLED)) {
        shakeListener.enable();
    }

    telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); // Start listen for telephony events

    // Inizialize the audio manager
    audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mediaButtonReceiverComponent = new ComponentName(getPackageName(), MediaButtonReceiver.class.getName());
    audioManager.registerMediaButtonEventReceiver(mediaButtonReceiverComponent);
    audioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

    // Initialize remote control client
    if (Build.VERSION.SDK_INT >= 14) {
        icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        mediaButtonIntent.setComponent(mediaButtonReceiverComponent);
        PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
                mediaButtonIntent, 0);

        remoteControlClient = new RemoteControlClient(mediaPendingIntent);
        remoteControlClient.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
                | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_NEXT);
        audioManager.registerRemoteControlClient(remoteControlClient);
    }

    updateNotificationMessage();

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("com.andreadec.musicplayer.quit");
    intentFilter.addAction("com.andreadec.musicplayer.previous");
    intentFilter.addAction("com.andreadec.musicplayer.previousNoRestart");
    intentFilter.addAction("com.andreadec.musicplayer.playpause");
    intentFilter.addAction("com.andreadec.musicplayer.next");
    intentFilter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("com.andreadec.musicplayer.quit")) {
                sendBroadcast(new Intent("com.andreadec.musicplayer.quitactivity"));
                stopSelf();
                return;
            } else if (action.equals("com.andreadec.musicplayer.previous")) {
                previousItem(false);
            } else if (action.equals("com.andreadec.musicplayer.previousNoRestart")) {
                previousItem(true);
            } else if (action.equals("com.andreadec.musicplayer.playpause")) {
                playPause();
            } else if (action.equals("com.andreadec.musicplayer.next")) {
                nextItem();
            } else if (action.equals(AudioManager.ACTION_AUDIO_BECOMING_NOISY)) {
                if (preferences.getBoolean(Constants.PREFERENCE_STOPPLAYINGWHENHEADSETDISCONNECTED,
                        Constants.DEFAULT_STOPPLAYINGWHENHEADSETDISCONNECTED)) {
                    pause();
                }
            }
        }
    };
    registerReceiver(broadcastReceiver, intentFilter);

    if (!isPlaying()) {
        loadLastSong();
    }

    startForeground(Constants.NOTIFICATION_MAIN, notification);
}

From source file:com.juliovaz.condio.activity.MainActivity.java

private void initGcm() {

    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override/*from  w  w  w.  j av  a  2  s . c  o m*/
        public void onReceive(Context context, Intent intent) {
        }
    };

    // Registering BroadcastReceiver
    registerReceiver();

    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
    }
}