Example usage for android.os AsyncTask THREAD_POOL_EXECUTOR

List of usage examples for android.os AsyncTask THREAD_POOL_EXECUTOR

Introduction

In this page you can find the example usage for android.os AsyncTask THREAD_POOL_EXECUTOR.

Prototype

Executor THREAD_POOL_EXECUTOR

To view the source code for android.os AsyncTask THREAD_POOL_EXECUTOR.

Click Source Link

Document

An Executor that can be used to execute tasks in parallel.

Usage

From source file:com.aegiswallet.actions.MainActivity.java

private void doDrawerSetup() {
    mTitle = mDrawerTitle = getTitle();//w w w. j  a  v  a 2s . c  o  m

    drawerOptions = getResources().getStringArray(R.array.drawer_items);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    if (wallet.isEncrypted()) {
        drawerOptions[3] = getString(R.string.drawer_wallet_decrypt);
    } else {
        drawerOptions[3] = getString(R.string.drawer_wallet_encrypt);
    }
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    arrayAdapter = new ArrayAdapter<String>(this, R.layout.drawer_list_item, drawerOptions);
    mDrawerList.setAdapter(arrayAdapter);

    mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

            switch (position) {
            case 0:
                mDrawerLayout.closeDrawer(mDrawerList);
                launchShowTransactionsActivity();
                break;
            //show addresses
            case 1:
                mDrawerLayout.closeDrawer(mDrawerList);
                launchShowAddressesActivity();
                break;
            //show currencies
            case 2:
                mDrawerLayout.closeDrawer(mDrawerList);
                launchCurrencyActivity();
                break;
            case 3:
                mDrawerLayout.closeDrawer(mDrawerList);
                if (wallet.isEncrypted()) {
                    //do decrypt wallet
                    if (application.getKeyCache() != null) {
                        DecryptWalletTask decryptWalletTask = new DecryptWalletTask(context, wallet, null,
                                application);
                        //decryptWalletTask.execute();
                        decryptWalletTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);

                    }
                    //Means x2 is written to the tag.
                    else if (!prefs.contains(Constants.SHAMIR_ENCRYPTED_KEY)) {
                        Intent decryptIntent = new Intent(context, NFCActivity.class);
                        decryptIntent.putExtra("nfc_action", "decrypt");
                        startActivity(decryptIntent);
                    } else {
                        application.showPasswordPrompt(context, Constants.ACTION_DECRYPT);
                    }
                } else {
                    if (nfcEnabled) {
                        Intent decryptIntent = new Intent(context, NFCActivity.class);
                        decryptIntent.putExtra("nfc_action", "encrypt");
                        startActivity(decryptIntent);
                    } else {
                        application.showPasswordPrompt(context, Constants.ACTION_ENCRYPT);
                    }
                }
                break;
            //If doing backup.
            case 4:
                mDrawerLayout.closeDrawer(mDrawerList);

                if (nfcEnabled) {
                    Intent intent = new Intent(context, NFCActivity.class);
                    intent.putExtra("nfc_action", "backup");
                    startActivity(intent);
                } else
                    application.showPasswordPrompt(context, Constants.ACTION_BACKUP);

                break;
            case 5:
                mDrawerLayout.closeDrawer(mDrawerList);
                initiateSettingsActivity();
                break;

            default:
                break;
            }
        }
    });

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the sliding drawer and the action bar app icon
    mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
            mDrawerLayout, /* DrawerLayout object */
            R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
            R.string.drawer_open, /* "open drawer" description for accessibility */
            R.string.drawer_close /* "close drawer" description for accessibility */
    ) {
        public void onDrawerClosed(View view) {
            setTitle(mTitle);
            //getActionBar().setTitle(mTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        public void onDrawerOpened(View drawerView) {
            //getActionBar().setTitle(mDrawerTitle);
            setTitle(mDrawerTitle);

            if (wallet.isEncrypted()) {
                drawerOptions[3] = getString(R.string.drawer_wallet_decrypt);
            } else {

                drawerOptions[3] = getString(R.string.drawer_wallet_encrypt);
            }
            arrayAdapter.notifyDataSetChanged();
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    mDrawerList.setItemChecked(0, true);
    setTitle(drawerOptions[0]);
    mDrawerLayout.closeDrawer(mDrawerList);

}

From source file:com.pk.wallpapermanager.PkWallpaperManager.java

/**
 * Loads wallpapers stored on your cloud repository asynchronously. It's safe to 
 * call this on the main UI thread.//from w  ww. j av a 2s . com
 * <p>
 * This will not throw any exceptions but it does not guarantee success either.
 * Use this as a lazy way of loading stuff in the background.
 * 
 * @param parallel   Boolean indicating whether to run serially or in parallel. 
 *                True for parallel, False for serial.
 */
public void fetchCloudWallpapersAsync(boolean parallel) {
    if (cloudWallpapersTask.getStatus() == AsyncTask.Status.PENDING) {
        // Execute task if it's ready to go!
        cloudWallpapersTask
                .executeOnExecutor(parallel ? AsyncTask.THREAD_POOL_EXECUTOR : AsyncTask.SERIAL_EXECUTOR);
    } else if (cloudWallpapersTask.getStatus() == AsyncTask.Status.RUNNING && debugEnabled) {
        // Don't execute if already running
        Log.d(LOG_TAG, "Task is already running...");
    } else if (cloudWallpapersTask.getStatus() == AsyncTask.Status.FINISHED) {
        // Okay, this is not supposed to happen. Reset and recall.
        if (debugEnabled)
            Log.d(LOG_TAG, "Uh oh, it appears the task has finished without being reset. Resetting task...");

        initCloudWallpapersTask();
        fetchCloudWallpapersAsync(parallel);
    }
}

From source file:com.android.leanlauncher.WidgetPreviewLoader.java

private static void removeItemFromDb(final CacheDb cacheDb, final String objectName) {
    new AsyncTask<Void, Void, Void>() {
        public Void doInBackground(Void... args) {
            SQLiteDatabase db = cacheDb.getWritableDatabase();
            try {
                db.delete(CacheDb.TABLE_NAME, CacheDb.COLUMN_NAME + " = ? ", // SELECT query
                        new String[] { objectName }); // args to SELECT query
            } catch (SQLiteDiskIOException ignored) {
            }/*from w  ww  .  j a v  a  2 s.  c om*/
            return null;
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
}

From source file:joshuatee.wx.ModelInterfaceActivity.java

public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

    if (spinner1_ran && spinner2_ran && spinner_sector_ran) {
        new GetContent().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    } else {/*from  w  w w .  ja v a  2  s  . c om*/

        switch (parent.getId()) {

        case R.id.spinner1:

            if (!spinner1_ran) {
                spinner1_ran = true;
            }
            break;
        case R.id.spinner2:
            if (!spinner2_ran) {
                spinner2_ran = true;
            }
            break;
        case R.id.spinner_sector:
            if (!spinner_sector_ran) {
                spinner_sector_ran = true;
            }
            break;
        }
    }

}

From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_communicator.util.FileUtils.java

public static void DownloadFromUrl(final String media, final String messageId, final Context ctx,
        final ImageView container, final Object object, final String timelineId, final String localId,
        final Long fileSize) {

    new AsyncTask<Void, Void, Boolean>() {
        private boolean retry = true;
        private Bitmap imageDownloaded;
        private BroadcastReceiver mDownloadCancelReceiver;
        private HttpGet job;
        private AccountManager am;
        private Account account;
        private String authToken;

        @Override//from   w  w w. ja v  a2  s. c  om
        protected void onPreExecute() {
            IntentFilter downloadFilter = new IntentFilter(ConstantKeys.BROADCAST_CANCEL_PROCESS);
            mDownloadCancelReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String localIdToClose = (String) intent.getExtras().get(ConstantKeys.LOCALID);
                    if (localId.equals(localIdToClose)) {
                        try {
                            job.abort();
                        } catch (Exception e) {
                            log.debug("The process was canceled");
                        }
                        cancel(false);
                    }
                }
            };

            // registering our receiver
            ctx.getApplicationContext().registerReceiver(mDownloadCancelReceiver, downloadFilter);
        }

        @Override
        protected void onCancelled() {
            File file1 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_JPG);
            File file2 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_3GP);

            if (file1.exists()) {
                file1.delete();
            }
            if (file2.exists()) {
                file2.delete();
            }

            file1 = null;
            file2 = null;
            System.gc();
            try {
                ctx.getApplicationContext().unregisterReceiver(mDownloadCancelReceiver);
            } catch (Exception e) {
                log.debug("Receriver unregister from another code");
            }

            for (int i = 0; i < AppUtils.getlistOfDownload().size(); i++) {
                if (AppUtils.getlistOfDownload().get(i).equals(localId)) {
                    AppUtils.getlistOfDownload().remove(i);
                }
            }

            DataBasesAccess.getInstance(ctx.getApplicationContext()).MessagesDataBaseWriteTotal(localId, 100);

            Intent intent = new Intent();
            intent.setAction(ConstantKeys.BROADCAST_DIALOG_DOWNLOAD_FINISH);
            intent.putExtra(ConstantKeys.LOCALID, localId);
            ctx.sendBroadcast(intent);

            if (object != null) {
                ((ProgressDialog) object).dismiss();
            }
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                File file1 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_JPG);
                File file2 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_3GP);
                // firt we are goint to search the local files
                if ((!file1.exists()) && (!file2.exists())) {
                    account = AccountUtils.getAccount(ctx.getApplicationContext(), false);
                    am = (AccountManager) ctx.getSystemService(Context.ACCOUNT_SERVICE);
                    authToken = ConstantKeys.STRING_DEFAULT;
                    authToken = am.blockingGetAuthToken(account, ctx.getString(R.string.account_type), true);

                    MessagingClientService messageService = new MessagingClientService(
                            ctx.getApplicationContext());

                    URL urlObj = new URL(Preferences.getServerProtocol(ctx), Preferences.getServerAddress(ctx),
                            Preferences.getServerPort(ctx), ctx.getString(R.string.url_get_content));

                    String url = ConstantKeys.STRING_DEFAULT;
                    url = Uri.parse(urlObj.toString()).buildUpon().build().toString() + timelineId + "/"
                            + messageId + "/" + "content";

                    job = new HttpGet(url);
                    // first, get free space
                    FreeUpSpace(ctx, fileSize);
                    messageService.getContent(authToken, media, messageId, timelineId, localId, false, false,
                            fileSize, job);
                }

                if (file1.exists()) {
                    imageDownloaded = decodeSampledBitmapFromPath(file1.getAbsolutePath(), 200, 200);
                } else if (file2.exists()) {
                    imageDownloaded = ThumbnailUtils.createVideoThumbnail(file2.getAbsolutePath(),
                            MediaStore.Images.Thumbnails.MINI_KIND);
                }

                if (imageDownloaded == null) {
                    return false;
                }
                return true;
            } catch (Exception e) {
                deleteFiles();
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean result) {
            // We have the media
            try {
                ctx.getApplicationContext().unregisterReceiver(mDownloadCancelReceiver);
            } catch (Exception e) {
                log.debug("Receiver was closed on cancel");
            }

            if (!(localId.contains(ConstantKeys.AVATAR))) {
                for (int i = 0; i < AppUtils.getlistOfDownload().size(); i++) {
                    if (AppUtils.getlistOfDownload().get(i).equals(localId)) {
                        AppUtils.getlistOfDownload().remove(i);
                    }
                }

                DataBasesAccess.getInstance(ctx.getApplicationContext()).MessagesDataBaseWriteTotal(localId,
                        100);

                Intent intent = new Intent();
                intent.setAction(ConstantKeys.BROADCAST_DIALOG_DOWNLOAD_FINISH);
                intent.putExtra(ConstantKeys.LOCALID, localId);
                ctx.sendBroadcast(intent);
            }

            if (object != null) {
                ((ProgressDialog) object).dismiss();
            }

            // Now the only container could be the avatar in edit screen
            if (container != null) {
                if (imageDownloaded != null) {
                    container.setImageBitmap(imageDownloaded);
                } else {
                    deleteFiles();
                    imageDownloaded = decodeSampledBitmapFromResource(ctx.getResources(),
                            R.drawable.ic_error_loading, 200, 200);
                    container.setImageBitmap(imageDownloaded);
                    Toast.makeText(ctx.getApplicationContext(),
                            ctx.getApplicationContext().getText(R.string.donwload_fail), Toast.LENGTH_SHORT)
                            .show();
                }
            } else {
                showMedia(localId, ctx, (ProgressDialog) object);
            }

        }

        private void deleteFiles() {
            File file1 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_JPG);
            File file2 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_3GP);
            if (file1.exists()) {
                file1.delete();
            }
            if (file2.exists()) {
                file2.delete();
            }
        }

    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:com.develop.autorus.MainActivity.java

@Override
protected void onResume() {
    super.onResume();
    if (mNavigationDrawerFragment.getCurrentItemSelected() == 0)
        mainFragment.updateMonitorsFragment();
    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    int numberOfCallingFragment = pref.getInt("NumberOfCallingFragment", -1);
    if (getIntent().hasExtra("isFromNotification")
            && getIntent().getBooleanExtra("isFromNotification", false)) {
        numberOfCallingFragment = 0;// ww w . j  a v a 2  s .  c  om
    }

    if (numberOfCallingFragment != -1) {
        if ((mNavigationDrawerFragment.getCurrentItemSelected() == 0 && numberOfCallingFragment == 1)
                || (mNavigationDrawerFragment.getCurrentItemSelected() == 1 && numberOfCallingFragment == 0)) {
            Waiter waiter = new Waiter();
            if (Build.VERSION.SDK_INT >= 11)
                waiter.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, numberOfCallingFragment, 400);
            else {
                onNavigationDrawerItemSelected(numberOfCallingFragment);
                setNavigationDrawerItem(numberOfCallingFragment);
            }
        } else {
            onNavigationDrawerItemSelected(numberOfCallingFragment);
            setNavigationDrawerItem(numberOfCallingFragment);
        }
        pref.edit().remove("NumberOfCallingFragment").commit();
    }

}

From source file:joshuatee.wx.USWarningsWithRadarActivity.java

public void LocationAdd(int id) {

    new SaveLocFromZone().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, id);

}

From source file:com.cloudzilla.fb.FacebookServiceProxy.java

public void showFacebookDialog(final String action, final Bundle params) {
    Log.d(TAG, "showFacebookDialog action=" + action + " params=" + toString(params));

    if (mInstance == null || !mInstance.isOnFacebook()) {
        Log.e(TAG, "You are not on Facebook");
        return;//from w w w.ja v  a 2 s.co m
    }

    new AsyncTask<Void, Void, JSONObject>() {
        private final IFacebookService facebookService = mFacebookService;

        protected JSONObject doInBackground(Void... nada) {
            JSONObject result = null;

            try {
                JSONObject jsonRequest = new JSONObject();
                jsonRequest.put("method", action);
                for (String key : params.keySet()) {
                    jsonRequest.put(key, params.get(key));
                }
                String resultAsStr = facebookService.ui(jsonRequest.toString());
                if (resultAsStr != null) {
                    result = new JSONObject(resultAsStr);
                }
            } catch (JSONException e) {
                Log.e(TAG, "Exception: ", e);
            } catch (RemoteException e) {
                Log.e(TAG, "Failed to invoke FacebookService", e);
            }

            return result;
        }

        protected void onPostExecute(JSONObject result) {
            Bundle bundle = null;
            if (result != null) {
                try {
                    bundle = toBundle(result);
                } catch (JSONException e) {
                    // Nothing to do. We'll return a Facebook
                    // exception below.
                }

                if (Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG, "Response from Facebook: ");
                    for (String key : bundle.keySet()) {
                        Log.d(TAG, "\t" + key + "=" + bundle.get(key));
                    }
                }
                //                    listener.onComplete(bundle, null);
            } else {
                //                    listener.onComplete(null, new FacebookException());
            }
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:joshuatee.wx.NEXRADAttributesActivity.java

private void selectItem(int position) {

    mDrawerList.setItemChecked(position, false);
    mDrawerLayout.closeDrawer(mDrawerList);

    filter = state_array[position];//  www .  j a  v  a 2 s. c  om
    new GetContent().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

}

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  w w .  jav  a  2  s .c om
        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;
}