List of usage examples for android.os Bundle getBoolean
public boolean getBoolean(String key, boolean defaultValue)
From source file:br.com.brolam.cloudvision.ui.NoteVisionActivity.java
private void setSaveInstanceState(Bundle savedInstanceState) { // read parameters from the savedInstanceState ou intent used to launch the activity. Bundle bundle = savedInstanceState != null ? savedInstanceState : getIntent().getExtras(); if (bundle != null) { this.useFlash = bundle.getBoolean(USE_FLASH, false); this.onKeyboard = bundle.getBoolean(ON_KEYBOARD, false); this.noteVisionKey = bundle.getString(NOTE_VISION_KEY, null); this.noteVisionItemKey = bundle.getString(NOTE_VISION_ITEM_KEY, null); this.editTextTitle.setText(bundle.getString(NoteVision.TITLE, this.editTextTitle.getText().toString())); this.editTextContent .setText(bundle.getString(NoteVisionItem.CONTENT, this.editTextContent.getText().toString())); } else {/* ww w. j ava2 s.com*/ this.useFlash = false; this.onKeyboard = false; this.noteVisionKey = null; this.noteVisionItemKey = null; } }
From source file:at.florian_lentsch.expirysync.AddProductActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.product_form); loadPhotoFromSaveInstanceState(savedInstanceState); initFormFields();/*from www.ja v a 2 s. com*/ // Default values etc: EditText amountField = (EditText) findViewById(R.id.amount_field); String hint = amountField.getHint().toString(); hint += " (" + getResources().getText(R.string.default_value) + ": " + DEFAULT_AMOUNT + ")"; amountField.setHint(hint); // Show the Up button in the action bar. setupActionBar(); boolean scanBarcodeOnStart = savedInstanceState != null ? savedInstanceState.getBoolean("scanBarcodeOnStart", true) : true; if (scanBarcodeOnStart) { Intent intent = new Intent(this, ScanBarcodeActivity.class); startActivityForResult(intent, SCAN_BARCODE_RESULT); } }
From source file:com.example.jumpnote.android.SyncAdapter.java
@Override public void onPerformSync(final Account account, Bundle extras, String authority, final ContentProviderClient provider, final SyncResult syncResult) { TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); String clientDeviceId = tm.getDeviceId(); final long newSyncTime = System.currentTimeMillis(); final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false); final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false); final boolean initialize = extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false); C2DMReceiver.refreshAppC2DMRegistrationState(mContext); Log.i(TAG, "Beginning " + (uploadOnly ? "upload-only" : "full") + " sync for account " + account.name); // Read this account's sync metadata final SharedPreferences syncMeta = mContext.getSharedPreferences("sync:" + account.name, 0); long lastSyncTime = syncMeta.getLong(LAST_SYNC, 0); long lastServerSyncTime = syncMeta.getLong(SERVER_LAST_SYNC, 0); // Check for changes in either app-wide auto sync registration information, or changes in // the user's preferences for auto sync on this account; if either changes, piggy back the // new registration information in this sync. long lastRegistrationChangeTime = C2DMessaging.getLastRegistrationChange(mContext); boolean autoSyncDesired = ContentResolver.getMasterSyncAutomatically() && ContentResolver.getSyncAutomatically(account, JumpNoteContract.AUTHORITY); boolean autoSyncEnabled = syncMeta.getBoolean(DM_REGISTERED, false); // Will be 0 for no change, -1 for unregister, 1 for register. final int deviceRegChange; JsonRpcClient.Call deviceRegCall = null; if (autoSyncDesired != autoSyncEnabled || lastRegistrationChangeTime > lastSyncTime || initialize || manualSync) {//from w ww . j a v a 2 s .c om String registrationId = C2DMessaging.getRegistrationId(mContext); deviceRegChange = (autoSyncDesired && registrationId != null) ? 1 : -1; if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Auto sync selection or registration information has changed, " + (deviceRegChange == 1 ? "registering" : "unregistering") + " messaging for this device, for account " + account.name); } try { if (deviceRegChange == 1) { // Register device for auto sync on this account. deviceRegCall = new JsonRpcClient.Call(JumpNoteProtocol.DevicesRegister.METHOD); JSONObject params = new JSONObject(); DeviceRegistration device = new DeviceRegistration(clientDeviceId, DEVICE_TYPE, registrationId); params.put(JumpNoteProtocol.DevicesRegister.ARG_DEVICE, device.toJSON()); deviceRegCall.setParams(params); } else { // Unregister device for auto sync on this account. deviceRegCall = new JsonRpcClient.Call(JumpNoteProtocol.DevicesUnregister.METHOD); JSONObject params = new JSONObject(); params.put(JumpNoteProtocol.DevicesUnregister.ARG_DEVICE_ID, clientDeviceId); deviceRegCall.setParams(params); } } catch (JSONException e) { logErrorMessage("Error generating device registration remote RPC parameters.", manualSync); e.printStackTrace(); return; } } else { deviceRegChange = 0; } // Get the list of locally changed notes. If this is an upload-only sync and there were // no local changes, cancel the sync. List<ModelJava.Note> locallyChangedNotes = null; try { locallyChangedNotes = getLocallyChangedNotes(provider, account, new Date(lastSyncTime)); } catch (RemoteException e) { logErrorMessage("Remote exception accessing content provider: " + e.getMessage(), manualSync); e.printStackTrace(); syncResult.stats.numIoExceptions++; return; } if (uploadOnly && locallyChangedNotes.isEmpty() && deviceRegCall == null) { Log.i(TAG, "No local changes; upload-only sync canceled."); return; } // Set up the RPC sync calls final AuthenticatedJsonRpcJavaClient jsonRpcClient = new AuthenticatedJsonRpcJavaClient(mContext, Config.SERVER_AUTH_URL_TEMPLATE, Config.SERVER_RPC_URL); try { jsonRpcClient.blockingAuthenticateAccount(account, manualSync ? AuthenticatedJsonRpcJavaClient.NEED_AUTH_INTENT : AuthenticatedJsonRpcJavaClient.NEED_AUTH_NOTIFICATION, false); } catch (AuthenticationException e) { logErrorMessage("Authentication exception when attempting to sync.", manualSync); e.printStackTrace(); syncResult.stats.numAuthExceptions++; return; } catch (OperationCanceledException e) { Log.i(TAG, "Sync for account " + account.name + " manually canceled."); return; } catch (RequestedUserAuthenticationException e) { syncResult.stats.numAuthExceptions++; return; } catch (InvalidAuthTokenException e) { logErrorMessage("Invalid auth token provided by AccountManager when attempting to " + "sync.", manualSync); e.printStackTrace(); syncResult.stats.numAuthExceptions++; return; } // Set up the notes sync call. JsonRpcClient.Call notesSyncCall = new JsonRpcClient.Call(JumpNoteProtocol.NotesSync.METHOD); try { JSONObject params = new JSONObject(); params.put(JumpNoteProtocol.ARG_CLIENT_DEVICE_ID, clientDeviceId); params.put(JumpNoteProtocol.NotesSync.ARG_SINCE_DATE, Util.formatDateISO8601(new Date(lastServerSyncTime))); JSONArray locallyChangedNotesJson = new JSONArray(); for (ModelJava.Note locallyChangedNote : locallyChangedNotes) { locallyChangedNotesJson.put(locallyChangedNote.toJSON()); } params.put(JumpNoteProtocol.NotesSync.ARG_LOCAL_NOTES, locallyChangedNotesJson); notesSyncCall.setParams(params); } catch (JSONException e) { logErrorMessage("Error generating sync remote RPC parameters.", manualSync); e.printStackTrace(); syncResult.stats.numParseExceptions++; return; } List<JsonRpcClient.Call> jsonRpcCalls = new ArrayList<JsonRpcClient.Call>(); jsonRpcCalls.add(notesSyncCall); if (deviceRegChange != 0) jsonRpcCalls.add(deviceRegCall); jsonRpcClient.callBatch(jsonRpcCalls, new JsonRpcClient.BatchCallback() { public void onData(Object[] data) { if (data[0] != null) { // Read notes sync data. JSONObject dataJson = (JSONObject) data[0]; try { List<ModelJava.Note> changedNotes = new ArrayList<ModelJava.Note>(); JSONArray notesJson = dataJson.getJSONArray(JumpNoteProtocol.NotesSync.RET_NOTES); for (int i = 0; i < notesJson.length(); i++) { changedNotes.add(new ModelJava.Note(notesJson.getJSONObject(i))); } reconcileSyncedNotes(provider, account, changedNotes, syncResult.stats); // If sync is successful (no exceptions thrown), update sync metadata long newServerSyncTime = Util .parseDateISO8601(dataJson.getString(JumpNoteProtocol.NotesSync.RET_NEW_SINCE_DATE)) .getTime(); syncMeta.edit().putLong(LAST_SYNC, newSyncTime).commit(); syncMeta.edit().putLong(SERVER_LAST_SYNC, newServerSyncTime).commit(); Log.i(TAG, "Sync complete, setting last sync time to " + Long.toString(newSyncTime)); } catch (JSONException e) { logErrorMessage("Error parsing note sync RPC response", manualSync); e.printStackTrace(); syncResult.stats.numParseExceptions++; return; } catch (ParseException e) { logErrorMessage("Error parsing note sync RPC response", manualSync); e.printStackTrace(); syncResult.stats.numParseExceptions++; return; } catch (RemoteException e) { logErrorMessage("RemoteException in reconcileSyncedNotes: " + e.getMessage(), manualSync); e.printStackTrace(); return; } catch (OperationApplicationException e) { logErrorMessage("Could not apply batch operations to content provider: " + e.getMessage(), manualSync); e.printStackTrace(); return; } finally { provider.release(); } } // Read device reg data. if (deviceRegChange != 0) { // data[1] will be null in case of an error (successful unregisters // will have an empty JSONObject, not null). boolean registered = (data[1] != null && deviceRegChange == 1); syncMeta.edit().putBoolean(DM_REGISTERED, registered).commit(); if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Stored account auto sync registration state: " + Boolean.toString(registered)); } } } public void onError(int callIndex, JsonRpcException e) { if (e.getHttpCode() == 403) { Log.w(TAG, "Got a 403 response, invalidating App Engine ACSID token"); jsonRpcClient.invalidateAccountAcsidToken(account); } provider.release(); logErrorMessage("Error calling remote note sync RPC", manualSync); e.printStackTrace(); } }); }
From source file:edu.cnu.PowerTutor.ui.PowerViewer.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); prefs = PreferenceManager.getDefaultSharedPreferences(this); uid = getIntent().getIntExtra("uid", SystemInfo.AID_ALL); collecting = true;/*from ww w . ja va 2s .c o m*/ if (savedInstanceState != null) { collecting = savedInstanceState.getBoolean("collecting", true); componentNames = savedInstanceState.getStringArray("componentNames"); noUidMask = savedInstanceState.getInt("noUidMask"); } serviceIntent = new Intent(this, UMLoggerService.class); conn = new CounterServiceConnection(); }
From source file:fr.simon.marquis.preferencesmanager.ui.PreferencesActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { setTheme(App.theme.theme);//from ww w .j a va 2 s. co m super.onCreate(savedInstanceState); setContentView(R.layout.activity_preferences); getSupportActionBar().setDisplayHomeAsUpEnabled(true); Bundle b = getIntent().getExtras(); if (b == null) { finish(); return; } int index = PreferenceManager.getDefaultSharedPreferences(this).getInt(KEY_SORT_TYPE, 0); preferenceSortType = PreferenceSortType.values()[index]; mViewPager = (ViewPager) findViewById(R.id.pager); mLoadingView = findViewById(R.id.loadingView); mEmptyView = findViewById(R.id.emptyView); iconUri = b.getParcelable(KEY_ICON_URI); packageName = b.getString(EXTRA_PACKAGE_NAME); title = b.getString(EXTRA_TITLE); launchedFromShortcut = b.getBoolean(EXTRA_SHORTCUT, false); getSupportActionBar().setTitle(Ui.applyCustomTypeFace(title, this)); getSupportActionBar().setSubtitle(Ui.applyCustomTypeFace(packageName, this)); Picasso.with(this).load(iconUri).error(R.drawable.ic_launcher) .into((android.widget.ImageView) findViewById(android.R.id.home)); if (savedInstanceState == null) { findFilesAndBackupsTask = new FindFilesAndBackupsTask(packageName); findFilesAndBackupsTask.execute(); } else { try { ArrayList<String> tmp = new ArrayList<String>(); JSONArray array = new JSONArray(savedInstanceState.getString(KEY_FILES)); for (int i = 0; i < array.length(); i++) { tmp.add(array.getString(i)); } updateFindFiles(tmp); updateFindBackups(Utils.getBackups(getApplicationContext(), packageName)); } catch (Exception e) { findFilesAndBackupsTask = new FindFilesAndBackupsTask(packageName); findFilesAndBackupsTask.execute(); } } }
From source file:com.android.mms.ui.ConversationList.java
@Override protected void onStart() { super.onStart(); if (notDeleting) { MessagingNotification.cancelNotification(getApplicationContext(), SmsRejectedReceiver.SMS_REJECTED_NOTIFICATION_ID); DraftCache.getInstance().addOnDraftChangedListener(this); Intent it = getIntent();/*from w w w . j a v a 2 s. c o m*/ Bundle bundle = it.getExtras(); if (bundle != null) { fromFolder = bundle.getBoolean("fromFolder", false); } if (fromFolder) { mNeedToMarkAsSeen = false; } else { mNeedToMarkAsSeen = true; } int dropNum = Conversation.cleanExpiredWapPush(this); if (0 < dropNum) { Toast.makeText(this, getResources().getString(R.string.dl_expired_wap_push, dropNum), Toast.LENGTH_LONG).show(); } startAsyncQuery(); // We used to refresh the DraftCache here, but // refreshing the DraftCache each time we go to the ConversationList seems overly // aggressive. We already update the DraftCache when leaving CMA in onStop() and // onNewIntent(), and when we delete threads or delete all in CMA or this activity. // I hope we don't have to do such a heavy operation each time we enter here. // we invalidate the contact cache here because we want to get updated presence // and any contact changes. We don't invalidate the cache by observing presence and contact // changes (since that's too untargeted), so as a tradeoff we do it here. // If we're in the middle of the app initialization where we're loading the conversation // threads, don't invalidate the cache because we're in the process of building it. // TODO: think of a better way to invalidate cache more surgically or based on actual // TODO: changes we care about if (!Conversation.loadingThreads()) { Contact.invalidateCache(); } // Listen for broadcast intents that indicate the SMS is ready IntentFilter filter = new IntentFilter(TelephonyIntents.ACTION_IS_SIM_SMS_READY); //===== fixed CR<NEWMS00127040> by luning at 11-10-07 begin ===== filter.addAction(TelephonyIntents.ACTION_IS_SIM_SMS_READY1); registerReceiver(mReceiver, filter); } }
From source file:br.com.bioscada.apps.biotracks.TrackDetailActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); hasCamera = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA); photoUri = savedInstanceState != null ? (Uri) savedInstanceState.getParcelable(PHOTO_URI_KEY) : null; hasPhoto = savedInstanceState != null ? savedInstanceState.getBoolean(HAS_PHOTO_KEY, false) : false; myTracksProviderUtils = MyTracksProviderUtils.Factory.get(this); handleIntent(getIntent());/* w ww . j av a2s .co m*/ sharedPreferences = getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); trackRecordingServiceConnection = new TrackRecordingServiceConnection(this, bindChangedCallback); trackDataHub = TrackDataHub.newInstance(this); tabHost = (TabHost) findViewById(android.R.id.tabhost); tabHost.setup(); viewPager = (ViewPager) findViewById(R.id.pager); tabsAdapter = new TabsAdapter(this, tabHost, viewPager); TabSpec mapTabSpec = tabHost.newTabSpec(MyTracksMapFragment.MAP_FRAGMENT_TAG).setIndicator( getString(R.string.track_detail_map_tab), getResources().getDrawable(R.drawable.ic_tab_map)); tabsAdapter.addTab(mapTabSpec, MyTracksMapFragment.class, null); if (PreferencesUtils.getBoolean(this, R.string.chart_show_pacer_key, PreferencesUtils.CHART_SHOW_PACER_DEFAULT)) { TabSpec chartAndPacerTabSpec = tabHost.newTabSpec(ChartAndPacerFragment.CHART_AND_PACER_FRAGMENT_TAG) .setIndicator(getString(R.string.track_detail_chart_and_pacer_tab), getResources().getDrawable(R.drawable.ic_tab_chart)); tabsAdapter.addTab(chartAndPacerTabSpec, ChartAndPacerFragment.class, null); } TabSpec chartTabSpec = tabHost.newTabSpec(ChartFragment.CHART_FRAGMENT_TAG).setIndicator( getString(R.string.track_detail_chart_tab), getResources().getDrawable(R.drawable.ic_tab_chart)); tabsAdapter.addTab(chartTabSpec, ChartFragment.class, null); TabSpec statsTabSpec = tabHost.newTabSpec(StatsFragment.STATS_FRAGMENT_TAG).setIndicator( getString(R.string.track_detail_stats_tab), getResources().getDrawable(R.drawable.ic_tab_stats)); tabsAdapter.addTab(statsTabSpec, StatsFragment.class, null); TabSpec pacerTabSpec = tabHost.newTabSpec(PacerFragment.PACER_FRAGMENT_TAG).setIndicator( getString(R.string.track_detail_pacer_tab), getResources().getDrawable(R.drawable.ic_tab_pacer)); tabsAdapter.addTab(pacerTabSpec, PacerFragment.class, null); if (savedInstanceState != null) { tabHost.setCurrentTabByTag(savedInstanceState.getString(CURRENT_TAB_TAG_KEY)); } // Set the background after all three tabs are added ApiAdapterFactory.getApiAdapter().setTabBackground(tabHost.getTabWidget()); trackController = new TrackController(this, trackRecordingServiceConnection, false, recordListener, stopListener); }
From source file:com.imalu.alyou.activity.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) { //T??home???appcrash //fragment?? finish();//from w ww .j a v a 2s. c o m startActivity(new Intent(this, LoginActivity.class)); return; } setContentView(R.layout.activity_main); initView(); getContactList(); //if (getIntent().getBooleanExtra("conflict", false) && !isConflictDialogShow) // showConflictDialog(); //inviteMessgeDao = new InviteMessgeDao(this); //userDao = new UserDao(this); // fragment??? // chatHistoryFragment = new ChatHistoryFragment(); // ?fragment chatHistoryFragment = new ChatAllHistoryFragment(); contactListFragment = new ContactlistFragment(); mainpageFragment = new MainPageFragment(); settingFragment = new SettingsFragment(); fragments = new Fragment[] { chatHistoryFragment, contactListFragment, mainpageFragment, settingFragment }; // fragment getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, chatHistoryFragment) .add(R.id.fragment_container, contactListFragment).hide(contactListFragment) .show(chatHistoryFragment).commit(); // ?BroadcastReceiver /*msgReceiver = new NewMessageBroadcastReceiver(); IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction()); intentFilter.setPriority(3); registerReceiver(msgReceiver, intentFilter);*/ // ack?BroadcastReceiver /*IntentFilter ackMessageIntentFilter = new IntentFilter(EMChatManager.getInstance().getAckMessageBroadcastAction()); ackMessageIntentFilter.setPriority(3); registerReceiver(ackMessageReceiver, ackMessageIntentFilter);*/ //??BroadcastReceiver /*IntentFilter cmdMessageIntentFilter = new IntentFilter(EMChatManager.getInstance().getCmdMessageBroadcastAction()); cmdMessageIntentFilter.setPriority(3); registerReceiver(cmdMessageReceiver, cmdMessageIntentFilter);*/ // ?BroadcastReceiver // IntentFilter offlineMessageIntentFilter = new // IntentFilter(EMChatManager.getInstance() // .getOfflineMessageBroadcastAction()); // registerReceiver(offlineMessageReceiver, offlineMessageIntentFilter); // setContactListener??? //EMContactManager.getInstance().setContactListener(new MyContactListener()); // ??listener //EMChatManager.getInstance().addConnectionListener(new MyConnectionListener()); // ?listener //EMGroupManager.getInstance().addGroupChangeListener(new MyGroupChangeListener()); // sdkUI ??receiverlistener, ??broadcast //EMChat.getInstance().setAppInited(); }
From source file:cn.hbm.superwechat.activity.ContactlistFragment.java
@Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mContext = getActivity();/*from ww w. ja v a2s .co m*/ updateContactListener();//? //T??home???appcrash if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) return; inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); listView = (ListView) getView().findViewById(R.id.list); sidebar = (Sidebar) getView().findViewById(R.id.sidebar); sidebar.setListView(listView); //??? blackList = EMContactManager.getInstance().getBlackListUsernames(); contactList = new ArrayList<User>(); // ?contactlist getContactList(); //? query = (EditText) getView().findViewById(R.id.query); query.setHint(R.string.search); clearSearch = (ImageButton) getView().findViewById(R.id.search_clear); query.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before, int count) { adapter.getFilter().filter(s); if (s.length() > 0) { clearSearch.setVisibility(View.VISIBLE); } else { clearSearch.setVisibility(View.INVISIBLE); } } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void afterTextChanged(Editable s) { } }); clearSearch.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { query.getText().clear(); hideSoftKeyboard(); } }); // adapter adapter = new ContactAdapter(getActivity(), R.layout.row_contact, contactList); listView.setAdapter(adapter); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String username = adapter.getItem(position).getUsername(); if (Constant.NEW_FRIENDS_USERNAME.equals(username)) { // ? User user = ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList() .get(Constant.NEW_FRIENDS_USERNAME); user.setUnreadMsgCount(0); startActivity(new Intent(getActivity(), NewFriendsMsgActivity.class)); } else if (Constant.GROUP_USERNAME.equals(username)) { // ?? startActivity(new Intent(getActivity(), GroupsActivity.class)); } else if (Constant.CHAT_ROOM.equals(username)) { //?? startActivity(new Intent(getActivity(), PublicChatRoomsActivity.class)); } else if (Constant.CHAT_ROBOT.equals(username)) { //Robot? startActivity(new Intent(getActivity(), RobotsActivity.class)); } else { // demo?? startActivity(new Intent(getActivity(), ChatActivity.class).putExtra("userId", adapter.getItem(position).getUsername())); } } }); listView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // ?? if (getActivity().getWindow() .getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) { if (getActivity().getCurrentFocus() != null) inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } return false; } }); ImageView addContactView = (ImageView) getView().findViewById(R.id.iv_new_contact); // ? addContactView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getActivity(), AddContactActivity.class)); } }); registerForContextMenu(listView); progressBar = (View) getView().findViewById(R.id.progress_bar); contactSyncListener = new HXContactSyncListener(); HXSDKHelper.getInstance().addSyncContactListener(contactSyncListener); blackListSyncListener = new HXBlackListSyncListener(); HXSDKHelper.getInstance().addSyncBlackListListener(blackListSyncListener); contactInfoSyncListener = new HXContactInfoSyncListener(); ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getUserProfileManager() .addSyncContactInfoListener(contactInfoSyncListener); if (!HXSDKHelper.getInstance().isContactsSyncedWithServer()) { progressBar.setVisibility(View.VISIBLE); } else { progressBar.setVisibility(View.GONE); } }
From source file:com.samsung.android.remindme.SyncAdapter.java
@Override public void onPerformSync(final Account account, Bundle extras, String authority, final ContentProviderClient provider, final SyncResult syncResult) { Log.i(TAG, "onPerformSync called!"); TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); String clientDeviceId = tm.getDeviceId(); final long newSyncTime = System.currentTimeMillis(); final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false); final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false); final boolean initialize = extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false); C2DMReceiver.refreshAppC2DMRegistrationState(mContext); Log.i(TAG, "Beginning " + (uploadOnly ? "upload-only" : "full") + " sync for account " + account.name); // Read this account's sync metadata final SharedPreferences syncMeta = mContext.getSharedPreferences("sync:" + account.name, 0); long lastSyncTime = syncMeta.getLong(LAST_SYNC, 0); long lastServerSyncTime = syncMeta.getLong(SERVER_LAST_SYNC, 0); // Check for changes in either app-wide auto sync registration information, or changes in // the user's preferences for auto sync on this account; if either changes, piggy back the // new registration information in this sync. long lastRegistrationChangeTime = C2DMessaging.getLastRegistrationChange(mContext); boolean autoSyncDesired = ContentResolver.getMasterSyncAutomatically() && ContentResolver.getSyncAutomatically(account, RemindMeContract.AUTHORITY); boolean autoSyncEnabled = syncMeta.getBoolean(DM_REGISTERED, false); // Will be 0 for no change, -1 for unregister, 1 for register. final int deviceRegChange; JsonRpcClient.Call deviceRegCall = null; if (autoSyncDesired != autoSyncEnabled || lastRegistrationChangeTime > lastSyncTime || initialize || manualSync) {/*from w ww . ja v a 2 s .c om*/ String registrationId = C2DMessaging.getRegistrationId(mContext); deviceRegChange = (autoSyncDesired && registrationId != null) ? 1 : -1; if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Auto sync selection or registration information has changed, " + (deviceRegChange == 1 ? "registering" : "unregistering") + " messaging for this device, for account " + account.name); } try { if (deviceRegChange == 1) { // Register device for auto sync on this account. deviceRegCall = new JsonRpcClient.Call(RemindMeProtocol.DevicesRegister.METHOD); JSONObject params = new JSONObject(); DeviceRegistration device = new DeviceRegistration(clientDeviceId, DEVICE_TYPE, registrationId); params.put(RemindMeProtocol.DevicesRegister.ARG_DEVICE, device.toJSON()); deviceRegCall.setParams(params); } else { // Unregister device for auto sync on this account. deviceRegCall = new JsonRpcClient.Call(RemindMeProtocol.DevicesUnregister.METHOD); JSONObject params = new JSONObject(); params.put(RemindMeProtocol.DevicesUnregister.ARG_DEVICE_ID, clientDeviceId); deviceRegCall.setParams(params); } } catch (JSONException e) { logErrorMessage("Error generating device registration remote RPC parameters.", manualSync); e.printStackTrace(); return; } } else { deviceRegChange = 0; } // Get the list of locally changed alerts. If this is an upload-only sync and there were // no local changes, cancel the sync. List<ModelJava.Alert> locallyChangedAlerts = null; try { locallyChangedAlerts = getLocallyChangedAlerts(provider, account, new Date(lastSyncTime)); } catch (RemoteException e) { logErrorMessage("Remote exception accessing content provider: " + e.getMessage(), manualSync); e.printStackTrace(); syncResult.stats.numIoExceptions++; return; } if (uploadOnly && locallyChangedAlerts.isEmpty() && deviceRegCall == null) { Log.i(TAG, "No local changes; upload-only sync canceled."); return; } // Set up the RPC sync calls final AuthenticatedJsonRpcJavaClient jsonRpcClient = new AuthenticatedJsonRpcJavaClient(mContext, Config.SERVER_AUTH_URL_TEMPLATE, Config.SERVER_RPC_URL); try { jsonRpcClient.blockingAuthenticateAccount(account, manualSync ? AuthenticatedJsonRpcJavaClient.NEED_AUTH_INTENT : AuthenticatedJsonRpcJavaClient.NEED_AUTH_NOTIFICATION, false); } catch (AuthenticationException e) { logErrorMessage("Authentication exception when attempting to sync. root cause: " + e.getMessage(), manualSync); e.printStackTrace(); syncResult.stats.numAuthExceptions++; return; } catch (OperationCanceledException e) { Log.i(TAG, "Sync for account " + account.name + " manually canceled."); return; } catch (RequestedUserAuthenticationException e) { syncResult.stats.numAuthExceptions++; return; } catch (InvalidAuthTokenException e) { logErrorMessage("Invalid auth token provided by AccountManager when attempting to " + "sync.", manualSync); e.printStackTrace(); syncResult.stats.numAuthExceptions++; return; } // Set up the alerts sync call. JsonRpcClient.Call alertsSyncCall = new JsonRpcClient.Call(RemindMeProtocol.AlertsSync.METHOD); try { JSONObject params = new JSONObject(); params.put(RemindMeProtocol.ARG_CLIENT_DEVICE_ID, clientDeviceId); params.put(RemindMeProtocol.AlertsSync.ARG_SINCE_DATE, Util.formatDateISO8601(new Date(lastServerSyncTime))); JSONArray locallyChangedAlertsJson = new JSONArray(); for (ModelJava.Alert locallyChangedAlert : locallyChangedAlerts) { locallyChangedAlertsJson.put(locallyChangedAlert.toJSON()); } params.put(RemindMeProtocol.AlertsSync.ARG_LOCAL_NOTES, locallyChangedAlertsJson); alertsSyncCall.setParams(params); } catch (JSONException e) { logErrorMessage("Error generating sync remote RPC parameters.", manualSync); e.printStackTrace(); syncResult.stats.numParseExceptions++; return; } List<JsonRpcClient.Call> jsonRpcCalls = new ArrayList<JsonRpcClient.Call>(); jsonRpcCalls.add(alertsSyncCall); if (deviceRegChange != 0) jsonRpcCalls.add(deviceRegCall); jsonRpcClient.callBatch(jsonRpcCalls, new JsonRpcClient.BatchCallback() { public void onData(Object[] data) { if (data[0] != null) { // Read alerts sync data. JSONObject dataJson = (JSONObject) data[0]; try { List<ModelJava.Alert> changedAlerts = new ArrayList<ModelJava.Alert>(); JSONArray alertsJson = dataJson.getJSONArray(RemindMeProtocol.AlertsSync.RET_NOTES); for (int i = 0; i < alertsJson.length(); i++) { changedAlerts.add(new ModelJava.Alert(alertsJson.getJSONObject(i))); } reconcileSyncedAlerts(provider, account, changedAlerts, syncResult.stats); // If sync is successful (no exceptions thrown), update sync metadata long newServerSyncTime = Util .parseDateISO8601( dataJson.getString(RemindMeProtocol.AlertsSync.RET_NEW_SINCE_DATE)) .getTime(); syncMeta.edit().putLong(LAST_SYNC, newSyncTime).commit(); syncMeta.edit().putLong(SERVER_LAST_SYNC, newServerSyncTime).commit(); Log.i(TAG, "Sync complete, setting last sync time to " + Long.toString(newSyncTime)); } catch (JSONException e) { logErrorMessage("Error parsing alert sync RPC response", manualSync); e.printStackTrace(); syncResult.stats.numParseExceptions++; return; } catch (ParseException e) { logErrorMessage("Error parsing alert sync RPC response", manualSync); e.printStackTrace(); syncResult.stats.numParseExceptions++; return; } catch (RemoteException e) { logErrorMessage("RemoteException in reconcileSyncedAlerts: " + e.getMessage(), manualSync); e.printStackTrace(); return; } catch (OperationApplicationException e) { logErrorMessage("Could not apply batch operations to content provider: " + e.getMessage(), manualSync); e.printStackTrace(); return; } finally { provider.release(); } } // Read device reg data. if (deviceRegChange != 0) { // data[1] will be null in case of an error (successful unregisters // will have an empty JSONObject, not null). boolean registered = (data[1] != null && deviceRegChange == 1); syncMeta.edit().putBoolean(DM_REGISTERED, registered).commit(); if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Stored account auto sync registration state: " + Boolean.toString(registered)); } } } public void onError(int callIndex, JsonRpcException e) { if (e.getHttpCode() == 403) { Log.w(TAG, "Got a 403 response, invalidating App Engine ACSID token"); jsonRpcClient.invalidateAccountAcsidToken(account); } provider.release(); logErrorMessage("Error calling remote alert sync RPC", manualSync); e.printStackTrace(); } }); }