Example usage for android.content Intent getStringExtra

List of usage examples for android.content Intent getStringExtra

Introduction

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

Prototype

public String getStringExtra(String name) 

Source Link

Document

Retrieve extended data from the intent.

Usage

From source file:com.ubikod.capptain.android.sdk.track.CapptainTrackReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    /* Once the application identifier is known */
    if ("com.ubikod.capptain.intent.action.APPID_GOT".equals(intent.getAction())) {
        /* Init the tracking agent */
        String appId = intent.getStringExtra("appId");
        CapptainTrackAgent.getInstance(context).onAppIdGot(appId);
    }/*from w  w w .j av  a2  s .co  m*/

    /* During installation, an install referrer may be triggered */
    else if ("com.android.vending.INSTALL_REFERRER".equals(intent.getAction())) {
        /* Forward this action to configured receivers */
        String forwardList = CapptainUtils.getMetaData(context)
                .getString("capptain:track:installReferrerForwardList");
        if (forwardList != null)
            for (String component : forwardList.split(","))
                if (!component.equals(getClass().getName())) {
                    Intent clonedIntent = new Intent(intent);
                    clonedIntent.setComponent(new ComponentName(context, component));
                    context.sendBroadcast(clonedIntent);
                }

        /* Guess store from referrer */
        String referrer = Uri.decode(intent.getStringExtra("referrer"));
        String store;

        /* GetJar uses an opaque string always starting with z= */
        if (referrer.startsWith("z="))
            store = "GetJar";

        /* Assume Android Market otherwise */
        else
            store = "Android Market";

        /* Look for a source parameter */
        Uri uri = Uri.parse("a://a?" + referrer);
        String source = uri.getQueryParameter("utm_source");

        /*
         * Skip "androidmarket" source, this is the default one when not set or installed via web
         * Android Market.
         */
        if ("androidmarket".equals(source))
            source = null;

        /* Send app info to register store/source */
        Bundle appInfo = new Bundle();
        appInfo.putString("store", store);
        if (source != null) {
            /* Parse source, if coming from capptain, it may be a JSON complex object */
            try {
                /* Convert JSON to bundle (just flat strings) */
                JSONObject jsonInfo = new JSONObject(source);
                Iterator<?> keyIt = jsonInfo.keys();
                while (keyIt.hasNext()) {
                    String key = keyIt.next().toString();
                    appInfo.putString(key, jsonInfo.getString(key));
                }
            } catch (JSONException jsone) {
                /* Not an object, process as a string */
                appInfo.putString("source", source);
            }
        }

        /* Send app info */
        CapptainAgent.getInstance(context).sendAppInfo(appInfo);
    }
}

From source file:com.parse.ParsePushBroadcastReceiver.java

private JSONObject getPushData(Intent intent) {
    try {/*from www .  j  a va2  s  .c  o m*/
        return new JSONObject(intent.getStringExtra(KEY_PUSH_DATA));
    } catch (JSONException e) {
        PLog.e(TAG, "Unexpected JSONException when receiving push data: ", e);
        return null;
    }
}

From source file:org.cvasilak.jboss.mobile.app.service.UploadToJBossServerService.java

@Override
protected void onHandleIntent(Intent intent) {
    // initialize

    // extract details
    Server server = intent.getParcelableExtra("server");
    String directory = intent.getStringExtra("directory");
    String filename = intent.getStringExtra("filename");

    // get the json parser from the application
    JsonParser jsonParser = new JsonParser();

    // start the ball rolling...
    final NotificationManager mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    builder.setTicker(String.format(getString(R.string.notif_ticker), filename))
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_notif_large))
            .setSmallIcon(R.drawable.ic_stat_notif_small)
            .setContentTitle(String.format(getString(R.string.notif_title), filename))
            .setContentText(getString(R.string.notif_content_init))
            // to avoid NPE on android 2.x where content intent is required
            // set an empty content intent
            .setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0)).setOngoing(true);

    // notify user that upload is starting
    mgr.notify(NOTIFICATION_ID, builder.build());

    // reset ticker for any subsequent notifications
    builder.setTicker(null);/* w  w  w.j av  a2s.  c  o  m*/

    AbstractHttpClient client = CustomHTTPClient.getHttpClient();

    // enable digest authentication
    if (server.getUsername() != null && !server.getUsername().equals("")) {
        Credentials credentials = new UsernamePasswordCredentials(server.getUsername(), server.getPassword());

        client.getCredentialsProvider().setCredentials(
                new AuthScope(server.getHostname(), server.getPort(), AuthScope.ANY_REALM), credentials);
    }

    final File file = new File(directory, filename);
    final long length = file.length();

    try {
        CustomMultiPartEntity multipart = new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
                new CustomMultiPartEntity.ProgressListener() {
                    @Override
                    public void transferred(long num) {
                        // calculate percentage

                        //System.out.println("transferred: " + num);

                        int progress = (int) ((num * 100) / length);

                        builder.setContentText(String.format(getString(R.string.notif_content), progress));

                        mgr.notify(NOTIFICATION_ID, builder.build());
                    }
                });

        multipart.addPart(file.getName(), new FileBody(file));

        HttpPost httpRequest = new HttpPost(server.getHostPort() + "/management/add-content");
        httpRequest.setEntity(multipart);

        HttpResponse serverResponse = client.execute(httpRequest);

        BasicResponseHandler handler = new BasicResponseHandler();
        JsonObject reply = jsonParser.parse(handler.handleResponse(serverResponse)).getAsJsonObject();

        if (!reply.has("outcome")) {
            throw new RuntimeException(getString(R.string.invalid_response));
        } else {
            // remove the 'upload in-progress' notification
            mgr.cancel(NOTIFICATION_ID);

            String outcome = reply.get("outcome").getAsString();

            if (outcome.equals("success")) {

                String BYTES_VALUE = reply.get("result").getAsJsonObject().get("BYTES_VALUE").getAsString();

                Intent resultIntent = new Intent(this, UploadCompletedActivity.class);
                // populate it
                resultIntent.putExtra("server", server);
                resultIntent.putExtra("BYTES_VALUE", BYTES_VALUE);
                resultIntent.putExtra("filename", filename);
                resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

                // the notification id for the 'completed upload' notification
                // each completed upload will have a different id
                int notifCompletedID = (int) System.currentTimeMillis();

                builder.setContentTitle(getString(R.string.notif_title_uploaded))
                        .setContentText(String.format(getString(R.string.notif_content_uploaded), filename))
                        .setContentIntent(
                                // we set the (2nd param request code to completedID)
                                // see http://tinyurl.com/kkcedju
                                PendingIntent.getActivity(this, notifCompletedID, resultIntent,
                                        PendingIntent.FLAG_UPDATE_CURRENT))
                        .setAutoCancel(true).setOngoing(false);

                mgr.notify(notifCompletedID, builder.build());

            } else {
                JsonElement elem = reply.get("failure-description");

                if (elem.isJsonPrimitive()) {
                    throw new RuntimeException(elem.getAsString());
                } else if (elem.isJsonObject())
                    throw new RuntimeException(
                            elem.getAsJsonObject().get("domain-failure-description").getAsString());
            }
        }

    } catch (Exception e) {
        builder.setContentText(e.getMessage()).setAutoCancel(true).setOngoing(false);

        mgr.notify(NOTIFICATION_ID, builder.build());
    }
}

From source file:me.willowcheng.makerthings.core.OpenHABVoiceService.java

@Override
protected void onHandleIntent(Intent intent) {
    Log.d(TAG, "onHandleIntent()");
    bufferIntent(intent);/*  w w  w.j  a v a2s.c  om*/
    if (intent.hasExtra(OPENHAB_BASE_URL_EXTRA)) {
        Log.d(TAG, "openHABBaseUrl passed as Intent");
        onOpenHABTracked(intent.getStringExtra(OPENHAB_BASE_URL_EXTRA), null);
    } else if (mOpenHABTracker == null) {
        Log.d(TAG, "No openHABBaseUrl passed, starting OpenHABTracker");
        mOpenHABTracker = new OpenHABTracker(OpenHABVoiceService.this, getString(R.string.openhab_service_type),
                false);
        mOpenHABTracker.start();
    }
}

From source file:com.google.samples.apps.iosched.service.FeedbackListenerService.java

public int onStartCommand(Intent intent, int flags, int startId) {
    if (null != intent) {
        String action = intent.getAction();
        if (SessionAlarmService.ACTION_NOTIFICATION_DISMISSAL.equals(action)) {
            String sessionId = intent.getStringExtra(SessionAlarmService.KEY_SESSION_ID);
            LOGD(TAG, "onStartCommand(): Action = ACTION_NOTIFICATION_DISMISSAL Session: " + sessionId);
            dismissWearableNotification(sessionId);
        }//from www.  j av a  2s.co  m
    }
    return Service.START_NOT_STICKY;
}

From source file:io.v.syncslides.DeckChooserFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case REQUEST_CODE_IMPORT_DECK:
        if (resultCode != Activity.RESULT_OK) {
            String errorStr = data != null && data.hasExtra(DocumentsContract.EXTRA_ERROR)
                    ? data.getStringExtra(DocumentsContract.EXTRA_ERROR)
                    : "";
            toast("Error selecting deck to import " + errorStr);
            break;
        }/*from ww w  .ja v  a2s .c  om*/
        Uri uri = data.getData();
        DeckImporter importer = new DeckImporter(getActivity().getContentResolver(), DB.Singleton.get());
        ListenableFuture<Void> future = importer.importDeck(DocumentFile.fromTreeUri(getContext(), uri));
        Futures.addCallback(future, new FutureCallback<Void>() {
            @Override
            public void onSuccess(Void result) {
                toast("Import complete");
            }

            @Override
            public void onFailure(Throwable t) {
                toast("Import failed: " + t.getMessage());
            }
        });
        break;
    }
}

From source file:org.klnusbaum.udj.auth.AuthActivity.java

/**
 * {@inheritDoc}/*from  w  w  w.j  ava  2  s.  c o  m*/
 */
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    mAccountManager = AccountManager.get(this);
    final Intent intent = getIntent();
    mUsername = intent.getStringExtra(PARAM_USERNAME);
    mRequestNewAccount = mUsername == null;
    mConfirmCredentials = intent.getBooleanExtra(PARAM_CONFIRM_CREDENTIALS, false);
    Log.i(TAG, "    request new: " + mRequestNewAccount);
    requestWindowFeature(Window.FEATURE_LEFT_ICON);
    setContentView(R.layout.login_activity);
    getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, android.R.drawable.ic_dialog_alert);
    mMessage = (TextView) findViewById(R.id.message);
    mUsernameEdit = (EditText) findViewById(R.id.username_edit);
    mPasswordEdit = (EditText) findViewById(R.id.password_edit);
    if (!TextUtils.isEmpty(mUsername))
        mUsernameEdit.setText(mUsername);
    mMessage.setText(getMessage());

    TextView signUp = (TextView) findViewById(R.id.signup_text);
    signUp.setText(Html.fromHtml(getString(R.string.dont_have_account)));
    signUp.setMovementMethod(LinkMovementMethod.getInstance());
}

From source file:com.gtdbrowser.data.service.GtdService.java

@Override
protected void onHandleIntent(final Intent intent) {
    final int workerType = intent.getIntExtra(INTENT_EXTRA_WORKER_TYPE, -1);
    String uri;/*from   w  w w  .j a va 2s  .com*/
    Bundle resultBundle;

    try {
        switch (workerType) {
        case WORKER_TYPE_FILTERED_LIST:
            uri = intent.getStringExtra(INTENT_EXTRA_URI);
            resultBundle = FilteredListWorker.start(this, uri);
            sendSuccess(intent, resultBundle);
            break;
        case WORKER_TYPE_ATTACK_LIST:
            uri = intent.getStringExtra(INTENT_EXTRA_URI);
            resultBundle = AttackListWorker.start(this, uri);

            // Update the web service URI if there are more pages, otherwise
            // call it the end of pagination on this filter type.
            String ws_uri;
            if (resultBundle.getString("nextURI") != null)
                ws_uri = resultBundle.getString("nextURI");
            else
                ws_uri = END_PAGINATION;
            int total_count = resultBundle.getInt("total_count");

            SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString("attacks" + "_uri", ws_uri);
            editor.putInt("total_count", total_count);
            editor.commit();

            sendSuccess(intent, resultBundle);
            break;
        }
    } catch (final IllegalStateException e) {
        Log.e(LOG_TAG, "IllegalStateException", e);
        sendConnexionFailure(intent, null);
    } catch (final IOException e) {
        Log.e(LOG_TAG, "IOException", e);
        sendConnexionFailure(intent, null);
    } catch (final URISyntaxException e) {
        Log.e(LOG_TAG, "URISyntaxException", e);
        sendConnexionFailure(intent, null);
    } catch (final RestClientException e) {
        Log.e(LOG_TAG, "RestClientException", e);
        sendConnexionFailure(intent, null);
    } catch (final ParserConfigurationException e) {
        Log.e(LOG_TAG, "ParserConfigurationException", e);
        sendDataFailure(intent, null);
    } catch (final SAXException e) {
        Log.e(LOG_TAG, "SAXException", e);
        sendDataFailure(intent, null);
    } catch (final JSONException e) {
        Log.e(LOG_TAG, "JSONException", e);
        sendDataFailure(intent, null);
    }
    // This block (which should be the last one in your implementation)
    // will catch all the RuntimeException and send you back an error
    // that you can manage. If you remove this catch, the
    // RuntimeException will still crash the GtdService but you will not be
    // informed (as it is in 'background') so you should never remove this
    // catch
    catch (final RuntimeException e) {
        Log.e(LOG_TAG, "RuntimeException", e);
        sendDataFailure(intent, null);
    }
}

From source file:edu.poly.cs9033.nowaiting.service.LocationReceiver.java

@Override
public void onReceive(Context context, Intent intent) {

    Logger.i("Location changes detected!");

    Bundle b = intent.getExtras();//from w ww  .ja  v  a2 s .  c om
    Location loc = (Location) b.get(LocationPoller.EXTRA_LOCATION);
    String msg;

    if (loc == null) {
        loc = (Location) b.get(LocationPoller.EXTRA_LASTKNOWN);

        if (loc == null) {
            msg = intent.getStringExtra(LocationPoller.EXTRA_ERROR);
        } else {
            msg = "TIMEOUT, lastKnown=" + loc.toString();
        }
    } else {
        msg = loc.toString();
        uploadCurrentLocation(loc);
    }

    if (msg == null) {
        msg = "Invalid broadcast received!";
    }

}

From source file:com.github.play.app.StatusService.java

@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
    if (intent != null) {
        String intentKey = intent.getStringExtra(EXTRA_KEY);
        if (!TextUtils.isEmpty(intentKey) && !intentKey.equals(applicationKey)) {
            destroyPusher(pusher);/*from   w  ww .ja v a  2s.c  o m*/
            createPusher(intentKey);
        }

        boolean updateNotification = intent.hasExtra(EXTRA_NOTIFY);
        if (updateNotification)
            sendNotification = intent.getBooleanExtra(EXTRA_NOTIFY, false);
        Song song = (Song) intent.getSerializableExtra(EXTRA_SONG);
        if (updateNotification && !sendNotification) {
            clearNotification();
        } else if (song != null)
            updateNotification(song);
    }

    return super.onStartCommand(intent, flags, startId);
}