Example usage for android.content Intent getParcelableExtra

List of usage examples for android.content Intent getParcelableExtra

Introduction

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

Prototype

public <T extends Parcelable> T getParcelableExtra(String name) 

Source Link

Document

Retrieve extended data from the intent.

Usage

From source file:com.marianhello.bgloc.LocationService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    log.info("Received start startId: {} intent: {}", startId, intent);

    if (provider != null) {
        provider.onDestroy();/*from  w  ww  .  ja  v  a2s .c  o  m*/
    }

    if (intent == null) {
        //service has been probably restarted so we need to load config from db
        ConfigurationDAO dao = DAOFactory.createConfigurationDAO(this);
        try {
            config = dao.retrieveConfiguration();
        } catch (JSONException e) {
            log.error("Config exception: {}", e.getMessage());
            config = new Config(); //using default config
        }
    } else {
        if (intent.hasExtra("config")) {
            config = intent.getParcelableExtra("config");
        } else {
            config = new Config(); //using default config
        }
    }

    log.debug("Will start service with: {}", config.toString());

    LocationProviderFactory spf = new LocationProviderFactory(this);
    provider = spf.getInstance(config.getLocationProvider());

    if (config.getStartForeground()) {
        // Build a Notification required for running service in foreground.
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setContentTitle(config.getNotificationTitle());
        builder.setContentText(config.getNotificationText());
        if (config.getSmallNotificationIcon() != null) {
            builder.setSmallIcon(getDrawableResource(config.getSmallNotificationIcon()));
        } else {
            builder.setSmallIcon(android.R.drawable.ic_menu_mylocation);
        }
        if (config.getLargeNotificationIcon() != null) {
            builder.setLargeIcon(BitmapFactory.decodeResource(getApplication().getResources(),
                    getDrawableResource(config.getLargeNotificationIcon())));
        }
        if (config.getNotificationIconColor() != null) {
            builder.setColor(this.parseNotificationIconColor(config.getNotificationIconColor()));
        }

        // Add an onclick handler to the notification
        Context context = getApplicationContext();
        String packageName = context.getPackageName();
        Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
        launchIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, launchIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        builder.setContentIntent(contentIntent);

        Notification notification = builder.build();
        notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE
                | Notification.FLAG_NO_CLEAR;
        startForeground(startId, notification);
    }

    provider.startRecording();

    //We want this service to continue running until it is explicitly stopped
    return START_STICKY;
}

From source file:net.exclaimindustries.geohashdroid.services.WikiService.java

@Override
protected ReturnCode handleIntent(Intent i) {
    // First and foremost, if there's no network connection, just give up
    // now./*from w  w w . ja va 2 s  . com*/
    if (!AndroidUtil.isConnected(this)) {
        showWaitingForConnectionNotification();
        return ReturnCode.PAUSE;
    }

    // Hey, there, Intent.  Got some extras for me?
    Info info = (Info) i.getSerializableExtra(EXTRA_INFO);
    Location loc = (Location) i.getSerializableExtra(EXTRA_LOCATION);
    String message = i.getStringExtra(EXTRA_MESSAGE);
    Calendar timestamp = (Calendar) i.getSerializableExtra(EXTRA_TIMESTAMP);
    Uri imageLocation = (Uri) i.getParcelableExtra(EXTRA_IMAGE);

    // Prep an HttpClient for later...
    HttpClient client = new DefaultHttpClient();

    // To Preferences!
    SharedPreferences prefs = getSharedPreferences(GHDConstants.PREFS_BASE, 0);
    String username = prefs.getString(GHDConstants.PREF_WIKI_USER, "");
    String password = prefs.getString(GHDConstants.PREF_WIKI_PASS, "");

    // If you're missing something vital, bail out.
    if (info == null || message == null || timestamp == null) {
        Log.e(DEBUG_TAG,
                "Intent was missing some vital data (either Info, message, or timestamp), giving up...");
        return ReturnCode.CONTINUE;
    }

    try {
        // If we got a username/password combo, try to log in.
        if (!username.isEmpty() && !password.isEmpty()) {
            WikiUtils.login(client, username, password);
        }

        // Let's say there's an image specified.
        ImageInfo imageInfo;
        if (imageLocation != null) {
            // If so, see if the user's even specified a login.  The wiki does
            // not allow anonymous uploads.

            if (username.equals("")) {
                // Aww.  Failure.
                // TODO: Need a real PendingIntent here!
                showPausingErrorNotification(getText(R.string.wiki_conn_anon_pic_error).toString(), null, null,
                        null);
                return ReturnCode.PAUSE;
            }

            // If that's all set, we can try to look it up on the system.
            imageInfo = readImageInfo(imageLocation, loc);

            // But, if said info remains null, we've got a problem.  The user
            // wanted an image uploaded, but we can't do that, so we have to
            // abandon this intent.  However, I don't think that's a showstopper
            // in terms of continuing the queue.
            if (imageInfo == null) {
                Log.e(DEBUG_TAG,
                        "The user was somehow allowed to choose an image that can't be accessed via MediaStore!");
                showImageErrorNotification();
                return ReturnCode.CONTINUE;
            }

            // Now, the location that we're going to send for the image SHOULD
            // match up with where the user thinks they are, so we'll read what
            // got stuffed into the ImageInfo.  Note that we just gave it the
            // user's current location in the event that MediaStore doesn't have
            // any idea, either, so we're not going to replace good data with a
            // null, if said good data exists.
            loc = imageInfo.location;

            // Make sure the image doesn't already exist.  If it does, we
            // can skip the entire "shrink image, annotate it, and upload
            // it" steps.
            if (!WikiUtils.doesWikiPageExist(client, getImageWikiName(info, imageInfo, username))) {
                // TODO: Create bitmap and upload it.
            }
        }

        return ReturnCode.CONTINUE;
    } catch (WikiException we) {
        // TODO: Handle wiki exceptions.
    } catch (Exception e) {
        // Okay, first off, are we still connected?  An Exception will get
        // thrown if the connection just goes poof while we're trying to do
        // something.
        if (!AndroidUtil.isConnected(this)) {
            // We're not!  Go to disconnected mode and wait.
            showWaitingForConnectionNotification();
            return ReturnCode.PAUSE;
        } else {
            // Otherwise, we're kinda stumped.  Maybe the user will know
            // what to do?
            // TODO: Handle other exceptions.
        }
    }

    // We shouldn't be here.
    return ReturnCode.PAUSE;
}

From source file:edu.mum.ml.group7.guessasketch.android.EasyPaint.java

public void loadFromIntents() {
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();
    System.out.println("Intentoso " + action + " type " + type);
    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if (type.startsWith("image/")) {
            setBackgroundUri((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM));
        }/*from  w w  w.  j av  a  2s. c  o m*/

    }
}

From source file:com.gsma.rcs.ri.messaging.GroupTalkView.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != RESULT_OK) {
        return;//from w  w  w  .  j  a v  a2 s  .c  o m
    }
    switch (requestCode) {
    case SELECT_GEOLOCATION:
        Geoloc geoloc = data.getParcelableExtra(EditGeoloc.EXTRA_GEOLOC);
        try {
            if (mGroupChat != null && geoloc != null) {
                mGroupChat.sendMessage(geoloc);
            }
        } catch (RcsServiceException e) {
            showExceptionThenExit(e);
        }
        break;
    }
}

From source file:edu.mit.media.funf.probe.Probe.java

/**
 * Returns true if request was successfully queued
 * @param request//from   w  ww .j av a2  s .co m
 * @return
 */
private boolean queueRequest(Intent request) {
    // Check for pending intent
    PendingIntent callback = null;
    try {
        callback = request.getParcelableExtra(CALLBACK_KEY);
    } catch (Exception e) {
        Log.e(TAG, "Request sent invalid callback.");
    }

    if (callback == null) {
        Log.e(TAG, "Request did not send callback.");
    } else {
        boolean succesfullyQueued = pendingRequests.offer(request);
        if (succesfullyQueued) {
            Log.i(TAG, "Queued request from package '" + callback.getTargetPackage() + "'");
            return true;
        } else {
            Log.e(TAG, "Unable to queue request from package '" + callback.getTargetPackage() + "'");
        }
    }
    return false;
}

From source file:edu.mit.media.funf.probe.Probe.java

/**
 * Updates request list with items in queue, replacing duplicate pending intents for this probe.
 * @param requests//from  w  w  w  .j a v a2s.c  o m
 */
private void updateRequests(boolean removeRunOnce) {
    assert requestsIntent != null;
    boolean hasChanges = false;
    ArrayList<Intent> requests = requestsIntent.getParcelableArrayListExtra(INTERNAL_REQUESTS_KEY);
    if (requests == null) {
        hasChanges = true;
        requests = new ArrayList<Intent>();
    }

    // Remove run once requests
    Parameter periodParam = Parameter.getAvailableParameter(getAvailableParameters(), Parameter.Builtin.PERIOD);
    if (periodParam != null && removeRunOnce) {
        for (Intent request : requests) {
            ArrayList<Bundle> dataRequests = Utils.getArrayList(request.getExtras(), REQUESTS_KEY);
            List<Bundle> runOnceDataRequests = new ArrayList<Bundle>();
            for (Bundle dataRequest : dataRequests) {
                long periodValue = Utils.getLong(dataRequest, Parameter.Builtin.PERIOD.name,
                        (Long) periodParam.getValue());
                if (periodValue == 0L) {
                    Log.d(TAG, "Removing run once dataRequest: " + dataRequest);
                    runOnceDataRequests.add(dataRequest);
                }
            }
            dataRequests.removeAll(runOnceDataRequests);
            if (dataRequests.isEmpty()) {
                deadRequests.add(request);
            } else {
                request.putExtra(REQUESTS_KEY, dataRequests);
            }
        }
    }

    // Remove all requests that we aren't able to (or supposed to) send to anymore
    if (!deadRequests.isEmpty()) {
        hasChanges = true;
        for (Intent deadRequest = deadRequests.poll(); deadRequest != null; deadRequest = deadRequests.poll()) {
            Log.d(TAG, "Removing dead request: " + deadRequest);
            requests.remove(deadRequest);
        }
    }
    // Add any pending requests
    if (!pendingRequests.isEmpty()) {
        hasChanges = true;
        Map<PendingIntent, Intent> existingCallbacksToRequests = new HashMap<PendingIntent, Intent>();
        for (Intent existingRequest : requests) {
            PendingIntent callback = existingRequest.getParcelableExtra(CALLBACK_KEY);
            existingCallbacksToRequests.put(callback, existingRequest);
        }
        for (Intent request = pendingRequests.poll(); request != null; request = pendingRequests.poll()) {
            PendingIntent callback = request.getParcelableExtra(CALLBACK_KEY);
            if (packageHasRequiredPermissions(this, callback.getTargetPackage(), getRequiredPermissions())) {
                existingCallbacksToRequests.containsKey(callback);
                int existingRequestIndex = requests.indexOf(existingCallbacksToRequests.get(callback));
                ArrayList<Bundle> dataRequests = Utils.getArrayList(request.getExtras(), REQUESTS_KEY);
                Log.d(TAG, "Adding pending intent with data requests: " + dataRequests);
                if (existingRequestIndex >= 0) {
                    if (dataRequests == null || dataRequests.isEmpty()) {
                        Log.d(TAG, "Adding pending intent, removing because empty or null");
                        requests.remove(existingRequestIndex);
                    } else {
                        requests.set(existingRequestIndex, request);
                    }
                } else {
                    if (dataRequests != null && !dataRequests.isEmpty()) { // Only add requests with nonempty data requests
                        Log.d(TAG, "Adding new pending intent: " + request);
                        requests.add(request);
                    }
                }
            } else {
                Log.w(TAG, "Package '" + callback.getTargetPackage()
                        + "' does not have the required permissions to get data from this probe.");
            }
        }
    }

    if (hasChanges) {
        requestsIntent.putExtra(INTERNAL_REQUESTS_KEY, requests);
        updateInternalRequestsPendingIntent();
    }
}

From source file:edu.mit.media.funf.probe.Probe.java

/**
 * Send some values to each requesting pending intent
 * @param valuesIntent/*from   ww w .  j  a  v a 2s . c o  m*/
 */
protected void _callback_registered(Intent valuesIntent, PendingIntent callback) {
    long epochTimestamp = valuesIntent.getLongExtra(TIMESTAMP, 0L);
    Set<PendingIntent> callbacks = new HashSet<PendingIntent>();
    if (callback != null) {
        callbacks.add(callback);
    }
    ArrayList<Intent> requests = null;
    if (requestsIntent != null) {
        requests = requestsIntent.getParcelableArrayListExtra(INTERNAL_REQUESTS_KEY);
    }

    if (ACTION_DATA.equals(valuesIntent.getAction())) {
        // Send to all requesters
        if (requests != null && !requests.isEmpty()) {
            JSONObject dataSentTimes = null;
            try {
                dataSentTimes = new JSONObject(
                        getHistoryPrefs().getString(MOST_RECENT_DATA_BY_REQUEST_KEY, "{}"));
            } catch (JSONException e) {
                Log.e(TAG, "Unable to parse data sent history.");
                dataSentTimes = new JSONObject();
            }

            Parameter[] availableParameters = getAvailableParameters();
            for (Intent request : requests) {
                PendingIntent requesterCallback = request.getParcelableExtra(CALLBACK_KEY);
                ArrayList<Bundle> dataRequests = Utils.getArrayList(request.getExtras(), REQUESTS_KEY);

                for (Bundle dataRequest : dataRequests) {
                    String requestKey = normalizedStringRepresentation(dataRequest, getAvailableParameters());
                    long lastDataSentTime = dataSentTimes.optLong(requestKey);
                    // TODO: If data request accepts passive data, but also needs data enforced on a schedule
                    // we may need to make logic more complicated
                    if (isDataRequestSatisfied(dataRequest, availableParameters, epochTimestamp,
                            lastDataSentTime)
                            || isDataRequestAcceptingPassiveData(dataRequest, availableParameters)) {
                        callbacks.add(requesterCallback);
                        try {
                            dataSentTimes.put(requestKey, epochTimestamp);
                        } catch (JSONException e) {
                            Log.e(TAG, "Unable to store data sent time in .");
                        }
                    }
                }
            }

            // Save the data sent times
            getHistoryPrefs().edit().putString(MOST_RECENT_DATA_BY_REQUEST_KEY, dataSentTimes.toString())
                    .putLong(MOST_RECENT_DATA_KEY, epochTimestamp).commit();
        }

    } else {
        // Add all
        for (Intent request : requests) {
            PendingIntent requesterCallback = request.getParcelableExtra(CALLBACK_KEY);
            callbacks.add(requesterCallback);
        }
    }

    Log.d(TAG, "Sent probe data at " + epochTimestamp);
    for (PendingIntent requesterCallback : callbacks) {
        try {
            requesterCallback.send(this, 0, valuesIntent);
        } catch (CanceledException e) {
            Log.w(TAG, "Unable to send to canceled pending intent at " + epochTimestamp);
            Map<PendingIntent, Intent> callbacksToRequests = getCallbacksToRequests(requests);
            Intent request = callbacksToRequests.get(requesterCallback);
            if (request != null) {
                deadRequests.add(request);
            }
        }
    }

    updateRequests();
}

From source file:com.piusvelte.sonet.core.SonetCreatePost.java

@Override
protected void onResume() {
    super.onResume();
    Intent intent = getIntent();
    if (intent != null) {
        String action = intent.getAction();
        if ((action != null) && action.equals(Intent.ACTION_SEND)) {
            if (intent.hasExtra(Intent.EXTRA_STREAM))
                getPhoto((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM));
            if (intent.hasExtra(Intent.EXTRA_TEXT)) {
                final String text = intent.getStringExtra(Intent.EXTRA_TEXT);
                mMessage.setText(text);//from w ww . j  a va  2  s  . co m
                mCount.setText(Integer.toString(text.length()));
            }
            chooseAccounts();
        } else {
            Uri data = intent.getData();
            if ((data != null) && data.toString().contains(Accounts.getContentUri(this).toString())) {
                // default to the account passed in, but allow selecting additional accounts
                Cursor account = this.getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID, Accounts.SERVICE }, Accounts._ID + "=?",
                        new String[] { data.getLastPathSegment() }, null);
                if (account.moveToFirst())
                    mAccountsService.put(account.getLong(0), account.getInt(1));
                account.close();
            } else if (intent.hasExtra(Widgets.INSTANT_UPLOAD)) {
                // check if a photo path was passed and prompt user to select the account
                setPhoto(intent.getStringExtra(Widgets.INSTANT_UPLOAD));
                chooseAccounts();
            }
        }
    }
}

From source file:com.ruesga.rview.MainActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_WIZARD) {
        if (resultCode == RESULT_OK) {
            // Save the account
            Account newAccount = data.getParcelableExtra(SetupAccountActivity.EXTRA_ACCOUNT);
            boolean accountExists = false;
            for (Account account : mAccounts) {
                // Current account
                if (account.isSameAs(newAccount)) {
                    accountExists = true;
                    break;
                }//from   w  ww.  j a  v  a2 s  .  c  om
            }

            if (!accountExists) {
                mAccount = newAccount;
                mAccounts = Preferences.addOrUpdateAccount(this, mAccount);
                Preferences.setAccount(this, mAccount);
                Formatter.refreshCachedPreferences(this);
                CacheHelper.createAccountCacheDir(this, mAccount);
                setupAccountUrlHandlingStatus(mAccount, true);
                NotificationsHelper.createNotificationChannel(this, mAccount);
            } else {
                showWarning(R.string.account_exists);
            }

            // Switch to the new account
            performAccountSwitch();
        } else {
            // If we don't have account, then close the activity.
            // Otherwise, do nothing
            if (Preferences.getAccount(this) == null) {
                finish();
            }
        }
    } else if (requestCode == REQUEST_ACCOUNT_SETTINGS) {
        // Refresh current view
        mAccount = Preferences.getAccount(this);
        if (mModel.currentNavigationItemId == INVALID_ITEM) {
            mModel.currentNavigationItemId = Preferences.getAccountHomePageId(this, mAccount);
        }
        Formatter.refreshCachedPreferences(this);
        performNavigateTo();
    }
}

From source file:org.exoplatform.shareextension.ShareActivity.java

@Override
protected void onCreate(Bundle bundle) {
    super.onCreate(bundle);

    setContentView(R.layout.share_extension_activity);

    loadingIndicator = (ProgressBar) findViewById(R.id.share_progress_indicator);
    mainButton = (Button) findViewById(R.id.share_button);
    mainButton.setTag(R.attr.share_button_type_post);
    online = false;//w ww. ja v a2 s  .  c om
    postInfo = new SocialPostInfo();

    if (isIntentCorrect()) {
        Intent intent = getIntent();
        String type = intent.getType();
        if ("text/plain".equals(type)) {
            // The share does not contain an attachment
            // TODO extract the link info - MOB-1866
            postInfo.postMessage = intent.getStringExtra(Intent.EXTRA_TEXT);
        } else {
            // The share contains an attachment
            if (mMultiFlag) {
                mAttachmentUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
            } else {
                Uri contentUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
                if (contentUri != null) {
                    mAttachmentUris = new ArrayList<Uri>();
                    mAttachmentUris.add(contentUri);
                }
                if (Log.LOGD) {
                    Log.d(LOG_TAG, "Number of files to share: ", mAttachmentUris.size());
                }
            }
            prepareAttachmentsAsync();
        }

        init();

        // Create and display the composer, aka ComposeFragment
        ComposeFragment composer = ComposeFragment.getFragment();
        openFragment(composer, ComposeFragment.COMPOSE_FRAGMENT, Anim.NO_ANIM);
    } else {
        // We're not supposed to reach this activity by anything else than an
        // ACTION_SEND intent
        finish();
    }

}