List of usage examples for android.content Intent getBooleanExtra
public boolean getBooleanExtra(String name, boolean defaultValue)
From source file:com.android.email.activity.zx.MessageView.java
@Override public void onCreate(Bundle icicle) { super.onCreate(icicle); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.message_view); mSubjectView = (TextView) findViewById(R.id.subject); mFromView = (TextView) findViewById(R.id.from); mToView = (TextView) findViewById(R.id.to); mCcView = (TextView) findViewById(R.id.cc); mCcContainerView = findViewById(R.id.cc_container); mDateView = (TextView) findViewById(R.id.date); mTimeView = (TextView) findViewById(R.id.time); mMessageContentView = (WebView) findViewById(R.id.message_content); mAttachments = (LinearLayout) findViewById(R.id.attachments); mAttachmentIcon = (ImageView) findViewById(R.id.attachment); mShowPicturesSection = findViewById(R.id.show_pictures_section); mSenderPresenceView = (ImageView) findViewById(R.id.presence); mMessageContentView.setVerticalScrollBarEnabled(false); mAttachments.setVisibility(View.GONE); mAttachmentIcon.setVisibility(View.GONE); mFromView.setOnClickListener(this); mSenderPresenceView.setOnClickListener(this); findViewById(R.id.reply).setOnClickListener(this); findViewById(R.id.reply_all).setOnClickListener(this); findViewById(R.id.delete).setOnClickListener(this); findViewById(R.id.show_pictures).setOnClickListener(this); mMessageContentView.getSettings().setBlockNetworkImage(true); mMessageContentView.getSettings().setSupportZoom(false); setTitle(""); mDateFormat = android.text.format.DateFormat.getDateFormat(this); // short format mTimeFormat = android.text.format.DateFormat.getTimeFormat(this); // 12/24 date format Intent intent = getIntent(); mAccount = (Account) intent.getSerializableExtra(EXTRA_ACCOUNT); mFolder = intent.getStringExtra(EXTRA_FOLDER); mMessageUid = intent.getStringExtra(EXTRA_MESSAGE); mFolderUids = intent.getStringArrayListExtra(EXTRA_FOLDER_UIDS); View next = findViewById(R.id.next); View previous = findViewById(R.id.previous); /*//from ww w . ja va2 s.c o m * Next and Previous Message are not shown in landscape mode, so * we need to check before we use them. */ if (next != null && previous != null) { next.setOnClickListener(this); previous.setOnClickListener(this); findSurroundingMessagesUid(); previous.setVisibility(mPreviousMessageUid != null ? View.VISIBLE : View.GONE); next.setVisibility(mNextMessageUid != null ? View.VISIBLE : View.GONE); boolean goNext = intent.getBooleanExtra(EXTRA_NEXT, false); if (goNext) { next.requestFocus(); } } MessagingController.getInstance(getApplication()).addListener(mListener); new Thread() { @Override public void run() { // TODO this is a spot that should be eventually handled by a MessagingController // thread pool. We want it in a thread but it can't be blocked by the normal // synchronization stuff in MC. Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); MessagingController.getInstance(getApplication()).loadMessageForView(mAccount, mFolder, mMessageUid, mListener); } }.start(); }
From source file:com.android.cts.verifier.managedprovisioning.ByodHelperActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { Log.w(TAG, "Restored state"); mOriginalSettings = savedInstanceState.getBundle(ORIGINAL_SETTINGS_NAME); } else {// ww w .j ava 2 s . c om mOriginalSettings = new Bundle(); } mAdminReceiverComponent = new ComponentName(this, DeviceAdminTestReceiver.class.getName()); mDevicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Intent intent = getIntent(); String action = intent.getAction(); Log.d(TAG, "ByodHelperActivity.onCreate: " + action); // we are explicitly started by {@link DeviceAdminTestReceiver} after a successful provisioning. if (action.equals(ACTION_PROFILE_PROVISIONED)) { // Jump back to CTS verifier with result. Intent response = new Intent(ACTION_PROFILE_OWNER_STATUS); response.putExtra(EXTRA_PROVISIONED, isProfileOwner()); startActivityInPrimary(response); // Queried by CtsVerifier in the primary side using startActivityForResult. } else if (action.equals(ACTION_QUERY_PROFILE_OWNER)) { Intent response = new Intent(); response.putExtra(EXTRA_PROVISIONED, isProfileOwner()); setResult(RESULT_OK, response); // Request to delete work profile. } else if (action.equals(ACTION_REMOVE_MANAGED_PROFILE)) { if (isProfileOwner()) { Log.d(TAG, "Clearing cross profile intents"); mDevicePolicyManager.clearCrossProfileIntentFilters(mAdminReceiverComponent); mDevicePolicyManager.wipeData(0); showToast(R.string.provisioning_byod_profile_deleted); } } else if (action.equals(ACTION_INSTALL_APK)) { boolean allowNonMarket = intent.getBooleanExtra(EXTRA_ALLOW_NON_MARKET_APPS, false); boolean wasAllowed = getAllowNonMarket(); // Update permission to install non-market apps setAllowNonMarket(allowNonMarket); mOriginalSettings.putBoolean(INSTALL_NON_MARKET_APPS, wasAllowed); // Request to install a non-market application- easiest way is to reinstall ourself final Intent installIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE) .setData(Uri.parse("package:" + getPackageName())) .putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true).putExtra(Intent.EXTRA_RETURN_RESULT, true); startActivityForResult(installIntent, REQUEST_INSTALL_PACKAGE); // Not yet ready to finish- wait until the result comes back return; // Queried by CtsVerifier in the primary side using startActivityForResult. } else if (action.equals(ACTION_CHECK_INTENT_FILTERS)) { final boolean intentFiltersSetForManagedIntents = new IntentFiltersTestHelper(this) .checkCrossProfileIntentFilters(IntentFiltersTestHelper.FLAG_INTENTS_FROM_MANAGED); setResult(intentFiltersSetForManagedIntents ? RESULT_OK : RESULT_FAILED, null); } else if (action.equals(ACTION_CAPTURE_AND_CHECK_IMAGE)) { // We need the camera permission to send the image capture intent. grantCameraPermissionToSelf(); Intent captureImageIntent = getCaptureImageIntent(); Pair<File, Uri> pair = getTempUri("image.jpg"); mImageFile = pair.first; mImageUri = pair.second; captureImageIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri); if (captureImageIntent.resolveActivity(getPackageManager()) != null) { startActivityForResult(captureImageIntent, REQUEST_IMAGE_CAPTURE); } else { Log.e(TAG, "Capture image intent could not be resolved in managed profile."); showToast(R.string.provisioning_byod_capture_media_error); finish(); } return; } else if (action.equals(ACTION_CAPTURE_AND_CHECK_VIDEO_WITH_EXTRA_OUTPUT) || action.equals(ACTION_CAPTURE_AND_CHECK_VIDEO_WITHOUT_EXTRA_OUTPUT)) { // We need the camera permission to send the video capture intent. grantCameraPermissionToSelf(); Intent captureVideoIntent = getCaptureVideoIntent(); int videoCaptureRequestId; if (action.equals(ACTION_CAPTURE_AND_CHECK_VIDEO_WITH_EXTRA_OUTPUT)) { mVideoUri = getTempUri("video.mp4").second; captureVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mVideoUri); videoCaptureRequestId = REQUEST_VIDEO_CAPTURE_WITH_EXTRA_OUTPUT; } else { videoCaptureRequestId = REQUEST_VIDEO_CAPTURE_WITHOUT_EXTRA_OUTPUT; } if (captureVideoIntent.resolveActivity(getPackageManager()) != null) { startActivityForResult(captureVideoIntent, videoCaptureRequestId); } else { Log.e(TAG, "Capture video intent could not be resolved in managed profile."); showToast(R.string.provisioning_byod_capture_media_error); finish(); } return; } else if (action.equals(ACTION_CAPTURE_AND_CHECK_AUDIO)) { Intent captureAudioIntent = getCaptureAudioIntent(); if (captureAudioIntent.resolveActivity(getPackageManager()) != null) { startActivityForResult(captureAudioIntent, REQUEST_AUDIO_CAPTURE); } else { Log.e(TAG, "Capture audio intent could not be resolved in managed profile."); showToast(R.string.provisioning_byod_capture_media_error); finish(); } return; } else if (ACTION_KEYGUARD_DISABLED_FEATURES.equals(action)) { final int value = intent.getIntExtra(EXTRA_PARAMETER_1, DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE); mDevicePolicyManager.setKeyguardDisabledFeatures(mAdminReceiverComponent, value); } else if (ACTION_LOCKNOW.equals(action)) { mDevicePolicyManager.lockNow(); setResult(RESULT_OK); } else if (action.equals(ACTION_TEST_NFC_BEAM)) { Intent testNfcBeamIntent = new Intent(this, NfcTestActivity.class); testNfcBeamIntent.putExtras(intent); startActivity(testNfcBeamIntent); finish(); return; } else if (action.equals(ACTION_TEST_CROSS_PROFILE_INTENTS_DIALOG)) { sendIntentInsideChooser(new Intent(CrossProfileTestActivity.ACTION_CROSS_PROFILE_TO_PERSONAL)); } else if (action.equals(ACTION_TEST_APP_LINKING_DIALOG)) { mDevicePolicyManager.addUserRestriction(DeviceAdminTestReceiver.getReceiverComponentName(), UserManager.ALLOW_PARENT_PROFILE_APP_LINKING); Intent toSend = new Intent(Intent.ACTION_VIEW); toSend.setData(Uri.parse("http://com.android.cts.verifier")); sendIntentInsideChooser(toSend); } else if (action.equals(ACTION_SET_USER_RESTRICTION)) { final String restriction = intent.getStringExtra(EXTRA_PARAMETER_1); if (restriction != null) { mDevicePolicyManager.addUserRestriction(DeviceAdminTestReceiver.getReceiverComponentName(), restriction); } } else if (action.equals(ACTION_CLEAR_USER_RESTRICTION)) { final String restriction = intent.getStringExtra(EXTRA_PARAMETER_1); if (restriction != null) { mDevicePolicyManager.clearUserRestriction(DeviceAdminTestReceiver.getReceiverComponentName(), restriction); } } else if (action.equals(ACTION_BYOD_SET_LOCATION_AND_CHECK_UPDATES)) { handleLocationAction(); return; } else if (action.equals(ACTION_NOTIFICATION)) { showNotification(Notification.VISIBILITY_PUBLIC); } else if (ACTION_NOTIFICATION_ON_LOCKSCREEN.equals(action)) { mDevicePolicyManager.lockNow(); showNotification(Notification.VISIBILITY_PRIVATE); } else if (ACTION_CLEAR_NOTIFICATION.equals(action)) { mNotificationManager.cancel(NOTIFICATION_ID); } else if (ACTION_TEST_SELECT_WORK_CHALLENGE.equals(action)) { mDevicePolicyManager.setOrganizationColor(mAdminReceiverComponent, Color.BLUE); mDevicePolicyManager.setOrganizationName(mAdminReceiverComponent, getResources().getString(R.string.provisioning_byod_confirm_work_credentials_header)); startActivity(new Intent(DevicePolicyManager.ACTION_SET_NEW_PASSWORD)); } else if (ACTION_LAUNCH_CONFIRM_WORK_CREDENTIALS.equals(action)) { KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); Intent launchIntent = keyguardManager.createConfirmDeviceCredentialIntent(null, null); startActivity(launchIntent); } else if (ACTION_SET_ORGANIZATION_INFO.equals(action)) { if (intent.hasExtra(OrganizationInfoTestActivity.EXTRA_ORGANIZATION_NAME)) { final String organizationName = intent .getStringExtra(OrganizationInfoTestActivity.EXTRA_ORGANIZATION_NAME); mDevicePolicyManager.setOrganizationName(mAdminReceiverComponent, organizationName); } final int organizationColor = intent.getIntExtra(OrganizationInfoTestActivity.EXTRA_ORGANIZATION_COLOR, mDevicePolicyManager.getOrganizationColor(mAdminReceiverComponent)); mDevicePolicyManager.setOrganizationColor(mAdminReceiverComponent, organizationColor); } else if (ACTION_TEST_PARENT_PROFILE_PASSWORD.equals(action)) { startActivity(new Intent(DevicePolicyManager.ACTION_SET_NEW_PARENT_PROFILE_PASSWORD)); } // This activity has no UI and is only used to respond to CtsVerifier in the primary side. finish(); }
From source file:cc.mintcoin.wallet.service.BlockchainServiceImpl.java
@Override public int onStartCommand(final Intent intent, final int flags, final int startId) { log.info("service start command: " + intent + (intent.hasExtra(Intent.EXTRA_ALARM_COUNT) ? " (alarm count: " + intent.getIntExtra(Intent.EXTRA_ALARM_COUNT, 0) + ")" : "")); //log.info("org.bitcoin.NativeSecp256k1.enabled=" + org.bitcoin.NativeSecp256k1.enabled); if (blockChain == null) { boolean blockChainFileExists = blockChainFile.exists(); boolean tryStarting = true; if (DownloadCompleteReceiver.isDownloading(application)) { log.info("isDownloading"); DownloadCompleteReceiver.updateDownloadState(application); // it can fix itself this way tryStarting = false;// w w w . j ava 2 s . com } else if (!blockChainFileExists) { if (DownloadCompleteReceiver.isObbAvailable(application)) { initializeBlockchainFast(); tryStarting = true; } else if (intent.getBooleanExtra(DownloadCompleteReceiver.INTENT_EXTRA_SKIP_OBB_INIT, false)) { tryStarting = true; } else { // open dialog box to ask user what to do for download Intent intent2 = new Intent(this, InitialBlockchainActivity.class); intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivity(intent2); tryStarting = false; } } if (tryStarting) { try { startBlockChain(); } catch (Error e) { stopSelf(); throw e; } } else { stopSelf(); } } String action = intent.getAction(); if (BlockchainService.ACTION_CANCEL_COINS_RECEIVED.equals(action)) { notificationCount = 0; notificationAccumulatedAmount = BigInteger.ZERO; notificationAddresses.clear(); nm.cancel(NOTIFICATION_ID_COINS_RECEIVED); } else if (BlockchainService.ACTION_RESET_BLOCKCHAIN.equals(action)) { log.info("will remove blockchain on service shutdown"); resetBlockchainOnShutdown = true; stopSelf(); } else if (BlockchainService.ACTION_BROADCAST_TRANSACTION.equals(action)) { final Sha256Hash hash = new Sha256Hash( intent.getByteArrayExtra(BlockchainService.ACTION_BROADCAST_TRANSACTION_HASH)); final Transaction tx = application.getWallet().getTransaction(hash); if (peerGroup != null) { log.info("broadcasting transaction " + tx.getHashAsString()); peerGroup.broadcastTransaction(tx); } else { log.info("peergroup not available, not broadcasting transaction " + tx.getHashAsString()); } } return START_NOT_STICKY; }
From source file:com.ubuntuone.android.files.service.MetaService.java
@Override protected void onHandleIntent(Intent intent) { sSyncRunning = true;// ww w. j a va 2 s . c o m Thread.currentThread().setPriority(Thread.MIN_PRIORITY); final String action = intent.getAction(); final String resourcePath = intent.getStringExtra(EXTRA_RESOURCE_PATH); final ResultReceiver receiver = intent.getParcelableExtra(EXTRA_CALLBACK); if (ACTION_GET_USER.equals(action)) { getUser(receiver); getVolumes(receiver); } else if (ACTION_GET_VOLUME.equals(action)) { getVolume(resourcePath, receiver); } else if (ACTION_CREATE_VOLUME.equals(action)) { createVolume(resourcePath, receiver); } else if (ACTION_MAKE_DIRECTORY.equals(action)) { makeDirectory(resourcePath, receiver); } else if (ACTION_GET_NODE.equals(action)) { getNode(resourcePath, receiver, true); } else if (ACTION_UPDATE_NODE.equals(action)) { if (intent.hasExtra(Nodes.NODE_NAME)) { String newPath = intent.getStringExtra(EXTRA_PATH); updateNode(resourcePath, newPath, receiver); } if (intent.hasExtra(Nodes.NODE_IS_PUBLIC)) { Boolean isPublic = intent.getBooleanExtra(Nodes.NODE_IS_PUBLIC, false); updateNode(resourcePath, isPublic, receiver); } } else if (ACTION_DELETE_NODE.equals(action)) { deleteNode(resourcePath, receiver); } sSyncRunning = false; }
From source file:com.ringdroid.RingdroidEditActivity.java
/** Called with the activity is first created. */ @Override// ww w . j a va2s . com public void onCreate(Bundle icicle) { super.onCreate(icicle); mRecordingFilename = null; mRecordingUri = null; mPlayer = null; mIsPlaying = false; Intent intent = getIntent(); mFilename = intent.getData().toString(); // If the Ringdroid media select activity was launched via a // GET_CONTENT intent, then we shouldn't display a "saved" // message when the user saves, we should just return whatever // they create. mWasGetContentIntent = intent.getBooleanExtra("was_get_content_intent", false); mSoundFile = null; mKeyDown = false; if (mFilename.equals("record")) { try { Intent recordIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION); startActivityForResult(recordIntent, REQUEST_CODE_RECORD); } catch (Exception e) { showFinalAlert(e, R.string.record_error); } } loadGui(); mHandler = new Handler(); mHandler.postDelayed(mTimerRunnable, 100); if (!mFilename.equals("record")) { loadFromFile(); } }
From source file:com.Beat.RingdroidEditActivity.java
/** Called when the activity is first created. */ @Override/* w ww.j ava2 s. com*/ public void onCreate(Bundle icicle) { super.onCreate(icicle); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); mRecordingFilename = null; mRecordingUri = null; mPlayer = null; mIsPlaying = false; Intent intent = getIntent(); if (intent.getBooleanExtra("privacy", false)) { showServerPrompt(true); return; } // If the Ringdroid media select activity was launched via a // GET_CONTENT intent, then we shouldn't display a "saved" // message when the user saves, we should just return whatever // they create. mWasGetContentIntent = intent.getBooleanExtra("was_get_content_intent", false); mFilename = intent.getData().toString(); mSoundFile = null; mKeyDown = false; if (mFilename.equals("record")) { try { Intent recordIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION); startActivityForResult(recordIntent, REQUEST_CODE_RECORD); } catch (Exception e) { showFinalAlert(e, R.string.record_error); } } mHandler = new Handler(); loadGui(); mHandler.postDelayed(mTimerRunnable, 100); if (!mFilename.equals("record")) { loadFromFile(); } }
From source file:com.android.contacts.ContactSaveService.java
private void splitContact(Intent intent) { final long rawContactIds[][] = (long[][]) intent.getSerializableExtra(EXTRA_RAW_CONTACT_IDS); final ResultReceiver receiver = intent.getParcelableExtra(EXTRA_RESULT_RECEIVER); final boolean hardSplit = intent.getBooleanExtra(EXTRA_HARD_SPLIT, false); if (rawContactIds == null) { Log.e(TAG, "Invalid argument for splitContact request"); if (receiver != null) { receiver.send(BAD_ARGUMENTS, new Bundle()); }/*from ww w .j a va 2 s . c o m*/ return; } final int batchSize = MAX_CONTACTS_PROVIDER_BATCH_SIZE; final ContentResolver resolver = getContentResolver(); final ArrayList<ContentProviderOperation> operations = new ArrayList<>(batchSize); for (int i = 0; i < rawContactIds.length; i++) { for (int j = 0; j < rawContactIds.length; j++) { if (i != j) { if (!buildSplitTwoContacts(operations, rawContactIds[i], rawContactIds[j], hardSplit)) { if (receiver != null) { receiver.send(CP2_ERROR, new Bundle()); return; } } } } } if (operations.size() > 0 && !applyOperations(resolver, operations)) { if (receiver != null) { receiver.send(CP2_ERROR, new Bundle()); } return; } LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(BROADCAST_UNLINK_COMPLETE)); if (receiver != null) { receiver.send(CONTACTS_SPLIT, new Bundle()); } else { showToast(R.string.contactUnlinkedToast); } }
From source file:at.alladin.rmbt.android.main.RMBTMainActivity.java
/** * *//*from ww w . j a v a2 s. co m*/ @Override public void onCreate(final Bundle savedInstanceState) { //Log.i("MAIN ACTIVITY", "onCreate"); restoreInstance(savedInstanceState); super.onCreate(savedInstanceState); NetworkInfoCollector.init(this); networkInfoCollector = NetworkInfoCollector.getInstance(); preferencesUpdate(); setContentView(R.layout.main_with_navigation_drawer); if (VIEW_HIERARCHY_SERVER_ENABLED) { ViewServer.get(this).addWindow(this); } ActionBar actionBar = getActionBar(); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE); actionBar.setDisplayUseLogoEnabled(true); // initialize the navigation drawer with the main menu list adapter: String[] mainTitles = getResources().getStringArray(R.array.navigation_main_titles); int[] navIcons = new int[] { R.drawable.ic_action_home, R.drawable.ic_action_history, R.drawable.ic_action_map, R.drawable.ic_action_stat, R.drawable.ic_action_help, R.drawable.ic_action_about, R.drawable.ic_action_settings, R.drawable.ic_action_about }; MainMenuListAdapter mainMenuAdapter = new MainMenuListAdapter(this, mainTitles, navIcons); drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); drawerList = (ListView) findViewById(R.id.left_drawer); drawerLayout.setBackgroundResource(R.drawable.ic_drawer); drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.page_title_title_page, R.string.page_title_title_page) { /** Called when a drawer has settled in a completely closed state. */ public void onDrawerClosed(View view) { super.onDrawerClosed(view); //refreshActionBar(null); exitAfterDrawerClose = false; } /** Called when a drawer has settled in a completely open state. */ public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); } }; drawerLayout.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (KeyEvent.KEYCODE_BACK == event.getKeyCode() && exitAfterDrawerClose) { onBackPressed(); return true; } return false; } }); drawerLayout.setDrawerListener(drawerToggle); drawerList.setAdapter(mainMenuAdapter); drawerList.setOnItemClickListener(new OnItemClickListener() { final int[] menuIds = new int[] { R.id.action_title_page, R.id.action_history, R.id.action_map, R.id.action_stats, R.id.action_help, R.id.action_info, R.id.action_settings, R.id.action_netstat, R.id.action_log }; @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectMenuItem(menuIds[position]); drawerLayout.closeDrawers(); } }); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); // Do something against banding effect in gradients // Dither flag might mess up on certain devices?? final Window window = getWindow(); window.setFormat(PixelFormat.RGBA_8888); window.addFlags(WindowManager.LayoutParams.FLAG_DITHER); // Setzt Default-Werte, wenn noch keine Werte vorhanden PreferenceManager.setDefaultValues(this, R.xml.preferences, false); final String uuid = ConfigHelper.getUUID(getApplicationContext()); fm = getFragmentManager(); final Fragment fragment = fm.findFragmentById(R.id.fragment_content); if (!ConfigHelper.isTCAccepted(this)) { if (fragment != null && fm.getBackStackEntryCount() >= 1) // clear fragment back stack fm.popBackStack(fm.getBackStackEntryAt(0).getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE); getActionBar().hide(); setLockNavigationDrawer(true); showTermsCheck(); } else { currentMapOptions.put("highlight", uuid); if (fragment == null) { if (false) // deactivated for si // ! ConfigHelper.isNDTDecisionMade(this)) { showTermsCheck(); showNdtCheck(); } else initApp(true); } } geoLocation = new MainGeoLocation(getApplicationContext()); mNetworkStateChangedFilter = new IntentFilter(); mNetworkStateChangedFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); mNetworkStateIntentReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) { if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) { final boolean connected = !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); final boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false); if (connected) { if (networkInfoCollector != null) { networkInfoCollector.setHasConnectionFromAndroidApi(true); } } else { if (networkInfoCollector != null) { networkInfoCollector.setHasConnectionFromAndroidApi(false); } } Log.i(DEBUG_TAG, "CONNECTED: " + connected + " FAILOVER: " + isFailover); } } }; }
From source file:com.android.contacts.ContactSaveService.java
private void saveContact(Intent intent) { RawContactDeltaList state = intent.getParcelableExtra(EXTRA_CONTACT_STATE); boolean isProfile = intent.getBooleanExtra(EXTRA_SAVE_IS_PROFILE, false); Bundle updatedPhotos = intent.getParcelableExtra(EXTRA_UPDATED_PHOTOS); if (state == null) { Log.e(TAG, "Invalid arguments for saveContact request"); return;//from w w w .j a v a 2 s . co m } int saveMode = intent.getIntExtra(EXTRA_SAVE_MODE, -1); // Trim any empty fields, and RawContacts, before persisting final AccountTypeManager accountTypes = AccountTypeManager.getInstance(this); RawContactModifier.trimEmpty(state, accountTypes); Uri lookupUri = null; final ContentResolver resolver = getContentResolver(); boolean succeeded = false; // Keep track of the id of a newly raw-contact (if any... there can be at most one). long insertedRawContactId = -1; // Attempt to persist changes int tries = 0; while (tries++ < PERSIST_TRIES) { try { // Build operations and try applying final ArrayList<CPOWrapper> diffWrapper = state.buildDiffWrapper(); final ArrayList<ContentProviderOperation> diff = Lists.newArrayList(); for (CPOWrapper cpoWrapper : diffWrapper) { diff.add(cpoWrapper.getOperation()); } if (DEBUG) { Log.v(TAG, "Content Provider Operations:"); for (ContentProviderOperation operation : diff) { Log.v(TAG, operation.toString()); } } int numberProcessed = 0; boolean batchFailed = false; final ContentProviderResult[] results = new ContentProviderResult[diff.size()]; while (numberProcessed < diff.size()) { final int subsetCount = applyDiffSubset(diff, numberProcessed, results, resolver); if (subsetCount == -1) { Log.w(TAG, "Resolver.applyBatch failed in saveContacts"); batchFailed = true; break; } else { numberProcessed += subsetCount; } } if (batchFailed) { // Retry save continue; } final long rawContactId = getRawContactId(state, diffWrapper, results); if (rawContactId == -1) { throw new IllegalStateException("Could not determine RawContact ID after save"); } // We don't have to check to see if the value is still -1. If we reach here, // the previous loop iteration didn't succeed, so any ID that we obtained is bogus. insertedRawContactId = getInsertedRawContactId(diffWrapper, results); if (isProfile) { // Since the profile supports local raw contacts, which may have been completely // removed if all information was removed, we need to do a special query to // get the lookup URI for the profile contact (if it still exists). Cursor c = resolver.query(Profile.CONTENT_URI, new String[] { Contacts._ID, Contacts.LOOKUP_KEY }, null, null, null); if (c == null) { continue; } try { if (c.moveToFirst()) { final long contactId = c.getLong(0); final String lookupKey = c.getString(1); lookupUri = Contacts.getLookupUri(contactId, lookupKey); } } finally { c.close(); } } else { final Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); lookupUri = RawContacts.getContactLookupUri(resolver, rawContactUri); } if (lookupUri != null && Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Saved contact. New URI: " + lookupUri); } // We can change this back to false later, if we fail to save the contact photo. succeeded = true; break; } catch (RemoteException e) { // Something went wrong, bail without success FeedbackHelper.sendFeedback(this, TAG, "Problem persisting user edits", e); break; } catch (IllegalArgumentException e) { // This is thrown by applyBatch on malformed requests FeedbackHelper.sendFeedback(this, TAG, "Problem persisting user edits", e); showToast(R.string.contactSavedErrorToast); break; } catch (OperationApplicationException e) { // Version consistency failed, re-parent change and try again Log.w(TAG, "Version consistency failed, re-parenting: " + e.toString()); final StringBuilder sb = new StringBuilder(RawContacts._ID + " IN("); boolean first = true; final int count = state.size(); for (int i = 0; i < count; i++) { Long rawContactId = state.getRawContactId(i); if (rawContactId != null && rawContactId != -1) { if (!first) { sb.append(','); } sb.append(rawContactId); first = false; } } sb.append(")"); if (first) { throw new IllegalStateException("Version consistency failed for a new contact", e); } final RawContactDeltaList newState = RawContactDeltaList.fromQuery( isProfile ? RawContactsEntity.PROFILE_CONTENT_URI : RawContactsEntity.CONTENT_URI, resolver, sb.toString(), null, null); state = RawContactDeltaList.mergeAfter(newState, state); // Update the new state to use profile URIs if appropriate. if (isProfile) { for (RawContactDelta delta : state) { delta.setProfileQueryUri(); } } } } // Now save any updated photos. We do this at the end to ensure that // the ContactProvider already knows about newly-created contacts. if (updatedPhotos != null) { for (String key : updatedPhotos.keySet()) { Uri photoUri = updatedPhotos.getParcelable(key); long rawContactId = Long.parseLong(key); // If the raw-contact ID is negative, we are saving a new raw-contact; // replace the bogus ID with the new one that we actually saved the contact at. if (rawContactId < 0) { rawContactId = insertedRawContactId; } // If the save failed, insertedRawContactId will be -1 if (rawContactId < 0 || !saveUpdatedPhoto(rawContactId, photoUri, saveMode)) { succeeded = false; } } } Intent callbackIntent = intent.getParcelableExtra(EXTRA_CALLBACK_INTENT); if (callbackIntent != null) { if (succeeded) { // Mark the intent to indicate that the save was successful (even if the lookup URI // is now null). For local contacts or the local profile, it's possible that the // save triggered removal of the contact, so no lookup URI would exist.. callbackIntent.putExtra(EXTRA_SAVE_SUCCEEDED, true); } callbackIntent.setData(lookupUri); deliverCallback(callbackIntent); } }