List of usage examples for android.os Bundle get
@Nullable
public Object get(String key)
From source file:com.antso.gcmtestapplication.GcmIntentService.java
@Override protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); // The getMessageType() intent parameter must be the intent you received // in your BroadcastReceiver. String messageType = gcm.getMessageType(intent); if (!extras.isEmpty()) { // has effect of unparcelling Bundle /*// ww w . j a va 2 s .c o m * Filter messages based on message type. Since it is likely that GCM will be * extended in the future with new message types, just ignore any message types you're * not interested in, or that you don't recognize. */ if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { sendNotification("Send error: " + extras.toString()); } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) { sendNotification("Deleted messages on server: " + extras.toString()); // If it's a regular GCM message, do some work. } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { // This loop represents the service doing some work. // for (int i = 0; i < 5; i++) { // Log.i(TAG, "Working... " + (i + 1) // + "/5 @ " + SystemClock.elapsedRealtime()); // try { // Thread.sleep(5000); // } catch (InterruptedException e) { // } // } // Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime()); // Post notification of received message. Log.i(TAG, "Received: " + extras.toString()); String data = (String) extras.get("data"); sendNotification("Received: " + data); } } // Release the wake lock provided by the WakefulBroadcastReceiver. GcmBroadcastReceiver.completeWakefulIntent(intent); }
From source file:com.wareninja.android.opensource.mongolab_sdk.common.WebService.java
public String webPost(String methodName, Bundle params) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os;// w w w .ja v a2s .c o m ret = null; String postUrl = webServiceUrl + methodName; if (AppContext.isDebugMode()) Log.d(TAG, "POST URL: " + postUrl); HttpURLConnection conn = (HttpURLConnection) new URL(postUrl).openConnection(); /*for (RequestHeader header : headers) { if (header != null) { conn.setRequestProperty(header.getKey(), header.getValue()); if (AppContext.isDebugMode()) { Log.d(TAG, String.format("httpDelete.setHeader(%s, %s)", header.getKey(), header.getValue()) ); } } }*/ //if ( TextUtils.isEmpty(conn.getRequestProperty("User-Agent")) ) { conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " WareNinjaAndroidSDK"//"com.wareninja.android.mayormonster"//CommonUtils.getMyUserAgent(mContext)// ); //} Bundle dataparams = new Bundle(); for (String key : params.keySet()) { byte[] byteArr = null; try { byteArr = (byte[]) params.get(key); } catch (Exception ex1) { } if (byteArr != null) dataparams.putByteArray(key, byteArr); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); appendRequestHeaders(conn, headers); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + strBoundary + endLine).getBytes()); os.write((CommonUtils.encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); String response = ""; try { response = CommonUtils.read(conn.getInputStream()); //mHttpResponseCode = conn.getResponseCode(); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = CommonUtils.read(conn.getErrorStream()); } if (AppContext.isDebugMode()) Log.d(TAG, "POST response: " + response); return response; }
From source file:com.code44.finance.ui.dialogs.recurrencepicker.RecurrencePickerDialogFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { eventBus.register(this); mRecurrence.wkst = EventRecurrence.timeDay2Day(Utils.getFirstDayOfWeek(getActivity())); getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE); boolean endCountHasFocus = false; if (savedInstanceState != null) { RecurrenceModel m = (RecurrenceModel) savedInstanceState.get(BUNDLE_MODEL); if (m != null) { mModel = m;//from ww w . j a v a 2 s.c o m } endCountHasFocus = savedInstanceState.getBoolean(BUNDLE_END_COUNT_HAS_FOCUS); } else { Bundle bundle = getArguments(); if (bundle != null) { mTime.set(bundle.getLong(BUNDLE_START_TIME_MILLIS)); String tz = bundle.getString(BUNDLE_TIME_ZONE); if (!TextUtils.isEmpty(tz)) { mTime.timezone = tz; } mTime.normalize(false); // Time days of week: Sun=0, Mon=1, etc mModel.weeklyByDayOfWeek[mTime.weekDay] = true; String rrule = bundle.getString(BUNDLE_RRULE); if (!TextUtils.isEmpty(rrule)) { mModel.recurrenceState = RecurrenceModel.STATE_RECURRENCE; mRecurrence.parse(rrule); copyEventRecurrenceToModel(mRecurrence, mModel); // Leave today's day of week as checked by default in weekly view. if (mRecurrence.bydayCount == 0) { mModel.weeklyByDayOfWeek[mTime.weekDay] = true; } } mModel.forceHideSwitchButton = bundle.getBoolean(BUNDLE_HIDE_SWITCH_BUTTON, false); } else { mTime.setToNow(); } } mResources = getResources(); mView = inflater.inflate(R.layout.recurrencepicker, container, true); final Activity activity = getActivity(); final Configuration config = activity.getResources().getConfiguration(); mRepeatSwitch = (SwitchCompat) mView.findViewById(R.id.repeat_switch); if (mModel.forceHideSwitchButton) { mRepeatSwitch.setChecked(true); mRepeatSwitch.setVisibility(View.GONE); mModel.recurrenceState = RecurrenceModel.STATE_RECURRENCE; } else { mRepeatSwitch.setChecked(mModel.recurrenceState == RecurrenceModel.STATE_RECURRENCE); mRepeatSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mModel.recurrenceState = isChecked ? RecurrenceModel.STATE_RECURRENCE : RecurrenceModel.STATE_NO_RECURRENCE; togglePickerOptions(); } }); } mFreqSpinner = (Spinner) mView.findViewById(R.id.freqSpinner); mFreqSpinner.setOnItemSelectedListener(this); ArrayAdapter<CharSequence> freqAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.recurrence_freq, R.layout.recurrencepicker_freq_item); freqAdapter.setDropDownViewResource(R.layout.recurrencepicker_freq_item); mFreqSpinner.setAdapter(freqAdapter); mIntervalGroup = (LinearLayout) mView.findViewById(R.id.intervalGroup); mInterval = (EditText) mView.findViewById(R.id.interval); mInterval.addTextChangedListener(new minMaxTextWatcher(1, INTERVAL_DEFAULT, INTERVAL_MAX) { @Override void onChange(int v) { if (mIntervalResId != -1 && mInterval.getText().toString().length() > 0) { mModel.interval = v; updateIntervalText(); mInterval.requestLayout(); } } }); mIntervalPreText = (TextView) mView.findViewById(R.id.intervalPreText); mIntervalPostText = (TextView) mView.findViewById(R.id.intervalPostText); mStartDatePreText = (TextView) mView.findViewById(R.id.startDatePreText); mStartDateTextView = (TextView) mView.findViewById(R.id.startDate); mStartDateTextView.setOnClickListener(this); if (mModel.startDate == null) { mModel.startDate = new Time(mTime); mModel.startDate.normalize(false); } mEndGroup = (LinearLayout) mView.findViewById(R.id.endGroup); mEndNeverStr = mResources.getString(R.string.recurrence_end_continously); mEndDateLabel = mResources.getString(R.string.recurrence_end_date_label); mEndCountLabel = mResources.getString(R.string.recurrence_end_count_label); mEndSpinnerArray.add(mEndNeverStr); mEndSpinnerArray.add(mEndDateLabel); mEndSpinnerArray.add(mEndCountLabel); mEndSpinner = (Spinner) mView.findViewById(R.id.endSpinner); mEndSpinner.setOnItemSelectedListener(this); mEndSpinnerAdapter = new EndSpinnerAdapter(getActivity(), mEndSpinnerArray, R.layout.recurrencepicker_freq_item, R.layout.recurrencepicker_end_text); mEndSpinnerAdapter.setDropDownViewResource(R.layout.recurrencepicker_freq_item); mEndSpinner.setAdapter(mEndSpinnerAdapter); mEndCount = (EditText) mView.findViewById(R.id.endCount); mEndCount.addTextChangedListener(new minMaxTextWatcher(1, COUNT_DEFAULT, COUNT_MAX) { @Override void onChange(int v) { if (mModel.endCount != v) { mModel.endCount = v; updateEndCountText(); mEndCount.requestLayout(); } } }); mPostEndCount = (TextView) mView.findViewById(R.id.postEndCount); mEndDateTextView = (TextView) mView.findViewById(R.id.endDate); mEndDateTextView.setOnClickListener(this); if (mModel.endDate == null) { mModel.endDate = new Time(mTime); switch (mModel.freq) { case RecurrenceModel.FREQ_DAILY: case RecurrenceModel.FREQ_WEEKLY: mModel.endDate.month += 1; break; case RecurrenceModel.FREQ_MONTHLY: mModel.endDate.month += 3; break; case RecurrenceModel.FREQ_YEARLY: mModel.endDate.year += 3; break; } mModel.endDate.normalize(false); } mWeekGroup = (LinearLayout) mView.findViewById(R.id.weekGroup); mWeekGroup2 = (LinearLayout) mView.findViewById(R.id.weekGroup2); // In Calendar.java day of week order e.g Sun = 1 ... Sat = 7 String[] dayOfWeekString = new DateFormatSymbols().getWeekdays(); mMonthRepeatByDayOfWeekStrs = new String[7][]; // from Time.SUNDAY as 0 through Time.SATURDAY as 6 mMonthRepeatByDayOfWeekStrs[0] = mResources.getStringArray(R.array.repeat_by_nth_sun); mMonthRepeatByDayOfWeekStrs[1] = mResources.getStringArray(R.array.repeat_by_nth_mon); mMonthRepeatByDayOfWeekStrs[2] = mResources.getStringArray(R.array.repeat_by_nth_tues); mMonthRepeatByDayOfWeekStrs[3] = mResources.getStringArray(R.array.repeat_by_nth_wed); mMonthRepeatByDayOfWeekStrs[4] = mResources.getStringArray(R.array.repeat_by_nth_thurs); mMonthRepeatByDayOfWeekStrs[5] = mResources.getStringArray(R.array.repeat_by_nth_fri); mMonthRepeatByDayOfWeekStrs[6] = mResources.getStringArray(R.array.repeat_by_nth_sat); // In Time.java day of week order e.g. Sun = 0 int idx = Utils.getFirstDayOfWeek(getActivity()); // In Calendar.java day of week order e.g Sun = 1 ... Sat = 7 dayOfWeekString = new DateFormatSymbols().getShortWeekdays(); int numOfButtonsInRow1; int numOfButtonsInRow2; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) { // Get screen width in dp first Display display = getActivity().getWindowManager().getDefaultDisplay(); DisplayMetrics outMetrics = new DisplayMetrics(); display.getMetrics(outMetrics); float density = getResources().getDisplayMetrics().density; float dpWidth = outMetrics.widthPixels / density; if (dpWidth > MIN_SCREEN_WIDTH_FOR_SINGLE_ROW_WEEK) { numOfButtonsInRow1 = 7; numOfButtonsInRow2 = 0; mWeekGroup2.setVisibility(View.GONE); mWeekGroup2.getChildAt(3).setVisibility(View.GONE); } else { numOfButtonsInRow1 = 4; numOfButtonsInRow2 = 3; mWeekGroup2.setVisibility(View.VISIBLE); // Set rightmost button on the second row invisible so it takes up // space and everything centers properly mWeekGroup2.getChildAt(3).setVisibility(View.INVISIBLE); } } else if (mResources.getConfiguration().screenWidthDp > MIN_SCREEN_WIDTH_FOR_SINGLE_ROW_WEEK) { numOfButtonsInRow1 = 7; numOfButtonsInRow2 = 0; mWeekGroup2.setVisibility(View.GONE); mWeekGroup2.getChildAt(3).setVisibility(View.GONE); } else { numOfButtonsInRow1 = 4; numOfButtonsInRow2 = 3; mWeekGroup2.setVisibility(View.VISIBLE); // Set rightmost button on the second row invisible so it takes up // space and everything centers properly mWeekGroup2.getChildAt(3).setVisibility(View.INVISIBLE); } /* First row */ for (int i = 0; i < 7; i++) { if (i >= numOfButtonsInRow1) { mWeekGroup.getChildAt(i).setVisibility(View.GONE); continue; } mWeekByDayButtons[idx] = (ToggleButton) mWeekGroup.getChildAt(i); mWeekByDayButtons[idx].setTextOff(dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[idx]]); mWeekByDayButtons[idx].setTextOn(dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[idx]]); mWeekByDayButtons[idx].setOnCheckedChangeListener(this); if (++idx >= 7) { idx = 0; } } /* 2nd Row */ for (int i = 0; i < 3; i++) { if (i >= numOfButtonsInRow2) { mWeekGroup2.getChildAt(i).setVisibility(View.GONE); continue; } mWeekByDayButtons[idx] = (ToggleButton) mWeekGroup2.getChildAt(i); mWeekByDayButtons[idx].setTextOff(dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[idx]]); mWeekByDayButtons[idx].setTextOn(dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[idx]]); mWeekByDayButtons[idx].setOnCheckedChangeListener(this); if (++idx >= 7) { idx = 0; } } mMonthGroup = (LinearLayout) mView.findViewById(R.id.monthGroup); mMonthRepeatByRadioGroup = (RadioGroup) mView.findViewById(R.id.monthGroup); mMonthRepeatByRadioGroup.setOnCheckedChangeListener(this); mRepeatMonthlyByNthDayOfWeek = (RadioButton) mView.findViewById(R.id.repeatMonthlyByNthDayOfTheWeek); mRepeatMonthlyByNthDayOfMonth = (RadioButton) mView.findViewById(R.id.repeatMonthlyByNthDayOfMonth); mDoneButton = (Button) mView.findViewById(R.id.done_button); mDoneButton.setOnClickListener(this); Button cancelButton = (Button) mView.findViewById(R.id.cancel_button); //FIXME no text color for this one ? cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); togglePickerOptions(); updateDialog(); if (endCountHasFocus) { mEndCount.requestFocus(); } return mView; }
From source file:com.gdglab.iot.gcm.GcmIntentService.java
@Override protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); // The getMessageType() intent parameter must be the intent you received // in your BroadcastReceiver. String messageType = gcm.getMessageType(intent); if (!extras.isEmpty()) { // has effect of unparcelling Bundle /*/* w ww. ja v a 2 s .co m*/ * Filter messages based on message type. Since it is likely that GCM will be * extended in the future with new message types, just ignore any message types you're * not interested in, or that you don't recognize. */ if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { sendNotification("Send error: " + extras.toString()); } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) { sendNotification("Deleted messages on server: " + extras.toString()); // If it's a regular GCM message, do some work. } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { // This loop represents the service doing some work. // for (int i = 0; i < 5; i++) { // Log.i(TAG, "Working... " + (i + 1) // + "/5 @ " + SystemClock.elapsedRealtime()); // try { // Thread.sleep(5000); // } catch (InterruptedException e) { // } // } // Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime()); // Post notification of received message. Log.i(TAG, "Received: " + extras.toString()); String text = (String) extras.get("message"); JSONObject json = null; String msgText = ""; try { json = new JSONObject(text); msgText = json.getString("text"); Log.i(TAG, "received text : " + msgText); sendNotification(msgText); } catch (JSONException e) { Log.e(TAG, "Error with JSON message"); e.printStackTrace(); } } } // Release the wake lock provided by the WakefulBroadcastReceiver. GcmBroadcastReceiver.completeWakefulIntent(intent); }
From source file:com.canappi.connector.yp.yhere.SearchView.java
public void viewDidLoad() { Bundle extras = getIntent().getExtras(); if (extras != null) { Set<String> keys = extras.keySet(); for (Iterator<String> iter = keys.iterator(); iter.hasNext();) { String key = iter.next(); Class c = SearchView.class; try { Field f = c.getDeclaredField(key); Object extra = extras.get(key); String value = extra.toString(); f.set(this, value); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace();/*from ww w . j a v a2 s .c o m*/ } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else { } searchViewIds = new HashMap(); searchViewValues = new HashMap(); isUserDefault = false; resultsListView = (ListView) findViewById(R.id.resultsTable); resultsAdapter = new ResultsEfficientAdapter(this); businessNameArray = new ArrayList<String>(); latitudeArray = new ArrayList<String>(); longitudeArray = new ArrayList<String>(); listingIdArray = new ArrayList<String>(); phoneArray = new ArrayList<String>(); callArray = new ArrayList<String>(); streetArray = new ArrayList<String>(); cityArray = new ArrayList<String>(); resultsListView.setAdapter(resultsAdapter); didSelectViewController(); }
From source file:com.google.android.apps.paco.FeedbackActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); experimentProviderUtil = new ExperimentProviderUtil(this); experiment = getExperimentFromIntent(); if (experiment == null) { displayNoExperimentMessage();//from ww w . ja v a2s .co m } else { setContentView(R.layout.feedback); experimentProviderUtil.loadLastEventForExperiment(experiment); rawDataButton = (Button) findViewById(R.id.rawDataButton); rawDataButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent rawDataIntent = new Intent(FeedbackActivity.this, RawDataActivity.class); rawDataIntent.setData(getIntent().getData()); startActivity(rawDataIntent); } }); webView = (WebView) findViewById(R.id.feedbackText); webView.getSettings().setJavaScriptEnabled(true); final Feedback feedback = experiment.getFeedback().get(0); injectObjectsIntoJavascriptEnvironment(feedback); setWebChromeClientThatHandlesAlertsAsDialogs(); WebViewClient webViewClient = createWebViewClientThatHandlesFileLinksForCharts(feedback); webView.setWebViewClient(webViewClient); if (experiment.getFeedbackType() == FeedbackDAO.FEEDBACK_TYPE_RETROSPECTIVE) { // TODO get rid of this and just use the customFeedback view loadOldDefaultFeedbackIntoWebView(); } else { loadCustomFeedbackIntoWebView(); } if (savedInstanceState != null) { webView.loadUrl((String) savedInstanceState.get("url")); String showDialogString = (String) savedInstanceState.get("showDialog"); if (showDialogString.equals("false")) { showDialog = false; } else { showDialog = true; } } } }
From source file:edu.mines.letschat.GcmIntentService.java
@Override protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); // The getMessageType() intent parameter must be the intent you received // in your BroadcastReceiver. String messageType = gcm.getMessageType(intent); if (!extras.isEmpty()) { // has effect of unparcelling Bundle /*//w w w . ja va 2s .c o m * Filter messages based on message type. Since it is likely that GCM will be * extended in the future with new message types, just ignore any message types you're * not interested in, or that you don't recognize. */ if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { sendNotification("Send error: " + extras.toString(), "0"); } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) { sendNotification("Deleted messages on server: " + extras.toString(), "0"); // If it's a regular GCM message, do some work. } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { // This loop represents the service doing some work. // for (int i = 0; i < 5; i++) { // Log.i(TAG, "Working... " + (i + 1) // + "/5 @ " + SystemClock.elapsedRealtime()); // try { // Thread.sleep(5000); // } catch (InterruptedException e) { // } // } Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime()); // Post notification of received message. String message = (String) extras.get("message"); messages.add(message); String picture = (String) extras.get("picture"); String senderID = (String) extras.get("sender"); String recipientID = (String) extras.get("recipient"); sendNotification(message, senderID); Log.v(TAG, "Received: " + message); Log.i(TAG, "Received: " + extras.toString()); Intent resultBroadCastIntent = new Intent(); /*set action here*/ resultBroadCastIntent.setAction( edu.mines.letschat.MessageActivity.TextCapitalizeResultReceiver.ACTION_TEXT_CAPITALIZED); /*set intent category as default*/ resultBroadCastIntent.addCategory(Intent.CATEGORY_DEFAULT); /*add data to intent*/ resultBroadCastIntent.putExtra(OUTPUT_TEXT, message); // Log.v(TAG, "Sender id " + senderID + " recieve id " + recipientID); Log.v(TAG, picture); Conversation convo = new Conversation(getApplicationContext(), senderID, recipientID, message, false, picture); convo.save(); if (!picture.isEmpty()) { new DownloadImage(picture).execute(); } /*send broadcast */ sendBroadcast(resultBroadCastIntent); } } // Release the wake lock provided by the WakefulBroadcastReceiver. GcmBroadcastReviever.completeWakefulIntent(intent); }
From source file:com.fsck.k9.activity.Accounts.java
@SuppressWarnings("unchecked") private void restoreAccountStats(Bundle icicle) { if (icicle != null) { Map<String, AccountStats> oldStats = (Map<String, AccountStats>) icicle.get(ACCOUNT_STATS); if (oldStats != null) { accountStats.putAll(oldStats); }/* w w w.j a va 2 s . c o m*/ mUnreadMessageCount = icicle.getInt(STATE_UNREAD_COUNT); } }
From source file:com.dwdesign.tweetings.util.Utils.java
public static String buildArguments(final Bundle args) { final Set<String> keys = args.keySet(); final JSONObject json = new JSONObject(); for (final String key : keys) { final Object value = args.get(key); if (value == null) { continue; }/*from w w w. j ava 2 s. c o m*/ try { if (value instanceof Boolean) { json.put(key, args.getBoolean(key)); } else if (value instanceof Integer) { json.put(key, args.getInt(key)); } else if (value instanceof Long) { json.put(key, args.getLong(key)); } else if (value instanceof String) { json.put(key, args.getString(key)); } else { Log.w(LOGTAG, "Unknown type " + (value != null ? value.getClass().getSimpleName() : null) + " in arguments key " + key); } } catch (final JSONException e) { e.printStackTrace(); } } return json.toString(); }
From source file:com.firescar96.nom.GCMIntentService.java
@Override protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); // The getMessageType() intent parameter must be the intent you received // in your BroadcastReceiver. String messageType = gcm.getMessageType(intent); if (!extras.isEmpty()) /*//from www . j av a 2 s.c o m * Filter messages based on message type. Since it is likely that GCM will be * extended in the future with new message types, just ignore any message types you're * not interested in, or that you don't recognize. */ if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) Log.i(Consts.TAG, "onHandleIntent: message error"); else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) Log.i(Consts.TAG, "onHandleIntent: message deleted"); // If it's a regular GCM message, do some work. else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { // Post notification of received message. System.out.println("Received: " + extras.toString()); if (context == null) { System.out.println("null conxtext"); /*Intent needIntent = new Intent(this, MainActivity.class); needIntent.putExtra("purpose", "update"); needIntent.putExtra("mate", (String)extras.get("mate")); needIntent.putExtra("event", (String)extras.get("event")); needIntent.putExtra("chat", (String)extras.get("chat")); needIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(needIntent);*/ System.out.println(getFilesDir().getAbsolutePath()); MainActivity.initAppData(getFilesDir().getAbsolutePath()); } try { if (extras.get("mate") != null) { //context.appData.getJSONArray("mates").put(extras.get("mate")); } if (extras.get("event") != null) { JSONObject eveData = new JSONObject("{\"event\":" + extras.get("event") + "}") .getJSONObject("event"); JSONArray eve = MainActivity.appData.getJSONArray("events"); for (int i = 0; i < eve.length(); i++) { System.out.println(eveData.getString("hash")); System.out.println(eve.getJSONObject(i).getString("hash")); if (eveData.getString("hash").equals(eve.getJSONObject(i).getString("hash"))) return; } eveData.accumulate("member", false); System.out.println(eveData.getLong("date")); System.out.println(Calendar.getInstance().getTimeInMillis()); if (eveData.getLong("date") < Calendar.getInstance().getTimeInMillis()) return; eve.put(eveData); Message msg = new Message(); Bundle data = new Bundle(); data.putString("type", "event." + eveData.getString("privacy")); data.putString("host", eveData.getString("host")); data.putString("date", eveData.getString("date")); msg.setData(data); contextHandler.sendMessage(msg); } if (extras.get("chat") != null) { JSONObject chatData = new JSONObject("{\"chat\":" + extras.get("chat") + "}") .getJSONObject("chat"); JSONArray eve = MainActivity.appData.getJSONArray("events"); for (int i = 0; i < eve.length(); i++) if (chatData.getString("hash").equals(eve.getJSONObject(i).getString("hash"))) { JSONObject msgSon = new JSONObject(); msgSon.accumulate("author", chatData.getString("author")); msgSon.accumulate("message", chatData.getString("message")); eve.getJSONObject(i).getJSONArray("chat").put(msgSon); Message msg = new Message(); Bundle data = new Bundle(); data.putString("type", "chat"); data.putString("author", chatData.getString("author")); data.putString("message", chatData.getString("message")); data.putBoolean("member", eve.getJSONObject(i).getBoolean("member")); data.putString("hash", chatData.getString("hash")); msg.setData(data); contextHandler.sendMessage(msg); return; } } MainActivity.closeAppData(getFilesDir().getAbsolutePath()); } catch (JSONException e1) { e1.printStackTrace(); } } // Release the wake lock provided by the WakefulBroadcastReceiver. MainBroadcastReceiver.completeWakefulIntent(intent); }