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:de.msal.shoutemo.fragments.ChatFragment.java

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_chat, container, false);

    /* set the fragment title of the toolbar */
    getActivity().setTitle(getString(R.string.app_name));

    /* INPUT FIELD WHERE THE MESSAGE IS COMPOSED */
    mInputField = (EditText) view.findViewById(R.id.et_input);

    /* display a blinking dot to show the refresh status */
    final ImageView updateStatus = (ImageView) view.findViewById(R.id.ib_update_indicator);
    mReceiver = new BroadcastReceiver() {
        @Override/*from   ww w.  ja  va  2  s .  c o  m*/
        public void onReceive(Context context, Intent intent) {
            boolean enabled = intent.getBooleanExtra(GetPostsService.INTENT_UPDATE_ENABLED, false);
            if (enabled) {
                updateStatus.setVisibility(View.VISIBLE);
            } else {
                updateStatus.setVisibility(View.INVISIBLE);
            }
        }
    };

    /* SEND MESSAGE BUTTON */
    mSendButton = (ImageButton) view.findViewById(R.id.ib_send);
    // initially the mInputField is empty, so disable the send button
    mSendButton.setVisibility(View.GONE);
    // Send message when clicked on SEND-BUTTON
    mSendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mInputField.getText() != null && !TextUtils.isEmpty(mInputField.getText())) {
                new SendPostTask(getActivity()).execute(mInputField.getText().toString());
                mInputField.setText("");
            }
        }
    });

    mEmoticonGrid = (GridView) view.findViewById(R.id.emoticons_grid);
    /* set the adapter for the emoticons */
    mEmoticonGrid
            .setAdapter(new EmoticonsAdapter(getActivity(), new EmoticonsAdapter.OnEmoticonClickListener() {
                @Override
                public void onEmoticonClick(String bbcode) {
                    mInputField.getText().replace(mInputField.getSelectionStart(),
                            mInputField.getSelectionEnd(), " " + bbcode + " ");
                }
            }));

    /* A BUTTON WHICH SWITCHES BETWEEN SOFT KEYBOARD AND EMOTICON SELECTOR */
    mKeyboardButton = (ImageButton) view.findViewById(R.id.ib_emoticons);
    /* Showing and dismissing popup on clicking EMOTICONS-BUTTON */
    mKeyboardButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mEmoticonGrid.getVisibility() == View.VISIBLE) {
                mKeyboardButton.setImageResource(R.drawable.ic_action_keyboard_alt_white_24dp);
                mEmoticonGrid.setVisibility(View.GONE);
            } else {
                mKeyboardButton.setImageResource(R.drawable.ic_action_keyboard_arrow_down_white_24dp);
                mEmoticonGrid.setVisibility(View.VISIBLE);
                hideKeyboard();
            }
        }
    });

    /* LIST STUFF */
    RecyclerView recyclerView = (RecyclerView) view.findViewById(android.R.id.list);
    recyclerView
            .addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
    mLayoutManager = new LinearLayoutManager(getActivity());
    mLayoutManager.setStackFromEnd(true);
    recyclerView.setLayoutManager(mLayoutManager);
    mListAdapter = new ChatAdapter(getActivity(), new ArrayList<Post>());
    mListAdapter.setOnItemLongClickListener(this);
    recyclerView.setAdapter(mListAdapter);
    getLoaderManager().initLoader(LOADER_ID_MESSAGES, null, this);

    return view;
}

From source file:com.google.samples.apps.gcmplayground.MyActivity.java

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

    registerButton = (Button) findViewById(R.id.register_button);
    unregisterButton = (Button) findViewById(R.id.unregister_button);
    stringIdentifierField = (EditText) findViewById(R.id.string_identifier);
    registrationTokenFieldView = (TextView) findViewById(R.id.registeration_token);
    statusView = (TextView) findViewById(R.id.status);
    downstreamBundleView = (TextView) findViewById(R.id.downstream_bundle);
    upstreamMessageField = (EditText) findViewById(R.id.upstream_message);
    sendButton = (Button) findViewById(R.id.button_send);
    subscribeTopicButton = (Button) findViewById(R.id.topic_subscribe);
    topicField = (EditText) findViewById(R.id.topic_name);
    progressBar = (ProgressBar) findViewById(R.id.progress_bar);

    gcm = GoogleCloudMessaging.getInstance(this);
    pubSub = GcmPubSub.getInstance(this);

    // If Play Services is not up to date, quit the app.
    checkPlayServices();//from  w  ww  .  j  av a 2  s . co  m

    registerButton.setOnClickListener(this);
    unregisterButton.setOnClickListener(this);
    subscribeTopicButton.setOnClickListener(this);
    sendButton.setOnClickListener(this);

    // Restore from saved instance state
    if (savedInstanceState != null) {
        token = savedInstanceState.getString(RegistrationConstants.EXTRA_KEY_TOKEN, "");
        if (token != "") {
            updateUI("Registration SUCCEEDED", true);
        }
    }

    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean sentToken = intent.getBooleanExtra(RegistrationConstants.SENT_TOKEN_TO_SERVER, false);

            token = intent.getStringExtra(RegistrationConstants.EXTRA_KEY_TOKEN);
            if (!sentToken) {
                updateUI("Registration FAILED", false);
            }
        }
    };

    mDownstreamBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String from = intent.getStringExtra(RegistrationConstants.SENDER_ID);
            Bundle data = intent.getBundleExtra(RegistrationConstants.EXTRA_KEY_BUNDLE);
            String message = data.getString(RegistrationConstants.EXTRA_KEY_MESSAGE);

            Log.d(TAG, "Received from >" + from + "< with >" + data.toString() + "<");
            Log.d(TAG, "Message: " + message);

            String action = data.getString(RegistrationConstants.ACTION);
            String status = data.getString(RegistrationConstants.STATUS);

            if (RegistrationConstants.REGISTER_NEW_CLIENT.equals(action)
                    && RegistrationConstants.STATUS_REGISTERED.equals(status)) {
                progressBar.setVisibility(View.INVISIBLE);
                updateUI("Registration SUCCEEDED", true);
            } else if (RegistrationConstants.UNREGISTER_CLIENT.equals(action)
                    && RegistrationConstants.STATUS_UNREGISTERED.equals(status)) {
                token = "";
                updateUI("Unregistration SUCCEEDED", false);
                showToast("Unregistered!");
            } else {
                downstreamBundleView.setText(data.toString());
            }
        }
    };

    LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
            new IntentFilter(RegistrationConstants.REGISTRATION_COMPLETE));
    LocalBroadcastManager.getInstance(this).registerReceiver(mDownstreamBroadcastReceiver,
            new IntentFilter(RegistrationConstants.NEW_DOWNSTREAM_MESSAGE));

    stringIdentifierField.setText("<a_name_to_recognize_the_device>");
}

From source file:com.tml.sharethem.sender.SHAREthemService.java

@Override
public void onCreate() {
    super.onCreate();
    wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    hotspotControl = HotspotControl.getInstance(getApplicationContext());
    m_notificationStopActionReceiver = new BroadcastReceiver() {
        @Override/*from www  .ja  va2 s . com*/
        public void onReceive(Context context, Intent intent) {
            if (null != intent && WIFI_AP_ACTION_STOP.equals(intent.getAction()))
                disableHotspotAndStop();
        }
    };
    registerReceiver(m_notificationStopActionReceiver, new IntentFilter(WIFI_AP_ACTION_STOP));
    //Start a foreground with message saying 'Initiating Hotspot'. Message is later updated using SHARE_SERVICE_NOTIFICATION_ID
    startForeground(SHARE_SERVICE_NOTIFICATION_ID,
            getShareThemNotification(getString(R.string.p2p_sender_service_init_notification_header), false));
    hotspotCheckHandler = new HotspotChecker(this);
}

From source file:org.openbmap.activities.DialogPreferenceMaps.java

/**
 * Initialises download manager for GINGERBREAD and newer
 *//* w  w w.ja v  a  2 s  .  co  m*/
@SuppressLint("NewApi")
private void initDownloadManager() {

    mDownloadManager = (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);

    mReceiver = new BroadcastReceiver() {
        @SuppressLint("NewApi")
        @Override
        public void onReceive(final Context context, final Intent intent) {
            final String action = intent.getAction();
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                final long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                final DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(downloadId);
                final Cursor c = mDownloadManager.query(query);
                if (c.moveToFirst()) {
                    final int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                    if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
                        // we're not checking download id here, that is done in handleDownloads
                        final String uriString = c
                                .getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                        handleDownloads(uriString);
                    } else {
                        final int reason = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON));
                        Log.e(TAG, "Download failed: " + reason);
                    }
                }
            }
        }
    };

    getContext().registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}

From source file:com.Duo.music.player.NowPlayingQueueActivity.NowPlayingQueueFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    //Inflate the correct layout based on the selected theme.
    mContext = getActivity().getApplicationContext();
    mApp = (Common) mContext;/*w  w w  .  j  ava  2s. c  om*/
    nowPlayingQueueFragment = this;
    sharedPreferences = mContext.getSharedPreferences("com.jams.music.player", Context.MODE_PRIVATE);

    mCursor = mApp.getService().getCursor();
    View rootView = (ViewGroup) inflater.inflate(R.layout.now_playing_queue_layout, container, false);

    receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            updateSongInfo();
        }

    };

    //Notify the application that this fragment is now visible.
    sharedPreferences.edit().putBoolean("NOW_PLAYING_QUEUE_VISIBLE", true).commit();

    //Get the screen's parameters.
    displayMetrics = new DisplayMetrics();
    getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    screenWidth = displayMetrics.widthPixels;
    screenHeight = displayMetrics.heightPixels;

    noMusicPlaying = (TextView) rootView.findViewById(R.id.now_playing_queue_no_music_playing);
    nowPlayingAlbumArt = (ImageView) rootView.findViewById(R.id.now_playing_queue_album_art);
    nowPlayingSongTitle = (TextView) rootView.findViewById(R.id.now_playing_queue_song_title);
    nowPlayingSongArtist = (TextView) rootView.findViewById(R.id.now_playing_queue_song_artist);
    nowPlayingSongContainer = (RelativeLayout) rootView
            .findViewById(R.id.now_playing_queue_current_song_container);

    noMusicPlaying.setTypeface(TypefaceHelper.getTypeface(mContext, "RobotoCondensed-Light"));
    nowPlayingSongTitle.setTypeface(TypefaceHelper.getTypeface(mContext, "RobotoCondensed-Light"));
    nowPlayingSongArtist.setTypeface(TypefaceHelper.getTypeface(mContext, "RobotoCondensed-Light"));

    nowPlayingQueueListView = (DragSortListView) rootView.findViewById(R.id.now_playing_queue_list_view);
    progressBar = (ProgressBar) rootView.findViewById(R.id.now_playing_queue_progressbar);
    playPauseButton = (ImageButton) rootView.findViewById(R.id.now_playing_queue_play);
    nextButton = (ImageButton) rootView.findViewById(R.id.now_playing_queue_next);
    previousButton = (ImageButton) rootView.findViewById(R.id.now_playing_queue_previous);

    //Apply the card layout's background based on the color theme.
    if (sharedPreferences.getString(Common.CURRENT_THEME, "LIGHT_CARDS_THEME").equals("LIGHT_CARDS_THEME")) {
        rootView.setBackgroundColor(0xFFEEEEEE);
        nowPlayingQueueListView.setDivider(getResources().getDrawable(R.drawable.transparent_drawable));
        nowPlayingQueueListView.setDividerHeight(3);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(7, 3, 7, 3);
        nowPlayingQueueListView.setLayoutParams(layoutParams);
    } else if (sharedPreferences.getString(Common.CURRENT_THEME, "LIGHT_CARDS_THEME")
            .equals("DARK_CARDS_THEME")) {
        rootView.setBackgroundColor(0xFF000000);
        nowPlayingQueueListView.setDivider(getResources().getDrawable(R.drawable.transparent_drawable));
        nowPlayingQueueListView.setDividerHeight(3);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(7, 3, 7, 3);
        nowPlayingQueueListView.setLayoutParams(layoutParams);
    }

    //Set the Now Playing container layout's background.
    nowPlayingSongContainer.setBackgroundColor(UIElementsHelper.getNowPlayingQueueBackground(mContext));

    //Loop through the service's cursor and retrieve the current queue's information.
    if (sharedPreferences.getBoolean("SERVICE_RUNNING", false) == false
            || mApp.getService().getCurrentMediaPlayer() == null) {

        //No audio is currently playing.
        noMusicPlaying.setVisibility(View.VISIBLE);
        nowPlayingAlbumArt.setImageBitmap(mApp.decodeSampledBitmapFromResource(R.drawable.default_album_art,
                screenWidth / 3, screenWidth / 3));
        nowPlayingQueueListView.setVisibility(View.GONE);
        nowPlayingSongTitle.setVisibility(View.GONE);
        nowPlayingSongArtist.setVisibility(View.GONE);
        progressBar.setVisibility(View.GONE);

    } else {

        //Set the current play/pause conditions.
        try {

            //Hide the progressBar and display the controls.
            progressBar.setVisibility(View.GONE);
            playPauseButton.setVisibility(View.VISIBLE);
            nextButton.setVisibility(View.VISIBLE);
            previousButton.setVisibility(View.VISIBLE);

            if (mApp.getService().getCurrentMediaPlayer().isPlaying()) {
                playPauseButton.setImageResource(R.drawable.pause_holo_light);
            } else {
                playPauseButton.setImageResource(R.drawable.play_holo_light);
            }
        } catch (Exception e) {
            /* The mediaPlayer hasn't been initialized yet, so let's just keep the controls 
             * hidden for now. Once the mediaPlayer is initialized and it starts playing, 
             * updateSongInfo() will be called, and we can show the controls/hide the progressbar 
             * there. For now though, we'll display the progressBar.
             */
            progressBar.setVisibility(View.VISIBLE);
            playPauseButton.setVisibility(View.GONE);
            nextButton.setVisibility(View.GONE);
            previousButton.setVisibility(View.GONE);
        }

        //Retrieve and set the current title/artist/artwork.
        mCursor.moveToPosition(
                mApp.getService().getPlaybackIndecesList().get(mApp.getService().getCurrentSongIndex()));
        String currentTitle = mCursor.getString(mCursor.getColumnIndex(DBAccessHelper.SONG_TITLE));
        String currentArtist = mCursor.getString(mCursor.getColumnIndex(DBAccessHelper.SONG_ARTIST));

        nowPlayingSongTitle.setText(currentTitle);
        nowPlayingSongArtist.setText(currentArtist);

        File file = new File(mContext.getExternalCacheDir() + "/current_album_art.jpg");
        Bitmap bm = null;
        if (file.exists()) {
            bm = mApp.decodeSampledBitmapFromFile(file, screenWidth, screenHeight);
            nowPlayingAlbumArt.setScaleX(1.0f);
            nowPlayingAlbumArt.setScaleY(1.0f);
        } else {
            int defaultResource = UIElementsHelper.getIcon(mContext, "default_album_art");
            bm = mApp.decodeSampledBitmapFromResource(defaultResource, screenWidth, screenHeight);
            nowPlayingAlbumArt.setScaleX(0.5f);
            nowPlayingAlbumArt.setScaleY(0.5f);
        }

        nowPlayingAlbumArt.setImageBitmap(bm);
        noMusicPlaying.setPaintFlags(
                noMusicPlaying.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);

        nowPlayingSongTitle.setPaintFlags(nowPlayingSongTitle.getPaintFlags() | Paint.ANTI_ALIAS_FLAG
                | Paint.FAKE_BOLD_TEXT_FLAG | Paint.SUBPIXEL_TEXT_FLAG);

        nowPlayingSongArtist.setPaintFlags(
                nowPlayingSongArtist.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);

        /* Set the adapter. We'll pass in playbackIndecesList as the adapter's data backend.
         * The array can then be manipulated (reordered, items removed, etc) with no restrictions. 
         * Each integer element in the array will be used as a pointer to a specific cursor row, 
         * so there's no need to fiddle around with the actual cursor itself. */
        nowPlayingQueueListViewAdapter = new NowPlayingQueueListViewAdapter(getActivity(),
                mApp.getService().getPlaybackIndecesList());

        nowPlayingQueueListView.setAdapter(nowPlayingQueueListViewAdapter);
        nowPlayingQueueListView.setFastScrollEnabled(true);
        nowPlayingQueueListView.setDropListener(onDrop);
        nowPlayingQueueListView.setRemoveListener(onRemove);
        SimpleFloatViewManager simpleFloatViewManager = new SimpleFloatViewManager(nowPlayingQueueListView);
        simpleFloatViewManager.setBackgroundColor(Color.TRANSPARENT);
        nowPlayingQueueListView.setFloatViewManager(simpleFloatViewManager);

        //Scroll down to the current song.
        nowPlayingQueueListView.setSelection(mApp.getService().getCurrentSongIndex());

        nowPlayingQueueListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int index, long arg3) {
                mApp.getService().skipToTrack(index);

            }

        });

        playPauseButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                mApp.getService().togglePlaybackState();
            }

        });

        nextButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mApp.getService().skipToNextTrack();
            }

        });

        previousButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mApp.getService().skipToPreviousTrack();
            }

        });

    }

    return rootView;
}

From source file:eu.power_switch.gui.fragment.configure_receiver.ConfigureReceiverDialogPage1NameFragment.java

@Nullable
@Override//w ww  .  j a  v  a  2  s  .  c  o  m
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.dialog_fragment_configure_receiver_page_1, container, false);

    // BroadcastReceiver to get notifications from background service if room data has changed
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            updateRoomNamesList();

            if (intent.hasExtra("newRoomName")) {
                String newRoomName = intent.getStringExtra("newRoomName");
                roomsListView.setItemChecked(roomNamesAdapter.getPosition(newRoomName), true);
            }
        }
    };

    floatingName = (TextInputLayout) rootView.findViewById(R.id.receiver_name_text_input_layout);
    name = (EditText) rootView.findViewById(R.id.editText_receiver_name);
    name.requestFocus();
    name.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            checkValidity();
        }
    });

    roomsListView = (ListView) rootView.findViewById(R.id.listView_rooms);
    roomNamesAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_single_choice,
            roomList);
    roomsListView.setAdapter(roomNamesAdapter);
    roomsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            checkValidity();
        }
    });

    updateRoomNamesList();

    addRoomFAB = (FloatingActionButton) rootView.findViewById(R.id.add_room_fab);
    addRoomFAB.setImageDrawable(IconicsHelper.getAddIcon(getActivity(),
            ContextCompat.getColor(getActivity(), android.R.color.white)));
    final Fragment fragment = this;
    addRoomFAB.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CreateRoomDialog createRoomDialog = new CreateRoomDialog();
            createRoomDialog.setTargetFragment(fragment, 0);
            createRoomDialog.show(getFragmentManager(), null);
        }
    });

    // TODO: Showcase is rendered behind the Dialog, maybe needs fix in library
    //        MaterialShowcaseView materialShowcaseView = new MaterialShowcaseView.Builder(getActivity())
    //                .setTarget(name)
    //                .setUseAutoRadius(false)
    //                .setRadius(64 * 2)
    //                .setDismissText(getString(R.string.tutorial__got_it))
    //                .setContentText(getString(R.string.tutorial__first_add_room))
    //                .setDelay(500)
    //                .setDismissOnTouch(true)
    ////                .singleUse("tutorial__first_add_room");
    //                .build();
    //        materialShowcaseView.bringToFront();
    //        materialShowcaseView.show(getActivity());

    Bundle args = getArguments();
    if (args != null && args.containsKey(ConfigureReceiverDialog.RECEIVER_ID_KEY)) {
        long receiverId = args.getLong(ConfigureReceiverDialog.RECEIVER_ID_KEY);
        initializeReceiverData(receiverId);
    }
    checkValidity();

    return rootView;
}

From source file:com.jelly.music.player.NowPlayingQueueActivity.NowPlayingQueueFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    //Inflate the correct layout based on the selected theme.
    mContext = getActivity().getApplicationContext();
    mApp = (Common) mContext;//from   ww  w. jav  a  2s . c om
    nowPlayingQueueFragment = this;
    sharedPreferences = mContext.getSharedPreferences("com.jelly.music.player", Context.MODE_PRIVATE);

    mCursor = mApp.getService().getCursor();
    View rootView = (ViewGroup) inflater.inflate(R.layout.now_playing_queue_layout, container, false);

    receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            updateSongInfo();
        }

    };

    //Notify the application that this fragment is now visible.
    sharedPreferences.edit().putBoolean("NOW_PLAYING_QUEUE_VISIBLE", true).commit();

    //Get the screen's parameters.
    displayMetrics = new DisplayMetrics();
    getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    screenWidth = displayMetrics.widthPixels;
    screenHeight = displayMetrics.heightPixels;

    noMusicPlaying = (TextView) rootView.findViewById(R.id.now_playing_queue_no_music_playing);
    nowPlayingAlbumArt = (ImageView) rootView.findViewById(R.id.now_playing_queue_album_art);
    nowPlayingSongTitle = (TextView) rootView.findViewById(R.id.now_playing_queue_song_title);
    nowPlayingSongArtist = (TextView) rootView.findViewById(R.id.now_playing_queue_song_artist);
    nowPlayingSongContainer = (RelativeLayout) rootView
            .findViewById(R.id.now_playing_queue_current_song_container);

    noMusicPlaying.setTypeface(TypefaceHelper.getTypeface(mContext, "RobotoCondensed-Light"));
    nowPlayingSongTitle.setTypeface(TypefaceHelper.getTypeface(mContext, "RobotoCondensed-Light"));
    nowPlayingSongArtist.setTypeface(TypefaceHelper.getTypeface(mContext, "RobotoCondensed-Light"));

    nowPlayingQueueListView = (DragSortListView) rootView.findViewById(R.id.now_playing_queue_list_view);
    progressBar = (ProgressBar) rootView.findViewById(R.id.now_playing_queue_progressbar);
    playPauseButton = (ImageButton) rootView.findViewById(R.id.now_playing_queue_play);
    nextButton = (ImageButton) rootView.findViewById(R.id.now_playing_queue_next);
    previousButton = (ImageButton) rootView.findViewById(R.id.now_playing_queue_previous);

    //Apply the card layout's background based on the color theme.
    if (sharedPreferences.getString(Common.CURRENT_THEME, "LIGHT_CARDS_THEME").equals("LIGHT_CARDS_THEME")) {
        rootView.setBackgroundColor(0xFFEEEEEE);
        nowPlayingQueueListView.setDivider(getResources().getDrawable(R.drawable.transparent_drawable));
        nowPlayingQueueListView.setDividerHeight(3);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(7, 3, 7, 3);
        nowPlayingQueueListView.setLayoutParams(layoutParams);
    } else if (sharedPreferences.getString(Common.CURRENT_THEME, "LIGHT_CARDS_THEME")
            .equals("DARK_CARDS_THEME")) {
        rootView.setBackgroundColor(0xFF000000);
        nowPlayingQueueListView.setDivider(getResources().getDrawable(R.drawable.transparent_drawable));
        nowPlayingQueueListView.setDividerHeight(3);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(7, 3, 7, 3);
        nowPlayingQueueListView.setLayoutParams(layoutParams);
    }

    //Set the Now Playing container layout's background.
    nowPlayingSongContainer.setBackgroundColor(UIElementsHelper.getNowPlayingQueueBackground(mContext));

    //Loop through the service's cursor and retrieve the current queue's information.
    if (sharedPreferences.getBoolean("SERVICE_RUNNING", false) == false
            || mApp.getService().getCurrentMediaPlayer() == null) {

        //No audio is currently playing.
        noMusicPlaying.setVisibility(View.VISIBLE);
        nowPlayingAlbumArt.setImageBitmap(mApp.decodeSampledBitmapFromResource(R.drawable.default_album_art,
                screenWidth / 3, screenWidth / 3));
        nowPlayingQueueListView.setVisibility(View.GONE);
        nowPlayingSongTitle.setVisibility(View.GONE);
        nowPlayingSongArtist.setVisibility(View.GONE);
        progressBar.setVisibility(View.GONE);

    } else {

        //Set the current play/pause conditions.
        try {

            //Hide the progressBar and display the controls.
            progressBar.setVisibility(View.GONE);
            playPauseButton.setVisibility(View.VISIBLE);
            nextButton.setVisibility(View.VISIBLE);
            previousButton.setVisibility(View.VISIBLE);

            if (mApp.getService().getCurrentMediaPlayer().isPlaying()) {
                playPauseButton.setImageResource(R.drawable.pause_holo_light);
            } else {
                playPauseButton.setImageResource(R.drawable.play_holo_light);
            }
        } catch (Exception e) {
            /* The mediaPlayer hasn't been initialized yet, so let's just keep the controls 
             * hidden for now. Once the mediaPlayer is initialized and it starts playing, 
             * updateSongInfo() will be called, and we can show the controls/hide the progressbar 
             * there. For now though, we'll display the progressBar.
             */
            progressBar.setVisibility(View.VISIBLE);
            playPauseButton.setVisibility(View.GONE);
            nextButton.setVisibility(View.GONE);
            previousButton.setVisibility(View.GONE);
        }

        //Retrieve and set the current title/artist/artwork.
        mCursor.moveToPosition(
                mApp.getService().getPlaybackIndecesList().get(mApp.getService().getCurrentSongIndex()));
        String currentTitle = mCursor.getString(mCursor.getColumnIndex(DBAccessHelper.SONG_TITLE));
        String currentArtist = mCursor.getString(mCursor.getColumnIndex(DBAccessHelper.SONG_ARTIST));

        nowPlayingSongTitle.setText(currentTitle);
        nowPlayingSongArtist.setText(currentArtist);

        File file = new File(mContext.getExternalCacheDir() + "/current_album_art.jpg");
        Bitmap bm = null;
        if (file.exists()) {
            bm = mApp.decodeSampledBitmapFromFile(file, screenWidth, screenHeight);
            nowPlayingAlbumArt.setScaleX(1.0f);
            nowPlayingAlbumArt.setScaleY(1.0f);
        } else {
            int defaultResource = UIElementsHelper.getIcon(mContext, "default_album_art");
            bm = mApp.decodeSampledBitmapFromResource(defaultResource, screenWidth, screenHeight);
            nowPlayingAlbumArt.setScaleX(0.5f);
            nowPlayingAlbumArt.setScaleY(0.5f);
        }

        nowPlayingAlbumArt.setImageBitmap(bm);
        noMusicPlaying.setPaintFlags(
                noMusicPlaying.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);

        nowPlayingSongTitle.setPaintFlags(nowPlayingSongTitle.getPaintFlags() | Paint.ANTI_ALIAS_FLAG
                | Paint.FAKE_BOLD_TEXT_FLAG | Paint.SUBPIXEL_TEXT_FLAG);

        nowPlayingSongArtist.setPaintFlags(
                nowPlayingSongArtist.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);

        /* Set the adapter. We'll pass in playbackIndecesList as the adapter's data backend.
         * The array can then be manipulated (reordered, items removed, etc) with no restrictions. 
         * Each integer element in the array will be used as a pointer to a specific cursor row, 
         * so there's no need to fiddle around with the actual cursor itself. */
        nowPlayingQueueListViewAdapter = new NowPlayingQueueListViewAdapter(getActivity(),
                mApp.getService().getPlaybackIndecesList());

        nowPlayingQueueListView.setAdapter(nowPlayingQueueListViewAdapter);
        nowPlayingQueueListView.setFastScrollEnabled(true);
        nowPlayingQueueListView.setDropListener(onDrop);
        nowPlayingQueueListView.setRemoveListener(onRemove);
        SimpleFloatViewManager simpleFloatViewManager = new SimpleFloatViewManager(nowPlayingQueueListView);
        simpleFloatViewManager.setBackgroundColor(Color.TRANSPARENT);
        nowPlayingQueueListView.setFloatViewManager(simpleFloatViewManager);

        //Scroll down to the current song.
        nowPlayingQueueListView.setSelection(mApp.getService().getCurrentSongIndex());

        nowPlayingQueueListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int index, long arg3) {
                mApp.getService().skipToTrack(index);

            }

        });

        playPauseButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                mApp.getService().togglePlaybackState();
            }

        });

        nextButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mApp.getService().skipToNextTrack();
            }

        });

        previousButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mApp.getService().skipToPreviousTrack();
            }

        });

    }

    return rootView;
}

From source file:fm.krui.kruifm.StreamActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.stream_layout);

    // Instantiate class members
    prefManager = new PreferenceManager(this);
    favTrackManager = new FavoriteTrackManager(this);

    stationTag = getIntent().getIntExtra(KEY_STATION_TAG, -1);

    // Set ActionBar Title
    ActionBar actionBar = getActionBar();
    actionBar.setTitle(getString(R.string.listen_sidebar));
    actionBar.setSubtitle(getActivitySubtitle(getIntent()));

    // FIXME: Move these to PreferenceManager after expanding its scope for cleaner code
    trackPrefs = this.getSharedPreferences(StreamService.PREFS_NAME, 0);

    // Instantiate broadcast receiver
    broadcastReceiver = new BroadcastReceiver() {
        @Override// www .  j  a va 2s.  com
        public void onReceive(Context context, Intent intent) {
            processBroadcastCommand(intent);
        }
    };

    // Retrieve player state to determine how to build this activity
    boolean playerState = prefManager.getPlayerState();

    // If audio is playing in StreamService, we don't want to rebuffer, and we want to restore the UI state from the cache.
    if (playerState) {
        restoreUIState();
    }

    // If audio is NOT playing, buffer and treat this launch like a clean startup.
    else {
        // Determine the URL we need to use to stream based on the station tag and quality preferences
        streamUrl = getStreamUrl(stationTag);
        Log.v(TAG, "streamUrl is now set to: " + streamUrl);

        // Perform initial configuration of audio server
        changeUrl(stationTag);

        // Begin buffering the audio
        startAudio((ImageView) this.findViewById(R.id.play_audio_imageview));
    }

    // Build play button listener
    final ImageView playButton = (ImageView) this.findViewById(R.id.play_audio_imageview);
    playButton.setOnClickListener(new View.OnClickListener() {

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

    // Build volume seek bar listener
    // ** DISABLED FOR NOW -- This might be completely thrown out. **
    /*final SeekBar volumeSeekBar = (SeekBar)this.findViewById(R.id.volume_seekbar);
    volumeSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            
    // When seek bar progress is changed, change the audio of the media player appropriately.
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        // Send new volume via intent? Will this be slow?
    }
            
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }
            
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }
    }); */

    // Build settings button listener and apply it to settings icon and submit button
    View.OnClickListener flipListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Card flip animation which toggles between stream controls and settings views
            flipCard();
        }
    };

    final ImageView settingsButton = (ImageView) this.findViewById(R.id.stream_settings_imageview);
    final Button saveSettingsButton = (Button) this.findViewById(R.id.set_stream_settings_button);
    settingsButton.setOnClickListener(flipListener);
    saveSettingsButton.setOnClickListener(flipListener);

    // Build favorite button listener
    final ImageView favoriteButton = (ImageView) this.findViewById(R.id.stream_favorite_imageview);
    favoriteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (trackIsFavorite) {
                favoriteButton.setImageResource(R.drawable.star_unfilled_white);
                trackIsFavorite = false;
                removeTrackFromFavorites();
            } else {
                favoriteButton.setImageResource(R.drawable.star_filled_white);
                trackIsFavorite = true;
                addTrackToFavorites();
            }
        }
    });

    // Build settings switches
    final Switch streamQualitySwitch = (Switch) this.findViewById(R.id.stream_quality_switch);
    final Switch albumArtSwitch = (Switch) this.findViewById(R.id.stream_album_art_switch);

    // Set initial state of switches
    albumArtSwitch.setChecked(prefManager.getAlbumArtDownloadPreference());
    if (prefManager.getStreamQuality() == prefManager.HIGH_QUALITY) {
        streamQualitySwitch.setChecked(true);
    } else {
        streamQualitySwitch.setChecked(false);
    }

    // Assign listeners to switches
    streamQualitySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                prefManager.setStreamQuality(prefManager.HIGH_QUALITY);
                Log.v(TAG, "Stream quality setting is now: " + prefManager.getStreamQuality());
            } else {
                prefManager.setStreamQuality(prefManager.LOW_QUALITY);
                Log.v(TAG, "Stream quality setting is now: " + prefManager.getStreamQuality());
            }
            changeUrl(stationSpinnerPosition);
        }
    });

    albumArtSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                prefManager.setAlbumArtDownloadPreference(true);
                Log.v(TAG, "Album Art Download setting is now " + prefManager.getAlbumArtDownloadPreference());
            } else {
                prefManager.setAlbumArtDownloadPreference(false);
                Log.v(TAG, "Album Art Download setting is now " + prefManager.getAlbumArtDownloadPreference());
            }
        }
    });

    // ***** Old onCreate function starts here!
    // Initialize screen lock/wake receiver
    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    BroadcastReceiver screenReceiver = new ScreenReceiver();

    // Attach it to this activity
    this.getApplicationContext().registerReceiver(screenReceiver, filter);

}

From source file:fm.krui.kruifm.StreamFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // Instantiate class members
    prefManager = new PreferenceManager(getActivity());
    favTrackManager = new FavoriteTrackManager(getActivity());

    // FIXME: Move these to PreferenceManager after expanding its scope for cleaner code
    trackPrefs = getActivity().getSharedPreferences(StreamService.PREFS_NAME, 0);

    // Instantiate broadcast receiver
    broadcastReceiver = new BroadcastReceiver() {
        @Override// w ww.j  a  v  a 2  s  .c o  m
        public void onReceive(Context context, Intent intent) {
            processBroadcastCommand(intent);
        }
    };

    // Determine the URL we need to use to stream based on the station tag and quality preferences
    streamUrl = getStreamUrl(stationTag);
    Log.v(TAG, "streamUrl is now set to: " + streamUrl);

    // Perform initial configuration of audio server
    changeUrl(stationTag);

    // Begin buffering the audio
    startAudio((ImageView) getActivity().findViewById(R.id.play_audio_imageview));

    // Build play button listener
    final ImageView playButton = (ImageView) getActivity().findViewById(R.id.play_audio_imageview);
    playButton.setOnClickListener(new View.OnClickListener() {

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

    // Build volume seek bar listener
    // ** DISABLED FOR NOW -- This might be completely thrown out. **
    /*final SeekBar volumeSeekBar = (SeekBar)getActivity().findViewById(R.id.volume_seekbar);
    volumeSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            
    // When seek bar progress is changed, change the audio of the media player appropriately.
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        // Send new volume via intent? Will this be slow?
    }
            
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }
            
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }
    }); */

    // Build settings button listener and apply it to settings icon and submit button
    View.OnClickListener flipListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Card flip animation which toggles between stream controls and settings views
            flipCard();
        }
    };

    final ImageView settingsButton = (ImageView) getActivity().findViewById(R.id.stream_settings_imageview);
    final Button saveSettingsButton = (Button) getActivity().findViewById(R.id.set_stream_settings_button);
    settingsButton.setOnClickListener(flipListener);
    saveSettingsButton.setOnClickListener(flipListener);

    // Build favorite button listener
    final ImageView favoriteButton = (ImageView) getActivity().findViewById(R.id.stream_favorite_imageview);
    favoriteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (trackIsFavorite) {
                favoriteButton.setImageResource(R.drawable.star_unfilled_white);
                trackIsFavorite = false;
                removeTrackFromFavorites();
            } else {
                favoriteButton.setImageResource(R.drawable.star_filled_white);
                trackIsFavorite = true;
                addTrackToFavorites();
            }
        }
    });

    // Build settings switches
    final Switch streamQualitySwitch = (Switch) getActivity().findViewById(R.id.stream_quality_switch);
    final Switch albumArtSwitch = (Switch) getActivity().findViewById(R.id.stream_album_art_switch);

    // Set initial state of switches
    albumArtSwitch.setChecked(prefManager.getAlbumArtDownloadPreference());
    if (prefManager.getStreamQuality() == prefManager.HIGH_QUALITY) {
        streamQualitySwitch.setChecked(true);
    } else {
        streamQualitySwitch.setChecked(false);
    }

    // Assign listeners to switches
    streamQualitySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                prefManager.setStreamQuality(prefManager.HIGH_QUALITY);
                Log.v(TAG, "Stream quality setting is now: " + prefManager.getStreamQuality());
            } else {
                prefManager.setStreamQuality(prefManager.LOW_QUALITY);
                Log.v(TAG, "Stream quality setting is now: " + prefManager.getStreamQuality());
            }
            changeUrl(stationSpinnerPosition);
        }
    });

    albumArtSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                prefManager.setAlbumArtDownloadPreference(true);
                Log.v(TAG, "Album Art Download setting is now " + prefManager.getAlbumArtDownloadPreference());
            } else {
                prefManager.setAlbumArtDownloadPreference(false);
                Log.v(TAG, "Album Art Download setting is now " + prefManager.getAlbumArtDownloadPreference());
            }
        }
    });

}

From source file:digital.dispatch.TaxiLimoNewUI.GCM.CommonUtilities.java

public static BroadcastReceiver getGenericReceiver(final Context ctx, final boolean isTrackDetail) {
    final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
        @Override/*from   www . j a  va  2  s .  c o  m*/
        public void onReceive(Context context, Intent intent) {
            if (intent.filterEquals(new Intent(gcmType.message.toString()))) {
                // get gcm notification ID to remove notification once read by user
                String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
                final int gcmID = intent.getIntExtra(GCM_ID, -1);

                AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
                builder.setTitle(R.string.gcm);
                builder.setMessage(newMessage);
                builder.setCancelable(false);

                // Create the AlertDialog object and return it
                builder.create();

                // clear late trip notification list once displayed
                SharedPreferences sharedPref = ctx.getSharedPreferences("mobile_booker", 0);
                SharedPreferences.Editor prefEditor = sharedPref.edit();
                final String lateID = sharedPref.getString(LATE_TRIP_TRID, "");

                if (!lateID.equalsIgnoreCase("")) {
                    DaoManager daoManager = DaoManager.getInstance(ctx);
                    DBBookingDao bookingDao = daoManager.getDBBookingDao(DaoManager.TYPE_WRITE);
                    final DBBooking dbBook = bookingDao.queryBuilder().where(Properties.Taxi_ride_id.eq(lateID))
                            .list().get(0);

                    builder.setPositiveButton(R.string.late_trip_wait, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            removeNotification(gcmID, ctx);

                        }
                    }).setNegativeButton(R.string.late_trip_no_wait, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            new CancelJobTask(ctx, dbBook).execute();
                            removeNotification(gcmID, ctx);
                        }
                    });

                    prefEditor.putString(LATE_TRIP_TRID, "");
                    prefEditor.commit();
                } else {
                    builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            removeNotification(gcmID, ctx);
                            if (isTrackDetail)
                                ((TrackDetailActivity) ctx).startRecallJobTask();
                            if (ctx instanceof MainActivity) {
                                if (((MainActivity) ctx).trackFragment.isAdded())
                                    ((MainActivity) ctx).trackFragment.startRecallJobTask();
                            }
                        }
                    });
                }
                try {
                    builder.create().show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    return mHandleMessageReceiver;
}