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.scooter1556.sms.android.service.MediaService.java

private void registerCarConnectionReceiver() {
    IntentFilter filter = new IntentFilter(AutoUtils.ACTION_MEDIA_STATUS);

    carConnectionReceiver = new BroadcastReceiver() {
        @Override/*from  www . j  av  a 2 s.  c  o m*/
        public void onReceive(Context context, Intent intent) {
            String connectionEvent = intent.getStringExtra(AutoUtils.MEDIA_CONNECTION_STATUS);
            isConnectedToCar = AutoUtils.MEDIA_CONNECTED.equals(connectionEvent);
            Log.i(TAG, "Connection event to Android Auto: " + connectionEvent + " isConnectedToCar="
                    + isConnectedToCar);
        }
    };

    registerReceiver(carConnectionReceiver, filter);
}

From source file:com.urgoo.message.activities.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/*w  ww  .j  a v a2s. co  m*/
        public void onReceive(Context context, Intent intent) {
            updateUnreadAddressLable();
            if (currentTabIndex == 0) {
                // ??????
                //                    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.mk4droid.IMC_Activities.Fragment_List.java

private void HandlersAndReceivers() {

    handlerBroadcastListRefresh = new Handler() // Broadcast  2. DistanceCh 3. IssuesNoCh
    {/*ww  w  .  ja v  a 2  s . c  o m*/
        public void handleMessage(Message msg) {
            InitList();
            super.handleMessage(msg);
        }
    };

    // --------- Broadcast that refresh is needed
    handlerBroadcastRefresh = new Handler() // Broadcast  2. DistanceCh 3. IssuesNoCh
    {
        public void handleMessage(Message msg) {
            if (msg.arg1 == 2)
                ctx.sendBroadcast(
                        new Intent("android.intent.action.MAIN").putExtra("DistanceChanged", "Indeed"));
            else if (msg.arg1 == 3)
                ctx.sendBroadcast(new Intent("android.intent.action.MAIN").putExtra("IssuesNoChanged", "yep"));

            super.handleMessage(msg);
        }
    };

    //---------- Upon Data Changed start updating the UI
    intentFilter = new IntentFilter("android.intent.action.MAIN"); // DataCh

    mReceiverDataChanged = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String DataChanged = intent.getStringExtra("DataChanged");

            if (DataChanged != null) {
                handlerBroadcastListRefresh.sendMessage(new Message());
            }
        }
    };

    if (!isReg_mReceiverDataChanged) {
        getActivity().registerReceiver(mReceiverDataChanged, intentFilter);
        isReg_mReceiverDataChanged = true;
    }
}

From source file:at.alladin.rmbt.android.main.RMBTMainActivity.java

/**
* 
*//*  www  .j  a  v  a2 s.  c om*/
@Override
public void onCreate(final Bundle savedInstanceState) {
    //Log.i("MAIN ACTIVITY", "onCreate");
    restoreInstance(savedInstanceState);
    super.onCreate(savedInstanceState);
    NetworkInfoCollector.init(this);
    networkInfoCollector = NetworkInfoCollector.getInstance();

    preferencesUpdate();
    setContentView(R.layout.main_with_navigation_drawer);

    if (VIEW_HIERARCHY_SERVER_ENABLED) {
        ViewServer.get(this).addWindow(this);
    }

    ActionBar actionBar = getActionBar();
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);
    actionBar.setDisplayUseLogoEnabled(true);

    // initialize the navigation drawer with the main menu list adapter:
    String[] mainTitles = getResources().getStringArray(R.array.navigation_main_titles);
    int[] navIcons = new int[] { R.drawable.ic_action_home, R.drawable.ic_action_history,
            R.drawable.ic_action_map, R.drawable.ic_action_stat, R.drawable.ic_action_help,
            R.drawable.ic_action_about, R.drawable.ic_action_settings, R.drawable.ic_action_about };

    MainMenuListAdapter mainMenuAdapter = new MainMenuListAdapter(this, mainTitles, navIcons);

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerList = (ListView) findViewById(R.id.left_drawer);
    drawerLayout.setBackgroundResource(R.drawable.ic_drawer);

    drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer,
            R.string.page_title_title_page, R.string.page_title_title_page) {

        /** Called when a drawer has settled in a completely closed state. */
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
            //refreshActionBar(null);
            exitAfterDrawerClose = false;
        }

        /** Called when a drawer has settled in a completely open state. */
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
        }
    };

    drawerLayout.setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (KeyEvent.KEYCODE_BACK == event.getKeyCode() && exitAfterDrawerClose) {
                onBackPressed();
                return true;
            }
            return false;
        }
    });
    drawerLayout.setDrawerListener(drawerToggle);
    drawerList.setAdapter(mainMenuAdapter);
    drawerList.setOnItemClickListener(new OnItemClickListener() {
        final int[] menuIds = new int[] { R.id.action_title_page, R.id.action_history, R.id.action_map,
                R.id.action_stats, R.id.action_help, R.id.action_info, R.id.action_settings,
                R.id.action_netstat, R.id.action_log };

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectMenuItem(menuIds[position]);
            drawerLayout.closeDrawers();
        }
    });

    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeButtonEnabled(true);

    // Do something against banding effect in gradients
    // Dither flag might mess up on certain devices??
    final Window window = getWindow();
    window.setFormat(PixelFormat.RGBA_8888);
    window.addFlags(WindowManager.LayoutParams.FLAG_DITHER);

    // Setzt Default-Werte, wenn noch keine Werte vorhanden
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    final String uuid = ConfigHelper.getUUID(getApplicationContext());

    fm = getFragmentManager();
    final Fragment fragment = fm.findFragmentById(R.id.fragment_content);
    if (!ConfigHelper.isTCAccepted(this)) {
        if (fragment != null && fm.getBackStackEntryCount() >= 1)
            // clear fragment back stack
            fm.popBackStack(fm.getBackStackEntryAt(0).getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);

        getActionBar().hide();
        setLockNavigationDrawer(true);

        showTermsCheck();
    } else {
        currentMapOptions.put("highlight", uuid);
        if (fragment == null) {
            if (false) // deactivated for si // ! ConfigHelper.isNDTDecisionMade(this))
            {
                showTermsCheck();
                showNdtCheck();
            } else
                initApp(true);
        }
    }

    geoLocation = new MainGeoLocation(getApplicationContext());

    mNetworkStateChangedFilter = new IntentFilter();
    mNetworkStateChangedFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);

    mNetworkStateIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(final Context context, final Intent intent) {
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                final boolean connected = !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
                        false);
                final boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

                if (connected) {
                    if (networkInfoCollector != null) {
                        networkInfoCollector.setHasConnectionFromAndroidApi(true);
                    }
                } else {
                    if (networkInfoCollector != null) {
                        networkInfoCollector.setHasConnectionFromAndroidApi(false);
                    }
                }

                Log.i(DEBUG_TAG, "CONNECTED: " + connected + " FAILOVER: " + isFailover);
            }
        }
    };
}

From source file:com.appsimobile.appsii.module.calls.CallLogLoader.java

/**
 * Handles a request to start the Loader.
 *//*from   w  ww .  ja  v  a 2s .com*/
@Override
protected void onStartLoading() {
    AppInjector.inject(this);
    if (mCallLogEntries != null) {
        // If we currently have a result available, deliver it
        // immediately.
        deliverResult(mCallLogEntries);
    }

    // Start watching for changes in the app data.
    if (mCallLogObserver == null) {
        mCallLogObserver = new ContentObserver(new Handler()) {
            @Override
            public void onChange(boolean selfChange) {
                onChange(selfChange, null);
            }

            @Override
            public void onChange(boolean selfChange, Uri uri) {
                onContentChanged();
            }
        };
        getContext().getContentResolver().registerContentObserver(CallLog.Calls.CONTENT_URI, true,
                mCallLogObserver);
    }

    mPermissionGrantedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int req = intent.getIntExtra(PermissionUtils.EXTRA_REQUEST_CODE, 0);
            if (req == PermissionUtils.REQUEST_CODE_PERMISSION_READ_CALL_LOG) {
                onContentChanged();
            }
        }
    };
    IntentFilter filter2 = new IntentFilter(PermissionUtils.ACTION_PERMISSION_RESULT);
    getContext().registerReceiver(mPermissionGrantedReceiver, filter2);

    // Has something interesting in the configuration changed since we
    // last built the app list?

    if (takeContentChanged() || mCallLogEntries == null) {
        // If the data has changed since the last time it was loaded
        // or is not currently available, start a load.
        forceLoad();
    }
}

From source file:com.android.mail.browse.ConversationItemView.java

private static synchronized void getItemViewResources(Context context) {
    if (sConfigurationChangedReceiver == null) {
        sConfigurationChangedReceiver = new BroadcastReceiver() {
            @Override//from   w w w. j av a  2  s  .com
            public void onReceive(Context context, Intent intent) {
                STAR_OFF = null;
                getItemViewResources(context);
            }
        };
        context.registerReceiver(sConfigurationChangedReceiver,
                new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED));
    }
    if (STAR_OFF == null) {
        final Resources res = context.getResources();
        // Initialize static bitmaps.
        STAR_OFF = BitmapFactory.decodeResource(res, R.drawable.ic_star_outline_20dp);
        STAR_ON = BitmapFactory.decodeResource(res, R.drawable.ic_star_20dp);
        ATTACHMENT = BitmapFactory.decodeResource(res, R.drawable.ic_attach_file_18dp);
        ONLY_TO_ME = BitmapFactory.decodeResource(res, R.drawable.ic_email_caret_double);
        TO_ME_AND_OTHERS = BitmapFactory.decodeResource(res, R.drawable.ic_email_caret_single);
        IMPORTANT_ONLY_TO_ME = BitmapFactory.decodeResource(res,
                R.drawable.ic_email_caret_double_important_unread);
        IMPORTANT_TO_ME_AND_OTHERS = BitmapFactory.decodeResource(res,
                R.drawable.ic_email_caret_single_important_unread);
        IMPORTANT = BitmapFactory.decodeResource(res, R.drawable.ic_email_caret_none_important_unread);
        STATE_REPLIED = BitmapFactory.decodeResource(res, R.drawable.ic_badge_reply_holo_light);
        STATE_FORWARDED = BitmapFactory.decodeResource(res, R.drawable.ic_badge_forward_holo_light);
        STATE_REPLIED_AND_FORWARDED = BitmapFactory.decodeResource(res,
                R.drawable.ic_badge_reply_forward_holo_light);
        STATE_CALENDAR_INVITE = BitmapFactory.decodeResource(res, R.drawable.ic_badge_invite_holo_light);
        FOCUSED_CONVERSATION_HIGHLIGHT = res.getDrawable(R.drawable.visible_conversation_highlight);

        // Initialize colors.
        sActivatedTextSpan = CharacterStyle
                .wrap(new ForegroundColorSpan(res.getColor(R.color.senders_text_color)));
        sSendersTextColor = res.getColor(R.color.senders_text_color);
        sSubjectTextUnreadSpan = new TextAppearanceSpan(context, R.style.SubjectAppearanceUnreadStyle);
        sSubjectTextReadSpan = new TextAppearanceSpan(context, R.style.SubjectAppearanceReadStyle);

        sBadgeTextSpan = new TextAppearanceSpan(context, R.style.BadgeTextStyle);
        sBadgeBackgroundSpan = new BackgroundColorSpan(res.getColor(R.color.badge_background_color));
        sDateTextColorRead = res.getColor(R.color.date_text_color_read);
        sDateTextColorUnread = res.getColor(R.color.date_text_color_unread);
        sStarTouchSlop = res.getDimensionPixelSize(R.dimen.star_touch_slop);
        sSenderImageTouchSlop = res.getDimensionPixelSize(R.dimen.sender_image_touch_slop);
        sShrinkAnimationDuration = res.getInteger(R.integer.shrink_animation_duration);
        sSlideAnimationDuration = res.getInteger(R.integer.slide_animation_duration);
        // Initialize static color.
        sSendersSplitToken = res.getString(R.string.senders_split_token);
        sElidedPaddingToken = res.getString(R.string.elided_padding_token);
        sScrollSlop = res.getInteger(R.integer.swipeScrollSlop);
        sFoldersMaxCount = res.getInteger(R.integer.conversation_list_max_folder_count);
        sCabAnimationDuration = res.getInteger(R.integer.conv_item_view_cab_anim_duration);
        sBadgePaddingExtraWidth = res.getDimensionPixelSize(R.dimen.badge_padding_extra_width);
        sBadgeRoundedCornerRadius = res.getDimensionPixelSize(R.dimen.badge_rounded_corner_radius);
        sDividerPaint.setColor(res.getColor(R.color.divider_color));
        sDividerHeight = res.getDimensionPixelSize(R.dimen.divider_height);
    }
}

From source file:com.cssweb.android.base.BaseActivity.java

private void listenScreen() {
    lockreceiver = new BroadcastReceiver() {

        @Override/*from  w  w w.j a v a  2s.c  o  m*/
        public void onReceive(Context context, Intent intent) {

            ServiceControl.pauseScreenReceiver();
        }
    };
    registerReceiver(lockreceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));
    homereceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            ServiceControl.resumeScreenReceiver();
        }
    };
    registerReceiver(homereceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));

}

From source file:com.google.codelabs.appauth.MainActivity.java

private void registerRestrictionsReceiver() {
    IntentFilter restrictionsFilter = new IntentFilter(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);

    mRestrictionsReceiver = new BroadcastReceiver() {
        @Override//from  w w  w .  j  a v a2  s .c  om
        public void onReceive(Context context, Intent intent) {
            getAppRestrictions();
        }
    };

    registerReceiver(mRestrictionsReceiver, restrictionsFilter);
}

From source file:eu.power_switch.gui.fragment.settings.GeneralSettingsFragment.java

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

    final Fragment fragment = this;

    CompoundButton.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override/*from w  ww .  j ava  2 s. co m*/
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            switch (buttonView.getId()) {
            case R.id.checkBox_autoDiscover:
                SmartphonePreferencesHandler.setAutoDiscover(isChecked);
                break;
            case R.id.checkBox_autoCollapseRooms:
                SmartphonePreferencesHandler.setAutoCollapseRooms(isChecked);
                break;
            case R.id.checkBox_autoCollapseTimers:
                SmartphonePreferencesHandler.setAutoCollapseTimers(isChecked);
                break;
            case R.id.checkBox_showRoomAllOnOffButtons:
                SmartphonePreferencesHandler.setShowRoomAllOnOff(isChecked);
                break;
            case R.id.checkBox_hideAddFAB:
                SmartphonePreferencesHandler.setUseOptionsMenuInsteadOfFAB(isChecked);
                break;
            case R.id.checkBox_vibrateOnButtonPress:
                SmartphonePreferencesHandler.setVibrateOnButtonPress(isChecked);
                if (isChecked) {
                    vibrationDurationLayout.setVisibility(View.VISIBLE);
                } else {
                    vibrationDurationLayout.setVisibility(View.GONE);
                }
                break;
            case R.id.checkBox_highlightLastActivatedButton:
                SmartphonePreferencesHandler.setHighlightLastActivatedButton(isChecked);
                // force receiver widget update
                ReceiverWidgetProvider.forceWidgetUpdate(getContext());
                break;
            default:
                break;
            }
        }
    };

    // setup hidden developer menu
    TextView generalSettingsTextView = (TextView) rootView.findViewById(R.id.TextView_generalSettings);
    generalSettingsTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Calendar currentTime = Calendar.getInstance();
            if (devMenuFirstClickTime != null) {
                Calendar latestTime = Calendar.getInstance();
                latestTime.setTime(devMenuFirstClickTime.getTime());
                latestTime.add(Calendar.SECOND, 5);
                if (currentTime.after(latestTime)) {
                    devMenuClickCounter = 0;
                }
            }

            devMenuClickCounter++;
            if (devMenuClickCounter == 1) {
                devMenuFirstClickTime = currentTime;
            }
            if (devMenuClickCounter >= 5) {
                devMenuClickCounter = 0;

                DeveloperOptionsDialog developerOptionsDialog = new DeveloperOptionsDialog();
                developerOptionsDialog.show(getActivity().getSupportFragmentManager(), null);
            }
        }
    });

    startupDefaultTab = (Spinner) rootView.findViewById(R.id.spinner_startupDefaultTab);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(), R.array.main_tab_names,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    startupDefaultTab.setAdapter(adapter);
    startupDefaultTab.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            SmartphonePreferencesHandler.setStartupDefaultTab(position);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    autoDiscover = (CheckBox) rootView.findViewById(R.id.checkBox_autoDiscover);
    autoDiscover.setOnCheckedChangeListener(onCheckedChangeListener);

    autoCollapseRooms = (CheckBox) rootView.findViewById(R.id.checkBox_autoCollapseRooms);
    autoCollapseRooms.setOnCheckedChangeListener(onCheckedChangeListener);

    autoCollapseTimers = (CheckBox) rootView.findViewById(R.id.checkBox_autoCollapseTimers);
    autoCollapseTimers.setOnCheckedChangeListener(onCheckedChangeListener);

    showRoomAllOnOffButtons = (CheckBox) rootView.findViewById(R.id.checkBox_showRoomAllOnOffButtons);
    showRoomAllOnOffButtons.setOnCheckedChangeListener(onCheckedChangeListener);

    hideAddFAB = (CheckBox) rootView.findViewById(R.id.checkBox_hideAddFAB);
    hideAddFAB.setOnCheckedChangeListener(onCheckedChangeListener);

    highlightLastActivatedButton = (CheckBox) rootView.findViewById(R.id.checkBox_highlightLastActivatedButton);
    highlightLastActivatedButton.setOnCheckedChangeListener(onCheckedChangeListener);

    vibrateOnButtonPress = (CheckBox) rootView.findViewById(R.id.checkBox_vibrateOnButtonPress);
    vibrateOnButtonPress.setOnCheckedChangeListener(onCheckedChangeListener);

    vibrationDurationLayout = (LinearLayout) rootView.findViewById(R.id.linearLayout_vibrationDuration);
    vibrationDuration = (EditText) rootView.findViewById(R.id.editText_vibrationDuration);
    vibrationDuration.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s != null && s.length() > 0) {
                SmartphonePreferencesHandler.setVibrationDuration(Integer.valueOf(s.toString()));
            }
        }
    });

    keepHistoryDuration = (Spinner) rootView.findViewById(R.id.spinner_keep_history);
    ArrayAdapter<CharSequence> adapterHistory = ArrayAdapter.createFromResource(getContext(),
            R.array.keep_history_selection_names, android.R.layout.simple_spinner_item);
    adapterHistory.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    keepHistoryDuration.setAdapter(adapterHistory);
    keepHistoryDuration.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            SmartphonePreferencesHandler.setKeepHistoryDuration(position);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    textView_backupPath = (TextView) rootView.findViewById(R.id.textView_backupPath);

    Button button_changeBackupPath = (Button) rootView.findViewById(R.id.button_changeBackupPath);
    button_changeBackupPath.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!PermissionHelper.isWriteExternalStoragePermissionAvailable(getContext())) {
                Snackbar snackbar = Snackbar.make(rootView, R.string.missing_external_storage_permission,
                        Snackbar.LENGTH_LONG);
                snackbar.setAction(R.string.grant, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ActivityCompat.requestPermissions(MainActivity.getActivity(),
                                new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                PermissionConstants.REQUEST_CODE_STORAGE_PERMISSION);
                    }
                });
                snackbar.show();
            }

            PathChooserDialog pathChooserDialog = PathChooserDialog.newInstance();
            pathChooserDialog.setTargetFragment(fragment, 0);
            pathChooserDialog.show(getActivity().getSupportFragmentManager(), null);
        }
    });

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.radioButton_darkBlue:
                SmartphonePreferencesHandler.setTheme(SettingsConstants.THEME_DARK_BLUE);
                break;
            case R.id.radioButton_lightBlue:
                SmartphonePreferencesHandler.setTheme(SettingsConstants.THEME_LIGHT_BLUE);
                break;
            case R.id.radioButton_dayNight_blue:
                SmartphonePreferencesHandler.setTheme(SettingsConstants.THEME_DAY_NIGHT_BLUE);
                break;
            default:
                break;
            }

            getActivity().finish();
            Intent intent = new Intent(getContext(), MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    };

    radioButtonDarkBlue = (RadioButton) rootView.findViewById(R.id.radioButton_darkBlue);
    radioButtonDarkBlue.setOnClickListener(onClickListener);

    radioButtonLightBlue = (RadioButton) rootView.findViewById(R.id.radioButton_lightBlue);
    radioButtonLightBlue.setOnClickListener(onClickListener);

    radioButtonDayNightBlue = (RadioButton) rootView.findViewById(R.id.radioButton_dayNight_blue);
    radioButtonDayNightBlue.setOnClickListener(onClickListener);

    sendLogsProgress = (ProgressBar) rootView.findViewById(R.id.sendLogsProgress);
    sendLogs = (Button) rootView.findViewById(R.id.button_sendLogs);
    sendLogs.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sendLogs.setEnabled(false);
            sendLogsProgress.setVisibility(View.VISIBLE);

            new AsyncTask<Void, Void, AsyncTaskResult<Boolean>>() {
                @Override
                protected AsyncTaskResult<Boolean> doInBackground(Void... params) {
                    try {
                        LogHandler.sendLogsAsMail(getContext());
                        return new AsyncTaskResult<>(true);
                    } catch (Exception e) {
                        return new AsyncTaskResult<>(e);
                    }
                }

                @Override
                protected void onPostExecute(AsyncTaskResult<Boolean> booleanAsyncTaskResult) {

                    if (booleanAsyncTaskResult.isSuccess()) {
                        // all is good
                    } else {
                        if (booleanAsyncTaskResult.getException() instanceof MissingPermissionException) {
                            Snackbar snackbar = Snackbar.make(rootView,
                                    R.string.missing_external_storage_permission, Snackbar.LENGTH_LONG);
                            snackbar.setAction(R.string.grant, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    ActivityCompat.requestPermissions(MainActivity.getActivity(),
                                            new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                            PermissionConstants.REQUEST_CODE_STORAGE_PERMISSION);
                                }
                            });
                            snackbar.show();
                        } else {
                            StatusMessageHandler.showErrorMessage(getContext(),
                                    booleanAsyncTaskResult.getException());
                        }
                    }

                    sendLogs.setEnabled(true);
                    sendLogsProgress.setVisibility(View.GONE);
                }
            }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
    });

    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(this, "received intent: " + intent.getAction());
            updateUI();
        }
    };

    return rootView;
}

From source file:com.tonyodev.fetch.FetchService.java

private void pause(final long id) {

    if (activeDownloads.containsKey(id)) {

        runningTask = true;/*from w  w w.  ja v  a 2s  . co m*/

        BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                if (FetchRunnable.getIdFromIntent(intent) == id) {
                    pauseAction(id);

                    broadcastManager.unregisterReceiver(this);
                    registeredReceivers.remove(this);
                    runningTask = false;
                    startDownload();
                }
            }
        };

        registeredReceivers.add(broadcastReceiver);
        broadcastManager.registerReceiver(broadcastReceiver, FetchRunnable.getDoneFilter());
        interruptActiveDownload(id);
    } else {

        pauseAction(id);
        startDownload();
    }
}