Example usage for android.app AlertDialog.Builder setOnKeyListener

List of usage examples for android.app AlertDialog.Builder setOnKeyListener

Introduction

In this page you can find the example usage for android.app AlertDialog.Builder setOnKeyListener.

Prototype

public void setOnKeyListener(@Nullable OnKeyListener onKeyListener) 

Source Link

Document

Sets the callback that will be called if a key is dispatched to the dialog.

Usage

From source file:org.skt.runtime.RuntimeChromeClient.java

/**
 * Tell the client to display a confirm dialog to the user.
 * /*from w  w  w .j av  a  2 s.  c o m*/
 * @param view
 * @param url
 * @param message
 * @param result
 */
@Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
    AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx);
    dlg.setMessage(message);
    dlg.setTitle("Confirm");
    dlg.setCancelable(true);
    dlg.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            result.confirm();
        }
    });
    dlg.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            result.cancel();
        }
    });
    dlg.setOnCancelListener(new DialogInterface.OnCancelListener() {
        public void onCancel(DialogInterface dialog) {
            result.cancel();
        }
    });
    dlg.setOnKeyListener(new DialogInterface.OnKeyListener() {
        //DO NOTHING
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                result.cancel();
                return false;
            } else
                return true;
        }
    });
    dlg.create();
    dlg.show();
    return true;
}

From source file:org.hfoss.posit.android.functionplugin.reminder.SetReminder.java

private void showAddrEnterDialog() {
    // Set the current dialog
    currentDialog = ADDRESS_ENTER_DIALOG_ID;

    // Build Address Enter Dialog
    AlertDialog.Builder addrEnterBuilder = new AlertDialog.Builder(this);
    addrEnterBuilder.setTitle("Step 3: Enter Location Name / Address");

    // Initialize EditText for user to type the desired address
    addressET = new EditText(this);
    addressET.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
    addrEnterBuilder.setView(addressET);

    // Set Listeners
    addrEnterBuilder.setPositiveButton("Search", mAddrEnterOnClickListner);
    // Finish the activity when the user presses cancel
    addrEnterBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            setResult(RESULT_OK);/*ww  w .  j ava  2 s. co m*/
            finish();
        }
    });
    addrEnterBuilder.setOnKeyListener(mBackKeyListener);

    // Show Address Enter Dialog
    addrEnterDialog = addrEnterBuilder.create();
    addrEnterDialog.show();
}

From source file:org.hfoss.posit.android.functionplugin.reminder.SetReminder.java

private void showAddrConfirmDialog() {
    // Set the current dialog
    currentDialog = ADDRESS_CONFIRM_DIALOG_ID;

    // Build Address Confirm Dialog
    AlertDialog.Builder addrConfirmBuilder = new AlertDialog.Builder(this);
    addrConfirmBuilder.setTitle("Step 4: Did you mean...");

    // Build the possible addresses list from results returned by Google URL request
    ArrayList<String> possibleAddr = new ArrayList<String>();

    for (int i = 0; i < addressArray.length(); i++) {
        try {//from  w  w w.j av a  2  s  .c o  m
            String receivedAddr = addressArray.getJSONObject(i).getString("formatted_address").replace(", ",
                    ",\n");
            possibleAddr.add(receivedAddr);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    final CharSequence[] possibleAddrChar = possibleAddr.toArray(new CharSequence[possibleAddr.size()]);
    addrConfirmBuilder.setItems(possibleAddrChar, mAddrConfirmOnClickListener);

    // Set Listeners
    addrConfirmBuilder.setOnKeyListener(mBackKeyListener);
    // Re-display Address Enter Dialog when the user presses retry
    addrConfirmBuilder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            showAddrEnterDialog();
            Toast.makeText(getApplicationContext(),
                    "To get better results, please type a more specific name or address "
                            + "with CITY NAME included.",
                    Toast.LENGTH_LONG).show();
        }
    });
    // Finish the activity when the user presses cancel
    addrConfirmBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            setResult(RESULT_OK);
            finish();
        }
    });

    // Show Address Confirm Dialog
    addrConfirmDialog = addrConfirmBuilder.create();
    addrConfirmDialog.show();
}

From source file:org.catrobat.catroid.ui.dialogs.TermsOfUseDialogFragment.java

@Override
public Dialog onCreateDialog(Bundle bundle) {
    Bundle fragmentDialogArguments = getArguments();
    boolean acceptTermsOfUse = false;
    if (fragmentDialogArguments != null) {
        acceptTermsOfUse = fragmentDialogArguments.getBoolean(DIALOG_ARGUMENT_TERMS_OF_USE_ACCEPT, false);
    }//from w  w w  .  ja  v  a  2  s .c  o m

    View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_terms_of_use, null);

    final CheckBox checkBoxTermsOfUseAcceptedPermanently = (CheckBox) view
            .findViewById(R.id.dialog_terms_of_use_check_box_agree_permanently);

    TextView termsOfUseUrlTextView = (TextView) view.findViewById(R.id.dialog_terms_of_use_text_view_url);
    termsOfUseUrlTextView.setMovementMethod(LinkMovementMethod.getInstance());

    String termsOfUseUrl = getString(R.string.terms_of_use_link_template, Constants.CATROBAT_TERMS_OF_USE_URL,
            getString(R.string.dialog_terms_of_use_link_text));

    termsOfUseUrlTextView.setText(Html.fromHtml(termsOfUseUrl));

    AlertDialog.Builder termsOfUseDialogBuilder = new AlertDialog.Builder(getActivity()).setView(view)
            .setTitle(R.string.dialog_terms_of_use_title);

    if (!acceptTermsOfUse) {
        termsOfUseDialogBuilder.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
    } else {
        termsOfUseDialogBuilder.setNegativeButton(R.string.dialog_terms_of_use_do_not_agree,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        getActivity().finish();
                        dialog.dismiss();
                    }
                });
        termsOfUseDialogBuilder.setPositiveButton(R.string.dialog_terms_of_use_agree,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        if (checkBoxTermsOfUseAcceptedPermanently.isChecked()) {
                            SettingsActivity.setTermsOfServiceAgreedPermanently(getActivity(), true);
                        }
                        dialog.dismiss();
                        DroneInitializer droneInitializer = ((PreStageActivity) getActivity())
                                .getDroneInitializer();
                        if (droneInitializer != null) {
                            droneInitializer.initialiseDrone();
                        }
                    }
                });
        termsOfUseDialogBuilder.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                Log.d(TAG, "prevent canceling the dialog with back button");
                return true;
            }
        });

        checkBoxTermsOfUseAcceptedPermanently.setVisibility(CheckBox.VISIBLE);
        checkBoxTermsOfUseAcceptedPermanently.setText(R.string.dialog_terms_of_use_agree_permanent);
        termsOfUseDialogBuilder.setCancelable(false);
    }

    AlertDialog termsOfUseDialog = termsOfUseDialogBuilder.create();
    if (!acceptTermsOfUse) {
        termsOfUseDialog.setCanceledOnTouchOutside(true);
    } else {
        termsOfUseDialog.setCancelable(false);
        termsOfUseDialog.setCanceledOnTouchOutside(false);
    }

    return termsOfUseDialog;
}

From source file:hku.fyp14017.blencode.ui.dialogs.TermsOfUseDialogFragment.java

@Override
public Dialog onCreateDialog(Bundle bundle) {
    Bundle fragmentDialogArguments = getArguments();
    boolean acceptTermsOfUse = false;
    if (fragmentDialogArguments != null) {
        acceptTermsOfUse = fragmentDialogArguments.getBoolean(DIALOG_ARGUMENT_TERMS_OF_USE_ACCEPT, false);
    }/*from  ww w .  java2  s . co m*/

    View view = LayoutInflater.from(getActivity()).inflate(hku.fyp14017.blencode.R.layout.dialog_terms_of_use,
            null);

    final CheckBox checkBoxTermsOfUseAcceptedPermanently = (CheckBox) view
            .findViewById(hku.fyp14017.blencode.R.id.dialog_terms_of_use_check_box_agree_permanently);

    TextView termsOfUseUrlTextView = (TextView) view
            .findViewById(hku.fyp14017.blencode.R.id.dialog_terms_of_use_text_view_url);
    termsOfUseUrlTextView.setMovementMethod(LinkMovementMethod.getInstance());

    String termsOfUseUrl = getString(hku.fyp14017.blencode.R.string.terms_of_use_link_template,
            Constants.CATROBAT_TERMS_OF_USE_URL,
            getString(hku.fyp14017.blencode.R.string.dialog_terms_of_use_link_text));

    termsOfUseUrlTextView.setText(Html.fromHtml(termsOfUseUrl));

    AlertDialog.Builder termsOfUseDialogBuilder = new AlertDialog.Builder(getActivity()).setView(view)
            .setTitle(hku.fyp14017.blencode.R.string.dialog_terms_of_use_title);

    if (!acceptTermsOfUse) {
        termsOfUseDialogBuilder.setNeutralButton(hku.fyp14017.blencode.R.string.ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
    } else {
        termsOfUseDialogBuilder.setNegativeButton(
                hku.fyp14017.blencode.R.string.dialog_terms_of_use_do_not_agree,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        getActivity().finish();
                        dialog.dismiss();
                    }
                });
        termsOfUseDialogBuilder.setPositiveButton(hku.fyp14017.blencode.R.string.dialog_terms_of_use_agree,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        if (checkBoxTermsOfUseAcceptedPermanently.isChecked()) {
                            SettingsActivity.setTermsOfServiceAgreedPermanently(getActivity(), true);
                        }
                        dialog.dismiss();
                        DroneInitializer droneInitializer = ((PreStageActivity) getActivity())
                                .getDroneInitializer();
                        if (droneInitializer != null) {
                            droneInitializer.initialiseDrone();
                        }
                    }
                });
        termsOfUseDialogBuilder.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                Log.d(TAG, "prevent canceling the dialog with back button");
                return true;
            }
        });

        checkBoxTermsOfUseAcceptedPermanently.setVisibility(CheckBox.VISIBLE);
        checkBoxTermsOfUseAcceptedPermanently
                .setText(hku.fyp14017.blencode.R.string.dialog_terms_of_use_agree_permanent);
        termsOfUseDialogBuilder.setCancelable(false);
    }

    AlertDialog termsOfUseDialog = termsOfUseDialogBuilder.create();
    if (!acceptTermsOfUse) {
        termsOfUseDialog.setCanceledOnTouchOutside(true);
    } else {
        termsOfUseDialog.setCancelable(false);
        termsOfUseDialog.setCanceledOnTouchOutside(false);
    }

    return termsOfUseDialog;
}

From source file:com.phonegap.plugins.wsiCameraLauncher.WsiCameraLauncher.java

/**
 * Get image from photo library./*from w w  w .j  av a 2 s  .  c  o  m*/
 * 
 * @param quality
 *            Compression quality hint (0-100: 0=low quality & high
 *            compression, 100=compress of max quality)
 * @param srcType
 *            The album to get image from.
 * @param returnType
 *            Set the type of image to return.
 */
// TODO: Images selected from SDCARD don't display correctly, but from
// CAMERA ALBUM do!
public void getImage(int srcType, int returnType) {

    final int srcTypeFinal = srcType;
    final int returnTypeFinal = returnType;

    String[] choices = { "Upload a Photo", "Upload a Video" };

    AlertDialog.Builder builder = new AlertDialog.Builder(this.cordova.getActivity());
    builder.setItems(choices, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Log.d(LOG_TAG, "Index #" + which + " chosen.");
            Intent intent = new Intent();
            if (which == 0) {
                // set up photo intent
                WsiCameraLauncher.this.mediaType = PICTURE;
                intent.setType("image/*");
            } else if (which == 1) {
                // set up video intent
                WsiCameraLauncher.this.mediaType = VIDEO;
                intent.setType("video/*");
            } else {
                WsiCameraLauncher.this.failPicture("Selection cancelled.");
                return;
            }
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            if (WsiCameraLauncher.this.cordova != null) {
                WsiCameraLauncher.this.cordova.startActivityForResult((CordovaPlugin) WsiCameraLauncher.this,
                        Intent.createChooser(intent, new String("Pick")),
                        (srcTypeFinal + 1) * 16 + returnTypeFinal + 1);
            }
        }
    });
    builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP
                    && !event.isCanceled()) {
                dialog.cancel();
                WsiCameraLauncher.this.failPicture("Selection cancelled.");
                return true;
            }
            return false;
        }
    });
    builder.show();
}

From source file:org.runnerup.export.SyncManager.java

private void askUsernamePassword(final Synchronizer sync, boolean showPassword) {
    AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
    builder.setTitle(sync.getName());/* w w  w .  j a  v a 2 s  . c o m*/

    final View view = View.inflate(mActivity, R.layout.userpass, null);
    final CheckBox cb = (CheckBox) view.findViewById(R.id.showpass);
    final TextView tv1 = (TextView) view.findViewById(R.id.username);
    final TextView tv2 = (TextView) view.findViewById(R.id.password_input);
    final TextView tvAuthNotice = (TextView) view.findViewById(R.id.textViewAuthNotice);
    String authConfigStr = sync.getAuthConfig();
    final JSONObject authConfig = newObj(authConfigStr);
    String username = authConfig.optString("username", "");
    String password = authConfig.optString("password", "");
    tv1.setText(username);
    tv2.setText(password);
    cb.setChecked(showPassword);
    tv2.setInputType(InputType.TYPE_CLASS_TEXT | (showPassword ? 0 : InputType.TYPE_TEXT_VARIATION_PASSWORD));
    cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            tv2.setInputType(
                    InputType.TYPE_CLASS_TEXT | (isChecked ? 0 : InputType.TYPE_TEXT_VARIATION_PASSWORD));
        }
    });
    if (sync.getAuthNotice() != null) {
        tvAuthNotice.setVisibility(View.VISIBLE);
        tvAuthNotice.setText(sync.getAuthNotice());
    } else {
        tvAuthNotice.setVisibility(View.GONE);
    }

    // Inflate and set the layout for the dialog
    // Pass null as the parent view because its going in the dialog layout
    builder.setView(view);
    builder.setPositiveButton(getResources().getString(R.string.OK), new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            try {
                authConfig.put("username", tv1.getText());
                authConfig.put("password", tv2.getText());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            testUserPass(sync, authConfig, cb.isChecked());
        }
    });
    builder.setNeutralButton("Skip", new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            handleAuthComplete(sync, Status.SKIP);
        }
    });
    builder.setNegativeButton(getResources().getString(R.string.Cancel), new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            handleAuthComplete(sync, Status.SKIP);
        }
    });
    builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
            if (i == KeyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_UP) {
                handleAuthComplete(sync, Status.CANCEL);
            }
            return false;
        }
    });
    final AlertDialog dialog = builder.create();
    dialog.show();
}

From source file:com.example.testapplication.DialogLocation.java

@SuppressLint("InlinedApi")
@Override//from  w w  w  .j a v a  2s .  com
public Dialog onCreateDialog(Bundle savedInstanceState) {
    mProgressBar = new ProgressBar(getActivity(), null, android.R.attr.progressBarStyleLarge);
    mProgressBarInv = new ProgressBar(getActivity(), null, android.R.attr.progressBarStyleLarge);
    mProgressBarInv.setVisibility(ProgressBar.GONE);

    mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

    mCriteria = new Criteria();
    int criteria = (mGpsPref) ? Criteria.POWER_HIGH : Criteria.POWER_MEDIUM;
    mCriteria.setPowerRequirement(criteria);

    mProvider = mLocationManager.getBestProvider(mCriteria, true);
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
    int telephonyInfo = tm.getNetworkType();

    boolean networkAvailable = true;

    if ((telephonyInfo == TelephonyManager.NETWORK_TYPE_UNKNOWN && !networkInfo.isConnected())
            || !mLocationManager.isProviderEnabled("network")) {
        networkAvailable = false;
    }

    int locationMode = -1;
    int locationType = -1;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        try {
            locationMode = Settings.Secure.getInt(getActivity().getContentResolver(),
                    Settings.Secure.LOCATION_MODE);
        } catch (SettingNotFoundException e) {
            e.printStackTrace();
        }

        if (locationMode == Settings.Secure.LOCATION_MODE_OFF
                || (!networkAvailable && (mProvider.matches("network"))))
            locationType = NO_LOCATION_SERVICES;
        else if (mGpsPref && (locationMode == Settings.Secure.LOCATION_MODE_SENSORS_ONLY
                || locationMode == Settings.Secure.LOCATION_MODE_HIGH_ACCURACY))
            locationType = (locationMode == Settings.Secure.LOCATION_MODE_SENSORS_ONLY || !networkAvailable)
                    ? USING_ONLY_GPS_LOCATION
                    : USING_GPS_LOCATION_NETWORK_AVAILABLE;
        else if (mProvider.matches("network") && (locationMode == Settings.Secure.LOCATION_MODE_BATTERY_SAVING
                || locationMode == Settings.Secure.LOCATION_MODE_HIGH_ACCURACY))
            locationType = USING_NETWORK_LOCATION;

    } else {
        if (mProvider.matches("passive") || !networkAvailable
                && (mProvider.matches("network") || (!mGpsPref && mProvider.matches("gps"))))
            locationType = NO_LOCATION_SERVICES;
        else if (mProvider.matches("gps") && mGpsPref)
            locationType = ((mProvider.matches("gps")) || !networkAvailable) ? USING_ONLY_GPS_LOCATION
                    : USING_GPS_LOCATION_NETWORK_AVAILABLE;
        else if (mProvider.matches("network"))
            locationType = USING_NETWORK_LOCATION;
    }

    switch (locationType) {
    case NO_LOCATION_SERVICES:
        builder.setTitle(DIALOG_LOCATION_NO_LOCATION_SERVICES_TITLE);
        builder.setMessage(DIALOG_LOCATION_NO_LOCATION_SERVICES_MESSAGE);
        builder.setNeutralButton(DIALOG_LOCATION_BUTTON_SETTINGS, noNetworkButton);
        mAbortRequest = true;
        break;
    case USING_ONLY_GPS_LOCATION:
        builder.setTitle(DIALOG_LOCATION_UPDATING_GPS_TITLE);
        builder.setMessage(DIALOG_LOCATION_ONLY_GPS_MESSAGE);
        builder.setNeutralButton(DIALOG_LOCATION_BUTTON_SETTINGS, noNetworkButton);
        builder.setView(mProgressBar);
        break;
    case USING_GPS_LOCATION_NETWORK_AVAILABLE:
        builder.setTitle(DIALOG_LOCATION_UPDATING_GPS_TITLE);
        builder.setPositiveButton(DIALOG_LOCATION_USE_NETWORK, null);
        builder.setView(mProgressBar);
        break;
    case USING_NETWORK_LOCATION:
        builder.setView(mProgressBar);
        builder.setTitle(DIALOG_LOCATION_UPDATING_NETWORK_TITLE);
        break;
    }

    builder.setNegativeButton(DIALOG_LOCATION_CANCEL, cancelListener);
    builder.setOnKeyListener(new DialogInterface.OnKeyListener() {

        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                mCallback.onLocationFound(null, mFragmentId);
                mLocationManager.removeUpdates(DialogLocation.this);
                Toast.makeText(getActivity(), "Location request cancelled", Toast.LENGTH_SHORT).show();
                dialog.cancel();
                return true;
            }
            return false;
        }
    });

    mRealDialog = builder.create();
    mRealDialog.setOnShowListener(usingNetwork);
    mRealDialog.setCanceledOnTouchOutside(false);
    return mRealDialog;
}

From source file:com.nearnotes.NoteLocation.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the Builder class for convenient dialog construction
    Bundle extras = getArguments();/* w ww  . java 2  s . c  o m*/
    mTypeFrag = extras.getInt("TypeFrag");

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
    Boolean gpsPref = sharedPref.getBoolean("pref_key_ignore_gps", false);
    mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    mCriteria = new Criteria();
    if (gpsPref) {
        mCriteria.setPowerRequirement(Criteria.POWER_HIGH);
    } else
        mCriteria.setPowerRequirement(Criteria.POWER_MEDIUM);
    mProvider = mLocationManager.getBestProvider(mCriteria, true);
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    boolean oldApi = false;
    int locationMode = 4;
    Log.e("mProvider", mProvider);

    ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    boolean networkAvailable = true;

    TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
    boolean networkType = true;
    if (tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_UNKNOWN && !networkInfo.isConnected()) {
        networkType = false;
    }

    Log.d("Phone state before if statement", "Phone State: " + mServiceState);
    Log.e("network isavailable", String.valueOf(networkInfo.isAvailable()));
    if (!networkType || !mLocationManager.isProviderEnabled("network")) {
        networkAvailable = false;
    }

    try {
        Log.e("Location_mode", String.valueOf(
                Settings.Secure.getInt(getActivity().getContentResolver(), Settings.Secure.LOCATION_MODE)));
        locationMode = Settings.Secure.getInt(getActivity().getContentResolver(),
                Settings.Secure.LOCATION_MODE);
    } catch (SettingNotFoundException e) {
        oldApi = true;
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if ((oldApi && mProvider.matches("passive")) || locationMode == LOCATION_MODE_OFF || (!networkAvailable
            && (mProvider.matches("network") || (!gpsPref && mProvider.matches("gps"))))) {
        builder.setTitle(getString(R.string.dialog_location_no_location_services_title));
        builder.setMessage(getString(R.string.dialog_location_no_location_services_message));
        builder.setNeutralButton(R.string.dialog_location_button_settings, noNetworkButton);
        mAbortRequest = true;
    } else if ((oldApi && mProvider.matches("gps") && gpsPref) || (mProvider.matches("gps") && gpsPref
            && (locationMode == LOCATION_MODE_SENSORS_ONLY || locationMode == LOCATION_MODE_HIGH_ACCURACY))) {
        if (mTypeFrag == NOTE_EDIT) {
            builder.setTitle(getString(R.string.dialog_location_finding_note_gps));
        } else if (mTypeFrag == NOTE_LIST) {
            builder.setTitle(getString(R.string.dialog_location_updating_note_gps));
        }
        if (locationMode == LOCATION_MODE_SENSORS_ONLY || (oldApi && mProvider.matches("gps"))
                || !networkAvailable) {
            builder.setMessage(getString(R.string.dialog_location_only_gps_message));
            builder.setNeutralButton(R.string.dialog_location_button_settings, noNetworkButton);

        } else
            builder.setPositiveButton(R.string.dialog_location_use_network, null);

        builder.setView(getActivity().getLayoutInflater().inflate(R.layout.dialogue_location, null));

    } else if ((oldApi && mProvider.matches("network")) || (mProvider.matches("network")
            && (locationMode == LOCATION_MODE_BATTERY_SAVING || locationMode == LOCATION_MODE_HIGH_ACCURACY))) {
        builder.setView(getActivity().getLayoutInflater().inflate(R.layout.dialogue_location, null));
        if (mTypeFrag == NOTE_EDIT) {
            builder.setTitle(getString(R.string.dialog_location_finding_note_network));
        } else if (mTypeFrag == NOTE_LIST) {
            builder.setTitle(getString(R.string.dialog_location_updating_note_network));
        }

    }
    builder.setNegativeButton(R.string.cancel, cancelListener);
    // Create the AlertDialog object and return it

    // builder.create();

    builder.setOnKeyListener(new DialogInterface.OnKeyListener() {

        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                mCallback.onLocationFound(null, mTypeFrag);
                mLocationManager.removeUpdates(NoteLocation.this);
                Toast.makeText(getActivity(), "Location request cancelled", Toast.LENGTH_SHORT).show();
                dialog.cancel();
                return true;
            }

            return false;
        }
    });

    mRealDialog = builder.create();
    // final LocationListener getFragment() = this.;

    mRealDialog.setOnShowListener(usingNetwork);
    mRealDialog.setCanceledOnTouchOutside(false);
    // mRealDialog.setCancelable(false);
    return mRealDialog;

}

From source file:com.android.mms.ui.ComposeMessageActivity.java

private void LaunchMsimDialog(final boolean bCheckEcmMode) {

    AlertDialog.Builder builder = new AlertDialog.Builder(ComposeMessageActivity.this);
    LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    View layout = inflater.inflate(R.layout.multi_sim_sms_sender, (ViewGroup) findViewById(R.id.layout_root));
    builder.setView(layout);//from w w  w  .j  a v  a  2  s  .c o  m
    builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            switch (keyCode) {
            case KeyEvent.KEYCODE_BACK: {
                dismissMsimDialog();
                return true;
            }
            case KeyEvent.KEYCODE_SEARCH: {
                return true;
            }
            }
            return false;
        }
    });

    builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dismissMsimDialog();
        }
    });

    ContactList recipients = isRecipientsEditorVisible() ? mRecipientsEditor.constructContactsFromInput(false)
            : getRecipients();
    builder.setTitle(
            getResources().getString(R.string.to_address_label) + recipients.formatNamesAndNumbers(","));

    mMsimDialog = builder.create();
    mMsimDialog.setCanceledOnTouchOutside(true);

    int[] smsBtnIds = { R.id.BtnSubOne, R.id.BtnSubTwo, R.id.BtnSubThree };
    int phoneCount = MSimTelephonyManager.getDefault().getPhoneCount();
    Button[] smsBtns = new Button[phoneCount];

    for (int i = 0; i < phoneCount; i++) {
        final int subscription = i;
        int subID = i + 1;
        smsBtns[i] = (Button) layout.findViewById(smsBtnIds[i]);
        smsBtns[i].setVisibility(View.VISIBLE);
        smsBtns[i].setText(MSimTelephonyManager.getDefault().getSimOperatorName(i) + "-" + subID);
        smsBtns[i].setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "Sub slected " + subscription);
                processMsimSendMessage(subscription, bCheckEcmMode);
            }
        });
    }
    mMsimDialog.show();
}