List of usage examples for android.net Uri getPort
public abstract int getPort();
From source file:me.xingrz.prox.tcp.TcpProxySession.java
public void setDestination(Uri proxy) { if (proxy.getScheme().equals(AutoConfigManager.PROXY_TYPE_HTTP)) { outgoingTunnel.setProxy(// w w w. ja v a 2 s . c o m new HttpConnectHandler(outgoingTunnel, getRemoteAddress().getHostAddress(), getRemotePort())); logger.v("Use HTTP proxy %s:%d", proxy.getHost(), proxy.getPort()); destination = new InetSocketAddress(proxy.getHost(), proxy.getPort()); } else { logger.v("Unsupported proxy scheme %s, ignored", proxy.getScheme()); } }
From source file:org.fdroid.fdroid.net.DownloaderService.java
/** * This method is invoked on the worker thread with a request to process. * Only one Intent is processed at a time, but the processing happens on a * worker thread that runs independently from other application logic. * So, if this code takes a long time, it will hold up other requests to * the same DownloaderService, but it will not hold up anything else. * When all requests have been handled, the DownloaderService stops itself, * so you should not ever call {@link #stopSelf}. * <p/>/*from w ww . ja va 2s . c om*/ * Downloads are put into subdirectories based on hostname/port of each repo * to prevent files with the same names from conflicting. Each repo enforces * unique APK file names on the server side. * * @param intent The {@link Intent} passed via {@link * android.content.Context#startService(Intent)}. */ protected void handleIntent(Intent intent) { final Uri uri = intent.getData(); File downloadDir = new File(Utils.getApkCacheDir(this), uri.getHost() + "-" + uri.getPort()); downloadDir.mkdirs(); final SanitizedFile localFile = new SanitizedFile(downloadDir, uri.getLastPathSegment()); final String packageName = getPackageNameFromIntent(intent); sendBroadcast(uri, Downloader.ACTION_STARTED, localFile); if (Preferences.get().isUpdateNotificationEnabled()) { Notification notification = createNotification(intent.getDataString(), getPackageNameFromIntent(intent)) .build(); startForeground(NOTIFY_DOWNLOADING, notification); } try { downloader = DownloaderFactory.create(this, uri, localFile); downloader.setListener(new Downloader.DownloaderProgressListener() { @Override public void sendProgress(URL sourceUrl, int bytesRead, int totalBytes) { if (isActive(uri.toString())) { Intent intent = new Intent(Downloader.ACTION_PROGRESS); intent.setData(uri); intent.putExtra(Downloader.EXTRA_BYTES_READ, bytesRead); intent.putExtra(Downloader.EXTRA_TOTAL_BYTES, totalBytes); localBroadcastManager.sendBroadcast(intent); if (Preferences.get().isUpdateNotificationEnabled()) { NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Notification notification = createNotification(uri.toString(), packageName) .setProgress(totalBytes, bytesRead, false).build(); nm.notify(NOTIFY_DOWNLOADING, notification); } } } }); downloader.download(); sendBroadcast(uri, Downloader.ACTION_COMPLETE, localFile); DownloadCompleteService.notify(this, packageName, intent.getDataString()); } catch (InterruptedException e) { sendBroadcast(uri, Downloader.ACTION_INTERRUPTED, localFile); } catch (IOException e) { e.printStackTrace(); sendBroadcast(uri, Downloader.ACTION_INTERRUPTED, localFile, e.getLocalizedMessage()); } finally { if (downloader != null) { downloader.close(); } // May have already been removed in response to a cancel intent, but that wont cause // problems if we ask to remove it again. QUEUE_WHATS.remove(uri.toString()); stopForeground(true); } downloader = null; }
From source file:ca.frozen.rpicameraviewer.activities.SourceFragment.java
public Source getAndCheckEditedSource() { // get the updated source Source editedSource = getSource(); // check the address if (forCamera || editedSource.connectionType == Source.ConnectionType.RawMulticast) { // make sure there's an address if (editedSource.address.isEmpty()) { App.error(getActivity(), R.string.error_no_address); return null; }// w ww . j ava 2 s . co m try { // check the address Uri uri = Uri.parse(editedSource.address); // check IP addresses String address = uri.getPath(); char c = address.charAt(0); if (c >= '0' && c <= '9') { if (!checkIpAddress(address)) { App.error(getActivity(), R.string.error_bad_address); return null; } } // use the port if it's there int port = uri.getPort(); if (port != -1) { editedSource.address = editedSource.address.replace(":" + port, ""); if (editedSource.port <= 0) { editedSource.port = port; } } // for HTTP, remove the scheme if it's there if (editedSource.connectionType == Source.ConnectionType.RawHttp) { String scheme = uri.getScheme(); if (scheme != null && !scheme.isEmpty()) { editedSource.address = editedSource.address.substring(scheme.length() + 3); } } } catch (Exception ex) { App.error(getActivity(), R.string.error_bad_address); return null; } // make sure it's a valid multicast address if (editedSource.connectionType == Source.ConnectionType.RawMulticast) { int check = checkMulticastAddress(editedSource.address); if (check < 0) { App.error(getActivity(), R.string.error_bad_multicast_address); return null; } else if (check == 0) { Toast.makeText(getActivity(), R.string.warning_multicast_address, Toast.LENGTH_LONG).show(); } } } // for settings, make sure there's a port if (!forCamera) { if (editedSource.port == 0) { App.error(getActivity(), R.string.error_no_port); return null; } } // make sure the port is within range if (editedSource.port != 0 && (editedSource.port < MIN_PORT || editedSource.port > MAX_PORT)) { App.error(getActivity(), String.format(getString(R.string.error_bad_port), MIN_PORT, MAX_PORT)); return null; } // check the width if (editedSource.width < 0) { App.error(getActivity(), R.string.error_bad_width); return null; } // check the height if (editedSource.height < 0) { App.error(getActivity(), R.string.error_bad_height); return null; } // check the FPS if (editedSource.fps < 0) { App.error(getActivity(), R.string.error_bad_fps); return null; } // check the BPS if (editedSource.bps < 0) { App.error(getActivity(), R.string.error_bad_bps); return null; } // return the successfully edited source return editedSource; }
From source file:at.bitfire.davdroid.ui.setup.LoginCredentialsFragment.java
protected LoginCredentials validateLoginData() { if (radioUseEmail.isChecked()) { URI uri = null;//from www .java 2s . c o m boolean valid = true; String email = editEmailAddress.getText().toString(); if (!email.matches(".+@.+")) { editEmailAddress.setError(getString(R.string.login_email_address_error)); valid = false; } else try { uri = new URI("mailto", email, null); } catch (URISyntaxException e) { editEmailAddress.setError(e.getLocalizedMessage()); valid = false; } String password = editEmailPassword.getText().toString(); if (password.isEmpty()) { editEmailPassword.setError(getString(R.string.login_password_required)); valid = false; } return valid ? new LoginCredentials(uri, email, password) : null; } else if (radioUseURL.isChecked()) { URI uri = null; boolean valid = true; Uri baseUrl = Uri.parse(editBaseURL.getText().toString()); String scheme = baseUrl.getScheme(); if ("https".equalsIgnoreCase(scheme) || "http".equalsIgnoreCase(scheme)) { String host = baseUrl.getHost(); if (StringUtils.isEmpty(host)) { editBaseURL.setError(getString(R.string.login_url_host_name_required)); valid = false; } else try { host = IDN.toASCII(host); } catch (IllegalArgumentException e) { Constants.log.log(Level.WARNING, "Host name not conforming to RFC 3490", e); } String path = baseUrl.getEncodedPath(); int port = baseUrl.getPort(); try { uri = new URI(baseUrl.getScheme(), null, host, port, path, null, null); } catch (URISyntaxException e) { editBaseURL.setError(e.getLocalizedMessage()); valid = false; } } else { editBaseURL.setError(getString(R.string.login_url_must_be_http_or_https)); valid = false; } String userName = editUserName.getText().toString(); if (userName.isEmpty()) { editUserName.setError(getString(R.string.login_user_name_required)); valid = false; } String password = editUrlPassword.getText().toString(); if (password.isEmpty()) { editUrlPassword.setError(getString(R.string.login_password_required)); valid = false; } return valid ? new LoginCredentials(uri, userName, password) : null; } return null; }
From source file:com.morphoss.acal.service.connector.AcalRequestor.java
/** * Interpret the URI in the string to set protocol, host, port & path for the next request. * If the URI only matches a path part then protocol/host/port will be unchanged. This call * will only allow for path parts that are anchored to the web root. This is used internally * for following Location: redirects./*from w w w . ja v a 2 s . c o m*/ * * This is also used to interpret the 'path' parameter to the request calls generally. * * @param uriString */ public void interpretUriString(String uriString) { if (uriString == null) return; // Match a URL, including an ipv6 address like http://[DEAD:BEEF:CAFE:F00D::]:8008/ final Pattern uriMatcher = Pattern.compile("^(?:(https?)://)?" + // Protocol "(" + // host spec "(?:(?:[a-z0-9-]+[.]){1,7}(?:[a-z0-9-]+))" + // Hostname or IPv4 address "|(?:\\[(?:[0-9a-f]{0,4}:)+(?:[0-9a-f]{0,4})?\\])" + // IPv6 address ")" + "(?:[:]([0-9]{2,5}))?" + // Port number "(/.*)?$" // Path bit. , Pattern.CASE_INSENSITIVE | Pattern.DOTALL); final Pattern pathMatcher = Pattern.compile("^(/.*)$"); if (Constants.LOG_VERBOSE) Log.println(Constants.LOGV, TAG, "Interpreting '" + uriString + "'"); Matcher m = uriMatcher.matcher(uriString); if (m.matches()) { if (m.group(1) != null && !m.group(1).equals("")) { if (Constants.LOG_VERBOSE) Log.println(Constants.LOGV, TAG, "Found protocol '" + m.group(1) + "'"); protocol = m.group(1); if (m.group(3) == null || m.group(3).equals("")) { port = (protocol.equals(PROTOCOL_HTTP) ? 80 : 443); } } if (m.group(2) != null) { if (Constants.LOG_VERBOSE) Log.println(Constants.LOGV, TAG, "Found hostname '" + m.group(2) + "'"); setHostName(m.group(2)); } if (m.group(3) != null && !m.group(3).equals("")) { if (Constants.LOG_VERBOSE) Log.println(Constants.LOGV, TAG, "Found port '" + m.group(3) + "'"); port = Integer.parseInt(m.group(3)); if (m.group(1) != null && (port == 0 || port == 80 || port == 443)) { port = (protocol.equals(PROTOCOL_HTTP) ? 80 : 443); } } if (m.group(4) != null && !m.group(4).equals("")) { if (Constants.LOG_VERBOSE) Log.println(Constants.LOGV, TAG, "Found path '" + m.group(4) + "'"); setPath(m.group(4)); } if (!initialised) initialise(); } else { m = pathMatcher.matcher(uriString); if (m.find()) { if (Constants.LOG_VERBOSE) Log.println(Constants.LOGV, TAG, "Found relative path '" + m.group(1) + "'"); setPath(m.group(1)); } else { if (Constants.LOG_DEBUG) Log.println(Constants.LOGD, TAG, "Using Uri class to process redirect..."); Uri newLocation = Uri.parse(uriString); if (newLocation.getHost() != null) setHostName(newLocation.getHost()); setPortProtocol(newLocation.getPort(), newLocation.getScheme()); setPath(newLocation.getPath()); if (Constants.LOG_VERBOSE) Log.println(Constants.LOGV, TAG, "Found new location at '" + fullUrl() + "'"); } } }
From source file:org.appcelerator.titanium.util.TiUIHelper.java
/** * To get the redirected Uri// ww w. ja va 2s.c om * @param Uri */ public static Uri getRedirectUri(Uri mUri) throws MalformedURLException, IOException { if (!TiC.HONEYCOMB_OR_GREATER && ("http".equals(mUri.getScheme()) || "https".equals(mUri.getScheme()))) { // Media player doesn't handle redirects, try to follow them // here. (Redirects work fine without this in ICS.) while (true) { // java.net.URL doesn't handle rtsp if (mUri.getScheme() != null && mUri.getScheme().equals("rtsp")) break; URL url = new URL(mUri.toString()); HttpURLConnection cn = (HttpURLConnection) url.openConnection(); cn.setInstanceFollowRedirects(false); String location = cn.getHeaderField("Location"); if (location != null) { String host = mUri.getHost(); int port = mUri.getPort(); String scheme = mUri.getScheme(); mUri = Uri.parse(location); if (mUri.getScheme() == null) { // Absolute URL on existing host/port/scheme if (scheme == null) { scheme = "http"; } String authority = port == -1 ? host : host + ":" + port; mUri = mUri.buildUpon().scheme(scheme).encodedAuthority(authority).build(); } } else { break; } } } return mUri; }
From source file:com.owncloud.android.authentication.AuthenticatorActivity.java
/** * Creates a new account through the Account Authenticator that started this * activity./*from ww w . j av a 2 s . c o m*/ * * This makes the account permanent. * * TODO Decide how to name the OAuth accounts */ private boolean createAccount() { // / create and save new ownCloud account boolean isOAuth = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mAuthTokenType); boolean isSaml = AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType); Uri uri = Uri.parse(mHostBaseUrl); String username = mUsernameInput.getText().toString().trim(); username = username + "@" + location; if (isSaml) { username = getUserNameForSamlSso(); } else if (isOAuth) { username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong(); } String accountName = username + "@" + uri.getHost(); if (uri.getPort() >= 0) { accountName += ":" + uri.getPort(); } mAccount = new Account(accountName, AccountAuthenticator.ACCOUNT_TYPE); if (AccountUtils.exists(mAccount, getApplicationContext())) { // fail - not a new account, but an existing one; disallow RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW); updateAuthStatusIconAndText(result); showAuthStatus(); Log_OC.d(TAG, result.getLogMessage()); return false; } else { if (isOAuth || isSaml) { mAccountMgr.addAccountExplicitly(mAccount, "", null); // with // external // authorizations, // the // password // is // never // input // in the // app } else { mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null); } // / add the new account as default in preferences, if there is none // already Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this); if (defaultAccount == null) { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit(); editor.putString("select_oc_account", accountName); editor.commit(); } // / prepare result to return to the Authenticator // TODO check again what the Authenticator makes with it; probably // has the same effect as addAccountExplicitly, but it's not well // done final Intent intent = new Intent(); intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, AccountAuthenticator.ACCOUNT_TYPE); intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name); /* * if (!isOAuth) intent.putExtra(AccountManager.KEY_AUTHTOKEN, * AccountAuthenticator.ACCOUNT_TYPE); */ intent.putExtra(AccountManager.KEY_USERDATA, username); if (isOAuth || isSaml) { mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken); } // / add user data to the new account; TODO probably can be done in // the last parameter addAccountExplicitly, or in KEY_USERDATA mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION, mDiscoveredVersion.toString()); mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL, mHostBaseUrl); if (isSaml) { mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE"); } else if (isOAuth) { mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_OAUTH2, "TRUE"); } setAccountAuthenticatorResult(intent.getExtras()); setResult(RESULT_OK, intent); // / immediately request for the synchronization of the new account Bundle bundle = new Bundle(); bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); ContentResolver.requestSync(mAccount, AccountAuthenticator.AUTHORITY, bundle); syncAccount(); // Bundle bundle = new Bundle(); // bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); // ContentResolver.requestSync(mAccount, // AccountAuthenticator.AUTHORITY, bundle); return true; } }
From source file:androidVNC.VncCanvasActivity.java
@Override public void onCreate(Bundle icicle) { super.onCreate(icicle); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); database = new VncDatabase(this); connection = new ConnectionBean(); Intent i = getIntent();/*from w w w .j a v a 2 s .c o m*/ Uri data = i.getData(); if ((data != null) && (data.getScheme().equals("vnc"))) { String host = data.getHost(); // This should not happen according to Uri contract, but bug introduced in Froyo (2.2) // has made this parsing of host necessary int index = host.indexOf(':'); int port; if (index != -1) { try { port = Integer.parseInt(host.substring(index + 1)); } catch (NumberFormatException nfe) { port = 0; } host = host.substring(0, index); } else { port = data.getPort(); } if (host.equals(VncConstants.CONNECTION)) { if (connection.Gen_read(database.getReadableDatabase(), port)) { MostRecentBean bean = androidVNC.getMostRecent(database.getReadableDatabase()); if (bean != null) { bean.setConnectionId(connection.get_Id()); bean.Gen_update(database.getWritableDatabase()); } } } else { connection.setAddress(host); connection.setNickname(connection.getAddress()); connection.setPort(port); List<String> path = data.getPathSegments(); if (path.size() >= 1) { connection.setColorModel(path.get(0)); } if (path.size() >= 2) { connection.setPassword(path.get(1)); } connection.save(database.getWritableDatabase()); } } else { Bundle extras = i.getExtras(); if (extras != null) { connection.Gen_populate((ContentValues) extras.getParcelable(VncConstants.CONNECTION)); } if (connection.getPort() == 0) connection.setPort(5900); // Parse a HOST:PORT entry String host = connection.getAddress(); if (host.indexOf(':') > -1) { String p = host.substring(host.indexOf(':') + 1); try { connection.setPort(Integer.parseInt(p)); } catch (Exception e) { } connection.setAddress(host.substring(0, host.indexOf(':'))); } } try { setContentView(fi.aalto.openoranges.project1.mcc.R.layout.canvas); vncCanvas = (VncCanvas) findViewById(fi.aalto.openoranges.project1.mcc.R.id.vnc_canvas); zoomer = (ZoomControls) findViewById(R.id.zoomer); } catch (Exception e) { e.printStackTrace(); } vncCanvas.initializeVncCanvas(connection, new Runnable() { public void run() { setModes(); } }); vncCanvas.setOnGenericMotionListener(this); zoomer.hide(); zoomer.setOnZoomInClickListener(new View.OnClickListener() { /* * (non-Javadoc) * * @see android.view.View.OnClickListener#onClick(android.view.View) */ @Override public void onClick(View v) { showZoomer(true); vncCanvas.scaling.zoomIn(VncCanvasActivity.this); } }); zoomer.setOnZoomOutClickListener(new View.OnClickListener() { /* * (non-Javadoc) * * @see android.view.View.OnClickListener#onClick(android.view.View) */ @Override public void onClick(View v) { showZoomer(true); vncCanvas.scaling.zoomOut(VncCanvasActivity.this); } }); zoomer.setOnZoomKeyboardClickListener(new View.OnClickListener() { /* * (non-Javadoc) * * @see android.view.View.OnClickListener#onClick(android.view.View) */ @Override public void onClick(View v) { InputMethodManager inputMgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMgr.toggleSoftInput(0, 0); } }); panner = new Panner(this, vncCanvas.handler); inputHandler = getInputHandlerById(fi.aalto.openoranges.project1.mcc.R.id.itemInputFitToScreen); mToken = getIntent().getStringExtra("token"); mId = getIntent().getStringExtra("id"); mName = getIntent().getStringExtra("name"); //listener for the back-button registerClickCallback(); //Notification in status bar NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(VncCanvasActivity.this) .setSmallIcon(R.drawable.icon_white).setContentTitle(mName + " running") .setContentText("Click to open the application screen"); // Creates an explicit intent for an Activity in your app Intent resultIntent = new Intent(VncCanvasActivity.this, VncCanvasActivity.class); resultIntent.setAction(Long.toString(System.currentTimeMillis())); mBuilder.setContentIntent(PendingIntent.getActivity(VncCanvasActivity.this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT)); NotificationManager mNotificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); // mNotifyID allows you to update the notification later on. mNotificationManager.notify(mNotifyId, mBuilder.build()); startService(); }
From source file:org.opendatakit.survey.android.activities.MainMenuActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // android.os.Debug.waitForDebugger(); mPropertyManager = new PropertyManager(this); // must be at the beginning of any activity that can be called from an // external intent setAppName("survey"); Uri uri = getIntent().getData(); Uri formUri = null;/*from w w w . j ava 2s. c om*/ if (uri != null) { // initialize to the URI, then we will customize further based upon the // savedInstanceState... final Uri uriFormsProvider = FormsProviderAPI.CONTENT_URI; final Uri uriWebView = UrlUtils.getWebViewContentUri(this); if (uri.getScheme().equalsIgnoreCase(uriFormsProvider.getScheme()) && uri.getAuthority().equalsIgnoreCase(uriFormsProvider.getAuthority())) { List<String> segments = uri.getPathSegments(); if (segments != null && segments.size() == 1) { String appName = segments.get(0); setAppName(appName); } else if (segments != null && segments.size() >= 2) { String appName = segments.get(0); setAppName(appName); formUri = Uri.withAppendedPath(Uri.withAppendedPath(uriFormsProvider, appName), segments.get(1)); } else { assignContentView(); createErrorDialog(getString(R.string.invalid_uri_expecting_n_segments, uri.toString(), 2), EXIT); return; } } else if (uri.getScheme().equals(uriWebView.getScheme()) && uri.getAuthority().equals(uriWebView.getAuthority()) && uri.getPort() == uriWebView.getPort()) { List<String> segments = uri.getPathSegments(); if (segments != null && segments.size() == 1) { String appName = segments.get(0); setAppName(appName); } else { assignContentView(); createErrorDialog(getString(R.string.invalid_uri_expecting_one_segment, uri.toString()), EXIT); return; } } else { assignContentView(); createErrorDialog(getString(R.string.unrecognized_uri, uri.toString(), uriWebView.toString(), uriFormsProvider.toString()), EXIT); return; } } if (savedInstanceState != null) { // if appName is explicitly set, use it... setAppName(savedInstanceState.containsKey(APP_NAME) ? savedInstanceState.getString(APP_NAME) : getAppName()); if (savedInstanceState.containsKey(CONFLICT_TABLES)) { mConflictTables = savedInstanceState.getBundle(CONFLICT_TABLES); } } WebLogger.getLogger(getAppName()).i(t, "Starting up, creating directories"); try { String appName = getAppName(); if (appName != null && appName.length() != 0) { ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); } } catch (RuntimeException e) { assignContentView(); createErrorDialog(e.getMessage(), EXIT); return; } if (savedInstanceState != null) { // if we are restoring, assume that initialization has already occurred. pageWaitingForData = savedInstanceState.containsKey(PAGE_WAITING_FOR_DATA) ? savedInstanceState.getString(PAGE_WAITING_FOR_DATA) : null; pathWaitingForData = savedInstanceState.containsKey(PATH_WAITING_FOR_DATA) ? savedInstanceState.getString(PATH_WAITING_FOR_DATA) : null; actionWaitingForData = savedInstanceState.containsKey(ACTION_WAITING_FOR_DATA) ? savedInstanceState.getString(ACTION_WAITING_FOR_DATA) : null; currentFragment = ScreenList.valueOf(savedInstanceState.containsKey(CURRENT_FRAGMENT) ? savedInstanceState.getString(CURRENT_FRAGMENT) : currentFragment.name()); if (savedInstanceState.containsKey(FORM_URI)) { FormIdStruct newForm = FormIdStruct.retrieveFormIdStruct(getContentResolver(), Uri.parse(savedInstanceState.getString(FORM_URI))); if (newForm != null) { setAppName(newForm.appName); setCurrentForm(newForm); } } setInstanceId(savedInstanceState.containsKey(INSTANCE_ID) ? savedInstanceState.getString(INSTANCE_ID) : getInstanceId()); setUploadTableId( savedInstanceState.containsKey(UPLOAD_TABLE_ID) ? savedInstanceState.getString(UPLOAD_TABLE_ID) : getUploadTableId()); String tmpScreenPath = savedInstanceState.containsKey(SCREEN_PATH) ? savedInstanceState.getString(SCREEN_PATH) : getScreenPath(); String tmpControllerState = savedInstanceState.containsKey(CONTROLLER_STATE) ? savedInstanceState.getString(CONTROLLER_STATE) : getControllerState(); setSectionScreenState(tmpScreenPath, tmpControllerState); setAuxillaryHash( savedInstanceState.containsKey(AUXILLARY_HASH) ? savedInstanceState.getString(AUXILLARY_HASH) : getAuxillaryHash()); if (savedInstanceState.containsKey(SESSION_VARIABLES)) { sessionVariables = savedInstanceState.getBundle(SESSION_VARIABLES); } if (savedInstanceState.containsKey(SECTION_STATE_SCREEN_HISTORY)) { sectionStateScreenHistory = savedInstanceState.getParcelableArrayList(SECTION_STATE_SCREEN_HISTORY); } } else if (formUri != null) { // request specifies a specific formUri -- try to open that FormIdStruct newForm = FormIdStruct.retrieveFormIdStruct(getContentResolver(), formUri); if (newForm == null) { // can't find it -- launch the initialization dialog to hopefully // discover it. WebLogger.getLogger(getAppName()).i(t, "onCreate -- calling setRunInitializationTask"); Survey.getInstance().setRunInitializationTask(getAppName()); currentFragment = ScreenList.WEBKIT; } else { transitionToFormHelper(uri, newForm); } } assignContentView(); }
From source file:org.opendatakit.survey.activities.MainMenuActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // android.os.Debug.waitForDebugger(); submenuPage = getIntentExtras().getString("_sync_state"); try {//from ww w . j a v a 2 s.com // ensure that we have a BackgroundTaskFragment... // create it programmatically because if we place it in the // layout XML, it will be recreated with each screen rotation // and we don't want that!!! mPropertyManager = new PropertyManager(this); // must be at the beginning of any activity that can be called from an // external intent setAppName(ODKFileUtils.getOdkDefaultAppName()); Uri uri = getIntent().getData(); Uri formUri = null; if (uri != null) { // initialize to the URI, then we will customize further based upon the // savedInstanceState... final Uri uriFormsProvider = FormsProviderAPI.CONTENT_URI; final Uri uriWebView = UrlUtils.getWebViewContentUri(this); if (uri.getScheme().equalsIgnoreCase(uriFormsProvider.getScheme()) && uri.getAuthority().equalsIgnoreCase(uriFormsProvider.getAuthority())) { List<String> segments = uri.getPathSegments(); if (segments != null && segments.size() == 1) { String appName = segments.get(0); setAppName(appName); } else if (segments != null && segments.size() >= 2) { String appName = segments.get(0); setAppName(appName); String tableId = segments.get(1); String formId = (segments.size() > 2) ? segments.get(2) : null; formUri = Uri.withAppendedPath(Uri.withAppendedPath( Uri.withAppendedPath(FormsProviderAPI.CONTENT_URI, appName), tableId), formId); } else { createErrorDialog(getString(R.string.invalid_uri_expecting_n_segments, uri.toString(), 2), EXIT); return; } } else if (uri.getScheme().equals(uriWebView.getScheme()) && uri.getAuthority().equals(uriWebView.getAuthority()) && uri.getPort() == uriWebView.getPort()) { List<String> segments = uri.getPathSegments(); if (segments != null && segments.size() == 1) { String appName = segments.get(0); setAppName(appName); } else { createErrorDialog(getString(R.string.invalid_uri_expecting_one_segment, uri.toString()), EXIT); return; } } else { createErrorDialog(getString(R.string.unrecognized_uri, uri.toString(), uriWebView.toString(), uriFormsProvider.toString()), EXIT); return; } } if (savedInstanceState != null) { // if appName is explicitly set, use it... setAppName(savedInstanceState.containsKey(IntentConsts.INTENT_KEY_APP_NAME) ? savedInstanceState.getString(IntentConsts.INTENT_KEY_APP_NAME) : getAppName()); if (savedInstanceState.containsKey(CONFLICT_TABLES)) { mConflictTables = savedInstanceState.getBundle(CONFLICT_TABLES); } } try { String appName = getAppName(); if (appName != null && appName.length() != 0) { ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); } } catch (RuntimeException e) { createErrorDialog(e.getMessage(), EXIT); return; } WebLogger.getLogger(getAppName()).i(t, "Starting up, creating directories"); if (savedInstanceState != null) { // if we are restoring, assume that initialization has already occurred. dispatchStringWaitingForData = savedInstanceState.containsKey(DISPATCH_STRING_WAITING_FOR_DATA) ? savedInstanceState.getString(DISPATCH_STRING_WAITING_FOR_DATA) : null; actionWaitingForData = savedInstanceState.containsKey(ACTION_WAITING_FOR_DATA) ? savedInstanceState.getString(ACTION_WAITING_FOR_DATA) : null; currentFragment = ScreenList.valueOf(savedInstanceState.containsKey(CURRENT_FRAGMENT) ? savedInstanceState.getString(CURRENT_FRAGMENT) : currentFragment.name()); if (savedInstanceState.containsKey(FORM_URI)) { FormIdStruct newForm = FormIdStruct.retrieveFormIdStruct(getContentResolver(), Uri.parse(savedInstanceState.getString(FORM_URI))); if (newForm != null) { setAppName(newForm.appName); setCurrentForm(newForm); } } setInstanceId( savedInstanceState.containsKey(INSTANCE_ID) ? savedInstanceState.getString(INSTANCE_ID) : getInstanceId()); setUploadTableId(savedInstanceState.containsKey(UPLOAD_TABLE_ID) ? savedInstanceState.getString(UPLOAD_TABLE_ID) : getUploadTableId()); String tmpScreenPath = savedInstanceState.containsKey(SCREEN_PATH) ? savedInstanceState.getString(SCREEN_PATH) : getScreenPath(); String tmpControllerState = savedInstanceState.containsKey(CONTROLLER_STATE) ? savedInstanceState.getString(CONTROLLER_STATE) : getControllerState(); setSectionScreenState(tmpScreenPath, tmpControllerState); setAuxillaryHash(savedInstanceState.containsKey(AUXILLARY_HASH) ? savedInstanceState.getString(AUXILLARY_HASH) : getAuxillaryHash()); if (savedInstanceState.containsKey(SESSION_VARIABLES)) { sessionVariables = savedInstanceState.getBundle(SESSION_VARIABLES); } if (savedInstanceState.containsKey(SECTION_STATE_SCREEN_HISTORY)) { sectionStateScreenHistory = savedInstanceState .getParcelableArrayList(SECTION_STATE_SCREEN_HISTORY); } if (savedInstanceState.containsKey(QUEUED_ACTIONS)) { String[] actionOutcomesArray = savedInstanceState.getStringArray(QUEUED_ACTIONS); queuedActions.clear(); queuedActions.addAll(Arrays.asList(actionOutcomesArray)); } if (savedInstanceState != null && savedInstanceState.containsKey(RESPONSE_JSON)) { String[] pendingResponseJSON = savedInstanceState.getStringArray(RESPONSE_JSON); queueResponseJSON.addAll(Arrays.asList(pendingResponseJSON)); } } else if (formUri != null) { // request specifies a specific formUri -- try to open that FormIdStruct newForm = FormIdStruct.retrieveFormIdStruct(getContentResolver(), formUri); if (newForm == null) { // can't find it -- launch the initialization dialog to hopefully // discover it. WebLogger.getLogger(getAppName()).i(t, "onCreate -- calling setRunInitializationTask"); ((Survey) getApplication()).setRunInitializationTask(getAppName()); currentFragment = ScreenList.WEBKIT; } else { transitionToFormHelper(uri, newForm); } } } catch (Exception e) { createErrorDialog(e.getMessage(), EXIT); } finally { setContentView(R.layout.main_screen); ActionBar actionBar = getActionBar(); actionBar.show(); } }