Example usage for android.content Intent hasExtra

List of usage examples for android.content Intent hasExtra

Introduction

In this page you can find the example usage for android.content Intent hasExtra.

Prototype

public boolean hasExtra(String name) 

Source Link

Document

Returns true if an extra value is associated with the given name.

Usage

From source file:com.jtechme.apphub.AppDetailsData.java

/**
 * Attempt to extract the packageName from the intent which launched this activity.
 * @return May return null, if we couldn't find the packageName. This should
 * never happen as AppDetails is only to be called by the FDroid activity
 * and not externally./*from w  w  w  . ja  va2 s. c  om*/
 */
private String getPackageNameFromIntent(Intent intent) {
    if (!intent.hasExtra(EXTRA_APPID)) {
        Log.e(TAG, "No package name found in the intent!");
        return null;
    }

    return intent.getStringExtra(EXTRA_APPID);
}

From source file:uk.bowdlerize.service.CensorCensusService.java

@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
    if (null == mNotifyManager)
        mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    if (null == mBuilder)
        mBuilder = new NotificationCompat.Builder(this);

    if (null == api)
        api = new API(this);

    mContext = this;

    checkedCount = getPreferences(this).getInt("checkedCount", 0);
    censoredCount = getPreferences(this).getInt("censoredCount", 0);
    sendtoORG = getPreferences(this).getBoolean("sendToOrg", false);

    //Make it so tapping an intent will launch the app (Fix #12)
    launchAppIntent = new Intent(mContext, MainActivity.class);
    pendingIntent = PendingIntent.getActivity(mContext, 0, launchAppIntent, 0);
    mBuilder.setContentIntent(pendingIntent);

    //Lets findout why we've been started
    if (intent.getBooleanExtra(API.EXTRA_POLL, false) || intent.getBooleanExtra(API.EXTRA_GCM_TICKLE, false)) {
        prepProbe(intent);/*from   ww  w .ja  v a  2 s . com*/
    } else if (intent.hasExtra("url") && !intent.getStringExtra("url").equals("")) {
        performProbe(intent);
    } else {
        onProbeFinish();
    }

    //If we're polling we probably want to stay alive
    if (getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE)
            .getInt(API.SETTINGS_GCM_PREFERENCE, API.SETTINGS_GCM_FULL) == API.SETTINGS_GCM_DISABLED) {
        return START_STICKY;
    } else {
        return START_NOT_STICKY;
    }
}

From source file:com.android.deskclock.AlarmClockFragment.java

@Override
public void onResume() {
    super.onResume();

    final DeskClock activity = (DeskClock) getActivity();
    if (activity.getSelectedTab() == DeskClock.ALARM_TAB_INDEX) {
        setFabAppearance();/*w  ww . j  a  va2s .  co  m*/
        setLeftRightButtonAppearance();
    }
    final int startDay = Utils.getZeroIndexedFirstDayOfWeek(getActivity());
    mDayOrder = new int[DaysOfWeek.DAYS_IN_A_WEEK];

    for (int i = 0; i < DaysOfWeek.DAYS_IN_A_WEEK; ++i) {
        mDayOrder[i] = DAY_ORDER[(startDay + i) % 7];
    }

    // Check if another app asked us to create a blank new alarm.
    final Intent intent = getActivity().getIntent();
    if (intent.hasExtra(ALARM_CREATE_NEW_INTENT_EXTRA)) {
        if (intent.getBooleanExtra(ALARM_CREATE_NEW_INTENT_EXTRA, false)) {
            // An external app asked us to create a blank alarm.
            startCreatingAlarm();
        }

        // Remove the CREATE_NEW extra now that we've processed it.
        intent.removeExtra(ALARM_CREATE_NEW_INTENT_EXTRA);
    } else if (intent.hasExtra(SCROLL_TO_ALARM_INTENT_EXTRA)) {
        long alarmId = intent.getLongExtra(SCROLL_TO_ALARM_INTENT_EXTRA, Alarm.INVALID_ID);
        if (alarmId != Alarm.INVALID_ID) {
            mScrollToAlarmId = alarmId;
            if (mCursorLoader != null && mCursorLoader.isStarted()) {
                // We need to force a reload here to make sure we have the latest view
                // of the data to scroll to.
                mCursorLoader.forceLoad();
            }
        }

        // Remove the SCROLL_TO_ALARM extra now that we've processed it.
        intent.removeExtra(SCROLL_TO_ALARM_INTENT_EXTRA);
    }

    setTimePickerListener();
}

From source file:com.coact.kochzap.CaptureActivity.java

@Override
protected void onResume() {
    super.onResume();

    // historyManager must be initialized here to update the history preference
    historyManager = new HistoryManager(this);
    historyManager.trimHistory();//  w  w w  .  ja  v a2 s .c o m

    // CameraManager must be initialized here, not in onCreate(). This is necessary because we don't
    // want to open the camera driver and measure the screen size if we're going to show the help on
    // first launch. That led to bugs where the scanning rectangle was the wrong size and partially
    // off screen.
    cameraManager = new CameraManager(getApplication());

    viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
    viewfinderView.setCameraManager(cameraManager);

    resultView = findViewById(R.id.result_view);
    statusView = (TextView) findViewById(R.id.status_view);

    handler = null;
    lastResult = null;

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);

    resetStatusView();

    beepManager.updatePrefs();
    ambientLightManager.start(cameraManager);

    inactivityTimer.onResume();

    Intent intent = getIntent();

    copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true)
            && (intent == null || intent.getBooleanExtra(Intents.Scan.SAVE_HISTORY, true));

    source = IntentSource.NONE;
    sourceUrl = null;
    scanFromWebPageManager = null;
    decodeFormats = null;
    characterSet = null;

    if (intent != null) {

        String action = intent.getAction();
        String dataString = intent.getDataString();

        if (Intents.Scan.ACTION.equals(action)) {
            // Scan the formats the intent requested, and return the result to the calling activity.
            source = IntentSource.NATIVE_APP_INTENT;
            decodeFormats = DecodeFormatManager.parseDecodeFormats(intent);
            decodeHints = DecodeHintManager.parseDecodeHints(intent);

            if (intent.hasExtra(Intents.Scan.WIDTH) && intent.hasExtra(Intents.Scan.HEIGHT)) {
                int width = intent.getIntExtra(Intents.Scan.WIDTH, 0);
                int height = intent.getIntExtra(Intents.Scan.HEIGHT, 0);
                if (width > 0 && height > 0) {
                    cameraManager.setManualFramingRect(width, height);
                }
            }

            if (intent.hasExtra(Intents.Scan.CAMERA_ID)) {
                int cameraId = intent.getIntExtra(Intents.Scan.CAMERA_ID, -1);
                if (cameraId >= 0) {
                    cameraManager.setManualCameraId(cameraId);
                }
            }

            String customPromptMessage = intent.getStringExtra(Intents.Scan.PROMPT_MESSAGE);
            if (customPromptMessage != null) {
                statusView.setText(customPromptMessage);
            }
        } else if (dataString != null && dataString.contains("http://www.google")
                && dataString.contains("/m/products/scan")) {

            // Scan only products and send the result to mobile Product Search.
            source = IntentSource.PRODUCT_SEARCH_LINK;
            sourceUrl = dataString;
            decodeFormats = DecodeFormatManager.PRODUCT_FORMATS;
        } else if (isZXingURL(dataString)) {

            // Scan formats requested in query string (all formats if none specified).
            // If a return URL is specified, send the results there. Otherwise, handle it ourselves.
            source = IntentSource.ZXING_LINK;
            sourceUrl = dataString;
            Uri inputUri = Uri.parse(dataString);
            scanFromWebPageManager = new ScanFromWebPageManager(inputUri);
            decodeFormats = DecodeFormatManager.parseDecodeFormats(inputUri);
            // Allow a sub-set of the hints to be specified by the caller.
            decodeHints = DecodeHintManager.parseDecodeHints(inputUri);

        }
        characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);
    }

    SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
    SurfaceHolder surfaceHolder = surfaceView.getHolder();
    if (hasSurface) {
        // The activity was paused but not stopped, so the surface still exists. Therefore
        // surfaceCreated() won't be called, so init the camera here.
        initCamera(surfaceHolder);
    } else {
        // Install the callback and wait for surfaceCreated() to init the camera.
        surfaceHolder.addCallback(this);
    }
}

From source file:com.embeddedlog.LightUpDroid.timer.TimerReceiver.java

@Override
public void onReceive(final Context context, final Intent intent) {
    if (Timers.LOGGING) {
        Log.v(TAG, "Received intent " + intent.toString());
    }//  w w  w .j av a2  s  . c  om
    String actionType = intent.getAction();
    // This action does not need the timers data
    if (Timers.NOTIF_IN_USE_CANCEL.equals(actionType)) {
        cancelInUseNotification(context);
        return;
    }

    // Get the updated timers data.
    if (mTimers == null) {
        mTimers = new ArrayList<TimerObj>();
    }
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    TimerObj.getTimersFromSharedPrefs(prefs, mTimers);

    // These actions do not provide a timer ID, but do use the timers data
    if (Timers.NOTIF_IN_USE_SHOW.equals(actionType)) {
        showInUseNotification(context);
        return;
    } else if (Timers.NOTIF_TIMES_UP_SHOW.equals(actionType)) {
        showTimesUpNotification(context);
        return;
    } else if (Timers.NOTIF_TIMES_UP_CANCEL.equals(actionType)) {
        cancelTimesUpNotification(context);
        return;
    }

    // Remaining actions provide a timer Id
    if (!intent.hasExtra(Timers.TIMER_INTENT_EXTRA)) {
        // No data to work with, do nothing
        Log.e(TAG, "got intent without Timer data");
        return;
    }

    // Get the timer out of the Intent
    int timerId = intent.getIntExtra(Timers.TIMER_INTENT_EXTRA, -1);
    if (timerId == -1) {
        Log.d(TAG, "OnReceive:intent without Timer data for " + actionType);
    }

    TimerObj t = Timers.findTimer(mTimers, timerId);

    if (Timers.TIMES_UP.equals(actionType)) {
        // Find the timer (if it doesn't exists, it was probably deleted).
        if (t == null) {
            Log.d(TAG, " timer not found in list - do nothing");
            return;
        }

        t.mState = TimerObj.STATE_TIMESUP;
        t.writeToSharedPref(prefs);
        // Play ringtone by using TimerRingService service with a default alarm.
        Log.d(TAG, "playing ringtone");
        Intent si = new Intent();
        si.setClass(context, TimerRingService.class);
        context.startService(si);

        // Update the in-use notification
        if (getNextRunningTimer(mTimers, false, Utils.getTimeNow()) == null) {
            // Found no running timers.
            cancelInUseNotification(context);
        } else {
            showInUseNotification(context);
        }

        // Start the TimerAlertFullScreen activity.
        Intent timersAlert = new Intent(context, TimerAlertFullScreen.class);
        timersAlert.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
        context.startActivity(timersAlert);
    } else if (Timers.TIMER_RESET.equals(actionType) || Timers.DELETE_TIMER.equals(actionType)
            || Timers.TIMER_DONE.equals(actionType)) {
        // Stop Ringtone if all timers are not in times-up status
        stopRingtoneIfNoTimesup(context);
    } else if (Timers.NOTIF_TIMES_UP_STOP.equals(actionType)) {
        // Find the timer (if it doesn't exists, it was probably deleted).
        if (t == null) {
            Log.d(TAG, "timer to stop not found in list - do nothing");
            return;
        } else if (t.mState != TimerObj.STATE_TIMESUP) {
            Log.d(TAG, "action to stop but timer not in times-up state - do nothing");
            return;
        }

        // Update timer state
        t.mState = t.getDeleteAfterUse() ? TimerObj.STATE_DELETED : TimerObj.STATE_DONE;
        t.mTimeLeft = t.mOriginalLength - (Utils.getTimeNow() - t.mStartTime);
        t.writeToSharedPref(prefs);

        // Flag to tell DeskClock to re-sync with the database
        prefs.edit().putBoolean(Timers.FROM_NOTIFICATION, true).apply();

        cancelTimesUpNotification(context, t);

        // Done with timer - delete from data base
        if (t.getDeleteAfterUse()) {
            t.deleteFromSharedPref(prefs);
        }

        // Stop Ringtone if no timers are in times-up status
        stopRingtoneIfNoTimesup(context);
    } else if (Timers.NOTIF_TIMES_UP_PLUS_ONE.equals(actionType)) {
        // Find the timer (if it doesn't exists, it was probably deleted).
        if (t == null) {
            Log.d(TAG, "timer to +1m not found in list - do nothing");
            return;
        } else if (t.mState != TimerObj.STATE_TIMESUP) {
            Log.d(TAG, "action to +1m but timer not in times up state - do nothing");
            return;
        }

        // Restarting the timer with 1 minute left.
        t.mState = TimerObj.STATE_RUNNING;
        t.mStartTime = Utils.getTimeNow();
        t.mTimeLeft = t.mOriginalLength = TimerObj.MINUTE_IN_MILLIS;
        t.writeToSharedPref(prefs);

        // Flag to tell DeskClock to re-sync with the database
        prefs.edit().putBoolean(Timers.FROM_NOTIFICATION, true).apply();

        cancelTimesUpNotification(context, t);

        // If the app is not open, refresh the in-use notification
        if (!prefs.getBoolean(Timers.NOTIF_APP_OPEN, false)) {
            showInUseNotification(context);
        }

        // Stop Ringtone if no timers are in times-up status
        stopRingtoneIfNoTimesup(context);
    } else if (Timers.TIMER_UPDATE.equals(actionType)) {
        // Refresh buzzing notification
        if (t.mState == TimerObj.STATE_TIMESUP) {
            // Must cancel the previous notification to get all updates displayed correctly
            cancelTimesUpNotification(context, t);
            showTimesUpNotification(context, t);
        }
    }
    // Update the next "Times up" alarm
    updateNextTimesup(context);
}

From source file:com.ubuntuone.android.files.service.MetaService.java

@Override
protected void onHandleIntent(Intent intent) {
    sSyncRunning = true;//from   w  ww .j  ava  2 s.  co 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.givon.anhao.activity.ChatActivity.java

private void setUpView() {
    activityInstance = this;
    iv_emoticons_normal.setOnClickListener(this);
    iv_emoticons_checked.setOnClickListener(this);
    // position = getIntent().getIntExtra("position", -1);
    clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE))
            .newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");
    // ???/*from   www. j a va 2 s.com*/
    Intent intent = getIntent();
    chatType = intent.getIntExtra("chatType", CHATTYPE_SINGLE);
    if (chatType == CHATTYPE_SINGLE) { // ??
        if (intent.hasExtra("userId")) {
            toChatUsername = intent.getStringExtra("userId");
            // ((TextView) findViewById(R.id.name)).setText(toChatUsername);
            // toChatUsername = intent.getStringExtra("userId");
            String title = intent.getStringExtra("location");
            ((TextView) findViewById(R.id.name)).setText(title);
            // if (intent.hasExtra("data")) {
            // mUserBean = (UserBean) intent.getSerializableExtra("data");
            // toChatUsername = mUserBean.getEasemobId();
            // }
            isFriend = AnhaoApplication.getInstance().getContactListOld().containsKey(toChatUsername);
            isHello = AnhaoApplication.getInstance().getHelloContactList().containsKey(toChatUsername);
        }
    } else {
        // TODO ?isCanAddFriend UserDao???? ? true
        // ?
        findViewById(R.id.container_to_group).setVisibility(View.VISIBLE);
        findViewById(R.id.container_remove).setVisibility(View.GONE);
        toChatUsername = getIntent().getStringExtra("groupId");
        group = EMGroupManager.getInstance().getGroup(toChatUsername);
        ((TextView) findViewById(R.id.name)).setText(group.getGroupName());
        // toChatUsername = getIntent().getStringExtra("groupId");
        // if (intent.hasExtra("data")) {
        // mUserBean = (UserBean) intent.getParcelableExtra("data");
        // toChatUsername = mUserBean.getEasemobId();
        // }
        // isCanAddFriend = false;
        // group = EMGroupManager.getInstance().getGroup(toChatUsername);

        isFriend = AnhaoApplication.getInstance().getContactListOld().containsKey(toChatUsername);
        isHello = AnhaoApplication.getInstance().getHelloContactList().containsKey(toChatUsername);
        // ((TextView) findViewById(R.id.name)).setText(mRoomBean.getRoomName());
    }
    conversation = EMChatManager.getInstance().getConversation(toChatUsername);
    // ?0
    conversation.resetUnsetMsgCount();
    adapter = new MessageAdapter(this, toChatUsername, chatType);
    // ?
    listView.setAdapter(adapter);
    listView.setOnScrollListener(new ListScrollListener());
    int count = listView.getCount();
    if (count > 0) {
        listView.setSelection(count - 1);
    }

    listView.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            hideKeyboard();
            more.setVisibility(View.GONE);
            iv_emoticons_normal.setVisibility(View.VISIBLE);
            iv_emoticons_checked.setVisibility(View.INVISIBLE);
            expressionContainer.setVisibility(View.GONE);
            btnContainer.setVisibility(View.GONE);
            return false;
        }
    });
    // ?
    receiver = new NewMessageBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
    // Mainacitivity,??chat??????
    intentFilter.setPriority(5);
    registerReceiver(receiver, intentFilter);

    // ack?BroadcastReceiver
    IntentFilter ackMessageIntentFilter = new IntentFilter(
            EMChatManager.getInstance().getAckMessageBroadcastAction());
    ackMessageIntentFilter.setPriority(5);
    registerReceiver(ackMessageReceiver, ackMessageIntentFilter);

    // ????T
    groupListener = new GroupListener();
    EMGroupManager.getInstance().addGroupChangeListener(groupListener);

    // show forward message if the message is not null
    String forward_msg_id = getIntent().getStringExtra("forward_msg_id");
    if (forward_msg_id != null) {
        // ?????
        forwardMessage(forward_msg_id);
    }

}

From source file:com.google.appinventor.components.runtime.Form.java

@Override
public void onCreate(Bundle icicle) {
    // Called when the activity is first created
    super.onCreate(icicle);
    Log.i(LOG_TAG, "saveBundle" + icicle);
    onCreateBundle = icicle; // icicle, (savedInstance == null) if it's not the result of changing orientation

    // Figure out the name of this form.
    String className = getClass().getName();
    int lastDot = className.lastIndexOf('.');
    formName = className.substring(lastDot + 1);
    Log.d(LOG_TAG, "Form " + formName + " got onCreate");

    activeForm = this;
    Log.i(LOG_TAG, "activeForm is now " + activeForm.formName);

    viewLayout = new LinearLayout(this, ComponentConstants.LAYOUT_ORIENTATION_VERTICAL);
    components = new ArrayList<AndroidViewComponent>();
    alignmentSetter = new AlignmentUtil(viewLayout);

    defaultPropertyValues();/* www .j  a va  2s  . c  o m*/

    // Get startup text if any before adding components
    Intent startIntent = getIntent();
    if (startIntent != null && startIntent.hasExtra(ARGUMENT_NAME)) {
        startupValue = startIntent.getStringExtra(ARGUMENT_NAME);
    }

    fullScreenVideoUtil = new FullScreenVideoUtil(this, androidUIHandler);

    /*
     * Add by Fuming.
     * We can save extras values that are intended for the Survey component, 
     * and later the component can read the value through container$form 
     * TODO: need to think about how to pass intent to a component through notification.
     * Something like the activity starter: the extra_key will be the component name 
     * the extra_value to pass in will be a json string. 
     * 
     * TODO: We could think of a more general approach that could work for arbitrary AI component that needs
     * intent data at start up.
     * 
     */

    if (startIntent != null && startIntent.hasExtra(ARGUMENT_SURVEY)) {
        Log.i(LOG_TAG, "surveyIntentValue:" + startIntent.getStringExtra(ARGUMENT_SURVEY));
        startupValueForSurvey = startIntent.getStringExtra(ARGUMENT_SURVEY);
    }

    /*
     * Add by Weihua Li.
     * We can save extras values that are intended for the GCM component, 
     * and later the component can read the value through container$form 
     * TODO: need to think about how to pass intent to a component through notification.
     * Something like the activity starter: the extra_key will be the component name 
     * the extra_value to pass in will be a json string. 
     * 
     * TODO: We could think of a more general approach that could work for arbitrary AI component that needs
     * intent data at start up.
     * 
     */

    if (startIntent != null && startIntent.hasExtra(ARGUMENT_GCM)) {
        Log.i(LOG_TAG, "GCMIntentValue:" + startIntent.getStringExtra(ARGUMENT_GCM));
        startupValueForGCM = startIntent.getStringExtra(ARGUMENT_GCM);
    }

    // Set soft keyboard to not cover the focused UI element, e.g., when you are typing
    // into a textbox near the bottom of the screen.
    WindowManager.LayoutParams params = getWindow().getAttributes();
    int softInputMode = params.softInputMode;
    getWindow().setSoftInputMode(softInputMode | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

    // Add application components to the form
    $define();

    // Special case for Event.Initialize(): all other initialize events are triggered after
    // completing the constructor. This doesn't work for Android apps though because this method
    // is called after the constructor completes and therefore the Initialize event would run
    // before initialization finishes. Instead the compiler suppresses the invocation of the
    // event and leaves it up to the library implementation.
    Initialize();
}

From source file:com.gcm.client.RegistrationIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    try {/* w  w  w .  ja va  2s  .c  o m*/
        if (null != intent) {
            String action = intent.getAction();
            String senderId = GcmHelper.getInstance().getAuthorizedEntity();

            InstanceID instanceID = InstanceID.getInstance(this);
            if (ACTION_REGISTER.equals(action)) {
                String token = registerForToken(instanceID, senderId);
                //subscribe topics
                ArrayList<String> topics = GcmHelper.getInstance().getSubscribedTopics();
                if (null != topics && topics.isEmpty()) {
                    String[] stringArray = new String[topics.size()];
                    // Subscribe to topic channels
                    subscribeTopics(token, topics.toArray(stringArray));
                }
                // Notify UI that registration has completed, so the progress indicator can be hidden.
                Intent registrationComplete = new Intent(REGISTRATION_COMPLETE);
                LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
                if (GcmHelper.DEBUG_ENABLED)
                    Log.d(GcmHelper.TAG, "RegistrationIntentService: registration completed");
                return;
            } else if (ACTION_UNREGISTER.equals(action)) {
                unRegisterToken(instanceID, senderId);
                if (GcmHelper.DEBUG_ENABLED)
                    Log.d(GcmHelper.TAG, "RegistrationIntentService: successfully unregistered");
                return;
            }
            if (intent.hasExtra(EXTRA_TOPIC_LIST)) {
                final String topics[] = intent.getStringArrayExtra(EXTRA_TOPIC_LIST);
                String pushToken = GcmHelper.getInstance().getPushToken(getApplicationContext());
                if (TextUtils.isEmpty(pushToken)) {
                    return;
                }
                if (ACTION_UNSUBSCRIBE.equals(action)) {
                    unsubscribeTopics(pushToken, topics);
                    if (GcmHelper.DEBUG_ENABLED)
                        Log.d(GcmHelper.TAG, "RegistrationIntentService: unsubscribe completed");
                } else if (ACTION_SUBSCRIBE.equals(action)) {
                    subscribeTopics(pushToken, topics);
                    if (GcmHelper.DEBUG_ENABLED)
                        Log.d(GcmHelper.TAG, "RegistrationIntentService: subscription completed");
                }
            }
        }
    } catch (Exception e) {
        if (GcmHelper.DEBUG_ENABLED)
            Log.e(GcmHelper.TAG, "PushRegistrationService: Failed to complete token refresh", e);
    }
}

From source file:org.planetmono.dcuploader.ActivityUploader.java

@SuppressWarnings("unchecked")
@Override/*from ww w. ja v a  2 s .  c om*/
public void onCreate(Bundle savedState) {
    super.onCreate(savedState);

    initViews();
    if (formLocation)
        queryLocation(true);

    if (savedState != null) {
        if (savedState.containsKey("tempfile"))
            tempFile = new File(savedState.getString("tempfile"));
        if (savedState.containsKey("target"))
            resolveTarget(savedState.getString("target"));
        if (savedState.containsKey("tempfiles"))
            tempFiles = savedState.getStringArrayList("tempfiles");
        if (savedState.containsKey("contents")) {
            contents = new ArrayList<Uri>();
            String[] carr = savedState.getStringArray("contents");
            for (String s : carr)
                contents.add(Uri.parse(s));
        }
    }

    postfix = "from <a href=\"http://palladium.planetmono.org/dcuploader\">DCUploader</a>";

    Button uploadVisit = (Button) findViewById(R.id.upload_visit);
    if (passThrough || target == null)
        uploadVisit.setEnabled(false);
    else
        uploadVisit.setEnabled(true);

    /* populate data by getting STREAM parameter */
    Intent i = getIntent();
    Bundle b = i.getExtras();
    String action = i.getAction();

    if (action.equals(Intent.ACTION_SEND) || action.equals(Intent.ACTION_SEND_MULTIPLE)) {
        called = true;

        if (i.hasExtra(Intent.EXTRA_STREAM)) {
            Object o = b.get(Intent.EXTRA_STREAM);

            /* quick and dirty. any better idea? */
            try {
                contents.add((Uri) o);
            } catch (Exception e1) {
                try {
                    contents = (ArrayList<Uri>) ((ArrayList<Uri>) o).clone();
                } catch (Exception e2) {
                }
            }

            boolean exceeded = false;
            if (contents.size() > 5) {
                exceeded = true;

                do {
                    contents.remove(5);
                } while (contents.size() > 5);
            }

            galleryChanged = true;

            updateImageButtons();
            resetThumbnails();
            updateGallery();

            if (exceeded)
                Toast.makeText(this,
                        " 5  . 5 ??? ? ?.",
                        Toast.LENGTH_LONG).show();
        }
        if (i.hasExtra(Intent.EXTRA_TEXT)) {
            ((EditText) findViewById(R.id.upload_text)).setText(b.getString(Intent.EXTRA_TEXT));
        }
    } else if (action.equals("share")) {
        called = true;
        /* HTC web browser uses non-standard intent */

        ((EditText) findViewById(R.id.upload_text)).setText(b.getString(Intent.EXTRA_TITLE));
    } else if (action.equals(Intent.ACTION_VIEW)) {
        Uri uri = i.getData();

        if (i.getCategories().contains(Intent.CATEGORY_BROWSABLE)) {
            passThrough = true;

            Pattern p = Pattern.compile("id=([\\-a-zA-Z0-9_]+)");
            Matcher m = p.matcher(uri.toString());

            if (m.find()) {
                resolveTarget(m.group(1));
            } else {
                passThrough = false;
            }

            if (uri.getHost().equals(Application.HOST_DCMYS)) {
                destination = Application.DESTINATION_DCMYS;
                postfix = "from dc.m.dcmys.kr w/ <a href=\"http://palladium.planetmono.org/dcuploader\">DCUploader</a>";
            } else if (uri.getHost().equals(Application.HOST_MOOLZO)) {
                destination = Application.DESTINATION_MOOLZO;
                postfix = "- From m.oolzo.com w/ <a href=\"http://palladium.planetmono.org/dcuploader\">DCUploader</a>";
            } else if (uri.getHost().equals(Application.HOST_DCINSIDE)) {
                destination = Application.DESTINATION_DCINSIDE;
            }

            setDefaultImage();
        }
    }

    reloadConfigurations();
}