List of usage examples for android.app AlertDialog setButton
public void setButton(int whichButton, CharSequence text, OnClickListener listener)
From source file:goo.TeaTimer.TimerActivity.java
/** { @inheritDoc} */ @Override/*from w w w .j a v a2s. co m*/ public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case PREF: startActivity(new Intent(this, TimerPrefActivity.class)); break; case ABOUT: //new TimerAboutDialog(this).show(); //break; LayoutInflater li = LayoutInflater.from(this); View view = li.inflate(R.layout.about, null); Builder p = new AlertDialog.Builder(this).setView(view); final AlertDialog alrt = p.create(); alrt.setIcon(R.drawable.icon); alrt.setTitle(mImgUrl); alrt.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.close), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); alrt.show(); return true; default: return false; } return true; }
From source file:semanticweb.hws14.movapp.activities.Criteria.java
private void useLocationData(Location location) { //Receive the location Data AlertDialog ad = new AlertDialog.Builder(that).create(); ad.setCancelable(false); // This blocks the 'BACK' button Geocoder geocoder = new Geocoder(that, Locale.ENGLISH); try {/* w w w . j a va 2 s . co m*/ List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); if (addresses != null) { Address returnedAddress = addresses.get(0); final String strReturnedAdress = returnedAddress.getLocality(); ad.setMessage("You are in: " + strReturnedAdress + "\nUse this location for the search?"); ad.setButton(DialogInterface.BUTTON_POSITIVE, "YES", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (tabPosition == 0) { MovieCriteria currentFragmet = (MovieCriteria) getFragmentByPosition(tabPosition); currentFragmet.setGPSLocation(strReturnedAdress); } else if (tabPosition == 1) { ActorCriteria currentFragmet = (ActorCriteria) getFragmentByPosition(tabPosition); currentFragmet.setGPSLocation(strReturnedAdress); } dialog.dismiss(); } }); ad.setButton(DialogInterface.BUTTON_NEGATIVE, "NO", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); } else { ad.setMessage("No Address returned!"); ad.setButton(DialogInterface.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); } } catch (IOException e) { e.printStackTrace(); ad.setMessage("Can not get Address!"); ad.setButton(DialogInterface.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); } ad.show(); setProgressBarIndeterminateVisibility(false); locMgr.removeUpdates(locListner); }
From source file:org.rapidandroid.activity.FormCreator.java
@Override public void onBackPressed() { AlertDialog dialog = new AlertDialog.Builder(this).create(); dialog.setMessage("Save Changes First?"); dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface d, int which) { doSave();// w ww .j a v a2 s . com finish(); } }); dialog.setButton(DialogInterface.BUTTON_NEUTRAL, "No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface d, int which) { finish(); } }); dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface d, int which) { } }); dialog.show(); }
From source file:org.iota.wallet.ui.activity.MainActivity.java
@Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { Fragment fragment = null;//from w w w . j a v a 2 s . c o m getFragmentManager().popBackStack(); switch (item.getItemId()) { case R.id.nav_wallet: String encSeed = prefs.getString(Constants.PREFERENCE_ENC_SEED, ""); if (!encSeed.isEmpty() && IOTA.seed == null) { showLogoutNavigationItem(); fragment = new PasswordLoginFragment(); killFragments = true; } else if (IOTA.seed == null) { showLogoutNavigationItem(); fragment = new SeedLoginFragment(); killFragments = true; } else { showLogoutNavigationItem(); fragment = getFragmentManager().findFragmentById(R.id.container); if (fragment != null && fragment instanceof PasswordLoginFragment || fragment instanceof SeedLoginFragment) killFragments = true; fragment = new WalletTabFragment(); } break; case R.id.nav_tangle_explorer: fragment = new TangleExplorerTabFragment(); break; case R.id.nav_node_info: fragment = new NodeInfoFragment(); break; case R.id.nav_neighbors: fragment = new NeighborsFragment(); break; case R.id.nav_settings: Intent settings = new Intent(MainActivity.this, SettingsActivity.class); startActivity(settings); break; case R.id.nav_about: fragment = new AboutFragment(); break; case R.id.nav_logout: AlertDialog alertDialog = new AlertDialog.Builder(this).setMessage(R.string.message_confirm_logout) .setCancelable(false).setPositiveButton(R.string.buttons_ok, null) .setNegativeButton(R.string.buttons_cancel, null) .setNeutralButton(R.string.buttons_backup, null).create(); alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.buttons_ok), (dialog, which) -> { prefs.edit().remove(Constants.PREFERENCE_ENC_SEED).apply(); IOTA.seed = null; TaskManager.stopAndDestroyAllTasks(MainActivity.this); killFragments = true; navigationView.getMenu().performIdentifierAction(R.id.nav_wallet, 0); }); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, getString(R.string.buttons_backup), (dialog, which) -> { Intent settings1 = new Intent(MainActivity.this, SettingsActivity.class); startActivity(settings1); }); alertDialog.show(); break; } if (fragment != null) { showFragment(fragment, false, killFragments); } drawer.closeDrawer(GravityCompat.START); return true; }
From source file:com.xperia64.timidityae.FileBrowserFragment.java
public void getDir(String dirPath) { currPath = dirPath;/*from w ww. j ava2 s .co m*/ fname = new ArrayList<String>(); path = new ArrayList<String>(); if (currPath != null) { File f = new File(currPath); if (f.exists()) { File[] files = f.listFiles(); if (files != null && files.length > 0) { Arrays.sort(files, new FileComparator()); // System.out.println(currPath); if (!currPath.matches("[/]+")) { fname.add("../"); path.add(f.getParent() + "/"); mCallback.needFileBackCallback(true); } else { mCallback.needFileBackCallback(false); } for (int i = 0; i < files.length; i++) { File file = files[i]; if ((!file.getName().startsWith(".") && !Globals.showHiddenFiles) || Globals.showHiddenFiles) { if (file.isFile()) { int dotPosition = file.getName().lastIndexOf("."); String extension = ""; if (dotPosition != -1) { extension = (file.getName().substring(dotPosition)).toLowerCase(Locale.US); if (extension != null) { if ((Globals.showVideos ? Globals.musicVideoFiles : Globals.musicFiles) .contains("*" + extension + "*")) { path.add(file.getAbsolutePath()); fname.add(file.getName()); } } else if (file.getName().endsWith("/")) { path.add(file.getAbsolutePath() + "/"); fname.add(file.getName() + "/"); } } } else { path.add(file.getAbsolutePath() + "/"); fname.add(file.getName() + "/"); } } } } else { if (!currPath.matches("[/]+")) { fname.add("../"); path.add(f.getParent() + "/"); } } ArrayAdapter<String> fileList = new ArrayAdapter<String>(getActivity(), R.layout.row, fname); getListView().setFastScrollEnabled(true); getListView().setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> l, View v, final int position, long id) { localfinished = false; if (new File(path.get(position)).isFile() && Globals.isMidi(path.get(position))) { AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); alert.setTitle("Convert to WAV File"); alert.setMessage( "Exports the MIDI/MOD file to WAV.\nNative Midi must be disabled in settings.\nWarning: WAV files are large."); InputFilter filter = new InputFilter() { public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) { String IC = "*/*\n*\r*\t*\0*\f*`*?***\\*<*>*|*\"*:*"; if (IC.contains("*" + source.charAt(i) + "*")) { return ""; } } return null; } }; // Set an EditText view to get user input final EditText input = new EditText(getActivity()); input.setFilters(new InputFilter[] { filter }); alert.setView(input); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String value = input.getText().toString(); if (!value.toLowerCase(Locale.US).endsWith(".wav")) value += ".wav"; String parent = path.get(position).substring(0, path.get(position).lastIndexOf('/') + 1); boolean aWrite = true; boolean alreadyExists = new File(parent + value).exists(); String needRename = null; String probablyTheRoot = ""; String probablyTheDirectory = ""; try { new FileOutputStream(parent + value, true).close(); } catch (FileNotFoundException e) { aWrite = false; } catch (IOException e) { e.printStackTrace(); } if (!alreadyExists && aWrite) new File(parent + value).delete(); if (aWrite && new File(parent).canWrite()) { value = parent + value; } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Globals.theFold != null) { // Write the file to getExternalFilesDir, then move it with the Uri // We need to tell JNIHandler that movement is needed. String[] tmp = Globals.getDocFilePaths(getActivity(), parent); probablyTheDirectory = tmp[0]; probablyTheRoot = tmp[1]; if (probablyTheDirectory.length() > 1) { needRename = parent.substring( parent.indexOf(probablyTheRoot) + probablyTheRoot.length()) + value; value = probablyTheDirectory + '/' + value; } else { value = Environment.getExternalStorageDirectory().getAbsolutePath() + '/' + value; } } else { value = Environment.getExternalStorageDirectory().getAbsolutePath() + '/' + value; } final boolean canWrite = aWrite; final String finalval = value; final String needToRename = needRename; final String probRoot = probablyTheRoot; if (new File(finalval).exists() || (new File(probRoot + needRename).exists() && needToRename != null)) { AlertDialog dialog2 = new AlertDialog.Builder(getActivity()).create(); dialog2.setTitle("Warning"); dialog2.setMessage("Overwrite WAV file?"); dialog2.setCancelable(false); dialog2.setButton(DialogInterface.BUTTON_POSITIVE, getResources().getString(android.R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int buttonId) { if (!canWrite && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (needToRename != null) { Globals.tryToDeleteFile(getActivity(), probRoot + needToRename); Globals.tryToDeleteFile(getActivity(), finalval); } else { Globals.tryToDeleteFile(getActivity(), finalval); } } else { new File(finalval).delete(); } saveWavPart2(position, finalval, needToRename); } }); dialog2.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(android.R.string.no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int buttonId) { } }); dialog2.show(); } else { saveWavPart2(position, finalval, needToRename); } } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Canceled. } }); alert.show(); return true; } else { } return false; } }); setListAdapter(fileList); } } }
From source file:edu.rutgers.winlab.crowdpp.ui.HomeFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.home_fragment_layout, container, false); tb_cal = (ToggleButton) view.findViewById(R.id.tb_home_calibration); tb_service = (ToggleButton) view.findViewById(R.id.tb_home_service); tb_test = (ToggleButton) view.findViewById(R.id.tb_home_test); tv_cal_content = (TextView) view.findViewById(R.id.tv_home_calibration_content); tv_cal_text = (TextView) view.findViewById(R.id.tv_home_calibration_text); tv_debug = (TextView) view.findViewById(R.id.tv_home_test_debug); tv_record = (TextView) view.findViewById(R.id.tv_home_test_record); timer_cal = (Chronometer) view.findViewById(R.id.timer_calibration); timer_test = (Chronometer) view.findViewById(R.id.timer_test); rl_service = (RelativeLayout) view.findViewById(R.id.rl_home_service); rl_test = (RelativeLayout) view.findViewById(R.id.rl_home_test); if (isMyServiceRunning() == true) tb_service.setChecked(true);/* w w w . j av a2 s .c o m*/ if (Constants.calibration()) tv_cal_content.setText("You are all set for the calibration."); if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { Toast.makeText(getActivity(), "Can not find SD card ...", Toast.LENGTH_SHORT).show(); getActivity().finish(); } crowdppDir = new File(Constants.crowdppPath); if (!crowdppDir.exists() || !crowdppDir.isDirectory()) { crowdppDir.mkdir(); } testDir = new File(Constants.testPath); if (!testDir.exists() || !testDir.isDirectory()) { testDir.mkdir(); } calWavFile = crowdppDir + "/" + Constants.PHONE_ID + ".wav"; timer_cal.setVisibility(View.INVISIBLE); timer_test.setVisibility(View.INVISIBLE); mDatabase = new DataBaseHelper(getActivity().getApplicationContext()); mDB = mDatabase.getWritableDatabase(); gps = new LocationTracker(getActivity().getApplicationContext()); s3Client = new AmazonS3Client(new BasicAWSCredentials(Constants.ACCESS_KEY_ID, Constants.SECRET_KEY)); s3Client.setRegion(Region.getRegion(Regions.US_WEST_2)); tb_cal.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // prevent the calibration button being pressed when either and test or service is running if (tb_service.isChecked()) { Toast.makeText(getActivity(), "Please turn off the service...", Toast.LENGTH_SHORT).show(); tb_cal.setChecked(false); } else if (tb_test.isChecked()) { Toast.makeText(getActivity(), "Please turn off the test...", Toast.LENGTH_SHORT).show(); tb_cal.setChecked(false); } // calibration else { if (isChecked) { tv_cal_text.setText(Constants.cal_text); rl_service.setVisibility(View.INVISIBLE); rl_test.setVisibility(View.INVISIBLE); timer_cal.setVisibility(View.VISIBLE); AlertDialog dialog = new AlertDialog.Builder(getActivity()).create(); dialog.setTitle("Calibration"); dialog.setMessage(Constants.cal_dialog); dialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { timer_cal.setBase(SystemClock.elapsedRealtime()); timer_cal.start(); tv_cal_content.setText("Recording your voice..."); Bundle mbundle = new Bundle(); mbundle.putString("audiopath", calWavFile); Log.i("HomeFragment", "start audio recording service"); // delete the existing calibration data before the recalibration FileProcess.deleteFile(calWavFile); FileProcess.deleteFile(calWavFile + ".jstk.mfcc.txt"); FileProcess.deleteFile(calWavFile + ".YIN.pitch.txt"); // start audio recording Intent recordIntent = new Intent(getActivity(), AudioRecordService.class); recordIntent.putExtras(mbundle); getActivity().startService(recordIntent); } }); dialog.show(); dialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextSize(20); } else { // stop audio recording Intent recordIntent = new Intent(getActivity(), AudioRecordService.class); getActivity().stopService(recordIntent); timer_cal.stop(); tb_cal.setClickable(false); tv_cal_content.setText("Calibrating...."); // start calibration new Calibration().execute(); tb_cal.setClickable(true); tv_cal_text.setText(""); rl_service.setVisibility(View.VISIBLE); rl_test.setVisibility(View.VISIBLE); timer_cal.setVisibility(View.INVISIBLE); } } } }); tb_service.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // prevent the service button being pressed when either and test or calibration is running if (tb_cal.isChecked()) { Toast.makeText(getActivity(), "Please turn off the calibration...", Toast.LENGTH_SHORT).show(); tb_service.setChecked(false); } else if (tb_test.isChecked()) { Toast.makeText(getActivity(), "Please turn off the test...", Toast.LENGTH_SHORT).show(); tb_service.setChecked(false); } // speaker counting service else { Intent countIntent = new Intent(getActivity(), SpeakerCountService.class); if (isChecked) { getActivity().startService(countIntent); } else { getActivity().stopService(countIntent); } } } }); tb_test.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // prevent the test button being pressed when either and service or calibration is running if (tb_cal.isChecked()) { Toast.makeText(getActivity(), "Please turn off the calibration...", Toast.LENGTH_SHORT).show(); tb_test.setChecked(false); } else if (tb_service.isChecked()) { Toast.makeText(getActivity(), "Please turn off the service...", Toast.LENGTH_SHORT).show(); tb_test.setChecked(false); } // perform the speaker counting test else { if (isChecked) { // get location information gps.getLocation(); if (gps.canGetLocation()) { latitude = gps.getLatitude(); longitude = gps.getLongitude(); } else { latitude = -1; longitude = -1; } gps.stopUsingGPS(); timer_test.setBase(SystemClock.elapsedRealtime()); timer_test.start(); tv_debug.setText("Recording..."); testWavFile = testDir + "/" + FileProcess.newFileOnTime("wav"); // start audio recording Bundle mbundle = new Bundle(); mbundle.putString("audiopath", testWavFile); Log.i("HomeFragment", "start audio recording service"); Intent recordIntent = new Intent(getActivity(), AudioRecordService.class); recordIntent.putExtras(mbundle); date = Now.getDate(); start = Now.getTimeOfDay(); getActivity().startService(recordIntent); timer_test.setVisibility(View.VISIBLE); } else { // stop audio recording Intent recordIntent = new Intent(getActivity(), AudioRecordService.class); getActivity().stopService(recordIntent); timer_test.stop(); end = Now.getTimeOfDay(); tb_test.setClickable(false); // start speaker counting test new Test().execute(); timer_test.setVisibility(View.INVISIBLE); tb_test.setClickable(true); } } } }); return view; }
From source file:com.microsoft.band.sdk.heartrate.BandHeartRateAppActivity.java
private void createAlert() { // Make an alert! AlertDialog alertDialog = new AlertDialog.Builder(BandHeartRateAppActivity.this).create(); alertDialog.setTitle("You are stressed!"); alertDialog.setMessage("Comedy has been shown to decrease stress, so watch a video!"); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss();/*w w w . j av a2 s. co m*/ } }); alertDialog.show(); // End Make an Alert }
From source file:group.pals.android.lib.ui.filechooser.utils.ui.bookmark.BookmarkFragment.java
/** * Shows a dialog to let user enter new name or change current name of a * bookmark.//from w ww . j a v a 2s. c o m * * @param context * {@link Context} * @param providerId * the provider ID. * @param id * the bookmark ID. * @param uri * the URI to the bookmark. * @param name * the name. To enter new name, this is the suggested name you * provide. To rename, this is the old name. */ public static void doEnterNewNameOrRenameBookmark(final Context context, final String providerId, final int id, final Uri uri, final String name) { final AlertDialog dialog = Dlg.newDlg(context); View view = LayoutInflater.from(context).inflate(R.layout.afc_simple_text_input_view, null); final EditText textName = (EditText) view.findViewById(R.id.afc_text1); textName.setText(name); textName.selectAll(); textName.setHint(R.string.afc_hint_new_name); textName.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { Ui.showSoftKeyboard(textName, false); Button btn = dialog.getButton(DialogInterface.BUTTON_POSITIVE); if (btn.isEnabled()) btn.performClick(); return true; } return false; }// onEditorAction() }); dialog.setView(view); dialog.setIcon(R.drawable.afc_bookmarks_dark); dialog.setTitle(id < 0 ? R.string.afc_title_new_bookmark : R.string.afc_title_rename); dialog.setButton(DialogInterface.BUTTON_POSITIVE, context.getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String newName = textName.getText().toString().trim(); if (android.text.TextUtils.isEmpty(newName)) { Dlg.toast(context, R.string.afc_msg_bookmark_name_is_invalid, Dlg._LengthShort); return; } Ui.showSoftKeyboard(textName, false); ContentValues values = new ContentValues(); values.put(BookmarkContract.Bookmark._ColumnName, newName); if (id >= 0) { values.put(BookmarkContract.Bookmark._ColumnModificationTime, DbUtils.formatNumber(new Date().getTime())); context.getContentResolver() .update(Uri.withAppendedPath(BookmarkContract.Bookmark._ContentIdUriBase, Uri.encode(Integer.toString(id))), values, null, null); } else { /* * Check if the URI exists or doesn't. If it exists, * update it instead of inserting the new one. */ Cursor cursor = context.getContentResolver().query( BookmarkContract.Bookmark._ContentUri, null, String.format("%s = %s AND %s LIKE %s", BookmarkContract.Bookmark._ColumnProviderId, DatabaseUtils.sqlEscapeString(providerId), BookmarkContract.Bookmark._ColumnUri, DatabaseUtils.sqlEscapeString(uri.toString())), null, null); try { if (cursor != null && cursor.moveToFirst()) { values.put(BookmarkContract.Bookmark._ColumnModificationTime, DbUtils.formatNumber(new Date().getTime())); context.getContentResolver().update( Uri.withAppendedPath(BookmarkContract.Bookmark._ContentIdUriBase, Uri.encode(cursor.getString( cursor.getColumnIndex(BookmarkContract.Bookmark._ID)))), values, null, null); } else { values.put(BookmarkContract.Bookmark._ColumnProviderId, providerId); values.put(BookmarkContract.Bookmark._ColumnUri, uri.toString()); context.getContentResolver().insert(BookmarkContract.Bookmark._ContentUri, values); } } finally { if (cursor != null) cursor.close(); } } Dlg.toast(context, context.getString(R.string.afc_msg_done), Dlg._LengthShort); }// onClick() }); dialog.show(); Ui.showSoftKeyboard(textName, true); final Button buttonOk = dialog.getButton(DialogInterface.BUTTON_POSITIVE); buttonOk.setEnabled(id < 0); textName.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { String newName = s.toString().trim(); boolean enabled = !android.text.TextUtils.isEmpty(newName); buttonOk.setEnabled(enabled); /* * If renaming, only enable button OK if new name is not equal * to the old one. */ if (enabled && id >= 0) buttonOk.setEnabled(!newName.equals(name)); } }); }
From source file:org.smap.smapTask.android.activities.MainTabsActivity.java
@Override protected Dialog onCreateDialog(int id) { switch (id) { case PROGRESS_DIALOG: mProgressDialog = new ProgressDialog(this); DialogInterface.OnClickListener loadingButtonListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss();//from ww w . j a v a 2 s . c om mDownloadTasks.setDownloaderListener(null, mContext); mDownloadTasks.cancel(true); // Refresh the task list Intent intent = new Intent("refresh"); LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent); } }; mProgressDialog.setTitle(getString(R.string.downloading_data)); mProgressDialog.setMessage(mProgressMsg); mProgressDialog.setIcon(android.R.drawable.ic_dialog_info); mProgressDialog.setIndeterminate(true); mProgressDialog.setCancelable(false); mProgressDialog.setButton(getString(R.string.cancel), loadingButtonListener); return mProgressDialog; case ALERT_DIALOG: mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setMessage(mAlertMsg); mAlertDialog.setTitle(getString(R.string.smap_get_tasks)); DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int i) { dialog.dismiss(); } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(getString(R.string.ok), quitListener); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); return mAlertDialog; case PASSWORD_DIALOG: AlertDialog.Builder builder = new AlertDialog.Builder(this); final AlertDialog passwordDialog = builder.create(); passwordDialog.setTitle(getString(R.string.enter_admin_password)); final EditText input = new EditText(this); input.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD); input.setTransformationMethod(PasswordTransformationMethod.getInstance()); passwordDialog.setView(input, 20, 10, 20, 10); passwordDialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String value = input.getText().toString(); String pw = mAdminPreferences.getString(AdminPreferencesActivity.KEY_ADMIN_PW, ""); if (pw.compareTo(value) == 0) { Intent i = new Intent(getApplicationContext(), AdminPreferencesActivity.class); startActivity(i); input.setText(""); passwordDialog.dismiss(); } else { Toast.makeText(MainTabsActivity.this, getString(R.string.admin_password_incorrect), Toast.LENGTH_SHORT).show(); Collect.getInstance().getActivityLogger().logAction(this, "adminPasswordDialog", "PASSWORD_INCORRECT"); } } }); passwordDialog.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Collect.getInstance().getActivityLogger().logAction(this, "adminPasswordDialog", "cancel"); input.setText(""); return; } }); passwordDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); return passwordDialog; } return null; }
From source file:ch.bfh.instacircle.NetworkActiveActivity.java
/** * Checks whether the current network configuration is how it is supposed to * be/*from ww w. j ava 2 s .c om*/ */ public void checkNetworkState() { ConnectivityManager conn = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); SharedPreferences preferences = getSharedPreferences(PREFS_NAME, 0); final String configuredSsid = preferences.getString("SSID", "N/A"); final String password = preferences.getString("password", "N/A"); NetworkInfo nInfo = conn.getNetworkInfo(ConnectivityManager.TYPE_WIFI); String ssid = wifi.getConnectionInfo().getSSID(); Log.d(TAG, "Currently active SSID: " + ssid); // Only check the state if this device is not an access point if (!wifiapmanager.isWifiAPEnabled(wifi)) { Log.d(TAG, "Configured SSID: " + configuredSsid); if (!(nInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED && nInfo.getState() == NetworkInfo.State.CONNECTED && ssid.equals(configuredSsid))) { if (repairInitiated == false && repairTime + 6000 < System.currentTimeMillis()) { repairInitiated = true; repairTime = System.currentTimeMillis(); // create a dialog that ask whether you want to repair the // network connection AlertDialog alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setTitle("InstaCircle - Network Connection Lost"); alertDialog.setMessage( "The connection to the network " + configuredSsid + " has been lost. Try to repair?"); alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Repair", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); adhoc.connectToNetwork(configuredSsid, password, NetworkActiveActivity.this, false); repairInitiated = false; } }); alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Leave", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); WifiManager wifiman = (WifiManager) getSystemService(Context.WIFI_SERVICE); new AdhocWifiManager(wifiman).restoreWifiConfiguration(getBaseContext()); new WifiAPManager().disableHotspot(wifiman, getBaseContext()); NotificationManager notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); notificationManager.cancelAll(); Intent stopIntent = new Intent(NetworkActiveActivity.this, NetworkService.class); stopService(stopIntent); Intent intent = new Intent(NetworkActiveActivity.this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } }); alertDialog.show(); } } else { repairInitiated = false; } } }