Example usage for android.content Intent setComponent

List of usage examples for android.content Intent setComponent

Introduction

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

Prototype

public @NonNull Intent setComponent(@Nullable ComponentName component) 

Source Link

Document

(Usually optional) Explicitly set the component to handle the intent.

Usage

From source file:id.zelory.codepolitan.ui.ReadActivity.java

private void onShareArticle(String packageName) {
    Article article = articles.get(position);

    if ("more".equals(packageName)) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, Html.fromHtml(article.getTitle()));
        intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(article.getTitle()) + "\n" + article.getLink());
        startActivity(Intent.createChooser(intent, "Share"));
    } else if ("email".equals(packageName)) {
        Intent intent = new Intent(Intent.ACTION_SENDTO);
        intent.setData(Uri.parse("mailto:"));
        intent.putExtra(Intent.EXTRA_SUBJECT, Html.fromHtml(article.getTitle()));
        intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(article.getTitle()) + "\n" + article.getLink());
        startActivity(intent);/*  ww  w. j a va2s  .c om*/
    } else if ("sms".equals(packageName)) {
        Intent intent = new Intent(Intent.ACTION_SENDTO);
        intent.setData(Uri.parse("smsto:"));
        intent.putExtra(Intent.EXTRA_SUBJECT, Html.fromHtml(article.getTitle()));
        intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(article.getTitle()) + "\n" + article.getLink());
        startActivity(intent);
    } else {
        boolean shared = false;
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, Html.fromHtml(article.getTitle()));
        intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(article.getTitle()) + "\n" + article.getLink());

        for (ResolveInfo resolveInfo : getPackageManager().queryIntentActivities(intent, 0)) {
            if (packageName.equals(resolveInfo.activityInfo.packageName)) {
                intent.addCategory(Intent.CATEGORY_LAUNCHER);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.setComponent(new ComponentName(packageName, resolveInfo.activityInfo.name));
                startActivity(intent);
                shared = true;
                break;
            }
        }

        if (!shared) {
            openPlayStore(packageName);
        }
    }
}

From source file:com.aimfire.gallery.GalleryActivity.java

/**
 * share only to certain apps. code based on "http://stackoverflow.com/questions/
 * 9730243/how-to-filter-specific-apps-for-action-send-intent-and-set-a-different-
 * text-for/18980872#18980872"//from  w  w w.j a  va 2  s .  co  m
 * 
 * "copy link" inspired by http://cketti.de/2016/06/15/share-url-to-clipboard/
 * 
 * in general, "deep linking" is supported by the apps below. Facebook, Wechat,
 * Telegram are exceptions. click on the link would bring users to the landing
 * page. 
 * 
 * Facebook doesn't take our EXTRA_TEXT so user will have to "copy link" first 
 * then paste the link
 */
private void shareMedia(Intent data) {
    /*
     * we log this as "share complete", but user can still cancel the share at this point,
     * and we wouldn't be able to know
     */
    mFirebaseAnalytics.logEvent(MainConsts.FIREBASE_CUSTOM_EVENT_SHARE_COMPLETE, null);

    Resources resources = getResources();

    /*
     * get the resource id for the shared file
     */
    String id = data.getStringExtra(MainConsts.EXTRA_ID_RESOURCE);

    /*
     * construct link
     */
    String link = "https://" + resources.getString(R.string.app_domain) + "/?id=" + id + "&name="
            + ((mPreviewName != null) ? mPreviewName : mMediaName);

    /*
     * message subject and text
     */
    String emailSubject, emailText, twitterText;

    if (MediaScanner.isPhoto(mMediaPath)) {
        emailSubject = resources.getString(R.string.emailSubjectPhoto);
        emailText = resources.getString(R.string.emailBodyPhotoPrefix) + link;
        twitterText = resources.getString(R.string.emailBodyPhotoPrefix) + link
                + resources.getString(R.string.twitterHashtagPhoto) + resources.getString(R.string.app_hashtag);
    } else if (MediaScanner.is3dMovie(mMediaPath)) {
        emailSubject = resources.getString(R.string.emailSubjectVideo);
        emailText = resources.getString(R.string.emailBodyVideoPrefix) + link;
        twitterText = resources.getString(R.string.emailBodyVideoPrefix) + link
                + resources.getString(R.string.twitterHashtagVideo) + resources.getString(R.string.app_hashtag);
    } else //if(MediaScanner.is2dMovie(mMediaPath))
    {
        emailSubject = resources.getString(R.string.emailSubjectVideo2d);
        emailText = resources.getString(R.string.emailBodyVideoPrefix2d) + link;
        twitterText = resources.getString(R.string.emailBodyVideoPrefix2d) + link
                + resources.getString(R.string.twitterHashtagVideo) + resources.getString(R.string.app_hashtag);
    }

    Intent emailIntent = new Intent();
    emailIntent.setAction(Intent.ACTION_SEND);
    // Native email client doesn't currently support HTML, but it doesn't hurt to try in case they fix it
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, emailSubject);
    emailIntent.putExtra(Intent.EXTRA_TEXT, emailText);
    //emailIntent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(resources.getString(R.string.share_email_native)));
    emailIntent.setType("message/rfc822");

    PackageManager pm = getPackageManager();
    Intent sendIntent = new Intent(Intent.ACTION_SEND);
    sendIntent.setType("text/plain");

    Intent openInChooser = Intent.createChooser(emailIntent, resources.getString(R.string.share_chooser_text));

    List<ResolveInfo> resInfo = pm.queryIntentActivities(sendIntent, 0);
    List<LabeledIntent> intentList = new ArrayList<LabeledIntent>();
    for (int i = 0; i < resInfo.size(); i++) {
        // Extract the label, append it, and repackage it in a LabeledIntent
        ResolveInfo ri = resInfo.get(i);
        String packageName = ri.activityInfo.packageName;
        if (packageName.contains("android.email")) {
            emailIntent.setPackage(packageName);
        } else if (packageName.contains("twitter") || packageName.contains("facebook")
                || packageName.contains("whatsapp") || packageName.contains("tencent.mm") || //wechat
                packageName.contains("line") || packageName.contains("skype") || packageName.contains("viber")
                || packageName.contains("kik") || packageName.contains("sgiggle") || //tango
                packageName.contains("kakao") || packageName.contains("telegram")
                || packageName.contains("nimbuzz") || packageName.contains("hike")
                || packageName.contains("imoim") || packageName.contains("bbm")
                || packageName.contains("threema") || packageName.contains("mms")
                || packageName.contains("android.apps.messaging") || //google messenger
                packageName.contains("android.talk") || //google hangouts
                packageName.contains("android.gm")) {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName(packageName, ri.activityInfo.name));
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("text/plain");
            if (packageName.contains("twitter")) {
                intent.putExtra(Intent.EXTRA_TEXT, twitterText);
            } else if (packageName.contains("facebook")) {
                /*
                 * the warning below is wrong! at least on GS5, Facebook client does take
                 * our text, however it seems it takes only the first hyperlink in the
                 * text.
                 * 
                 * Warning: Facebook IGNORES our text. They say "These fields are intended 
                 * for users to express themselves. Pre-filling these fields erodes the 
                 * authenticity of the user voice."
                 * One workaround is to use the Facebook SDK to post, but that doesn't 
                 * allow the user to choose how they want to share. We can also make a 
                 * custom landing page, and the link will show the <meta content ="..."> 
                 * text from that page with our link in Facebook.
                 */
                intent.putExtra(Intent.EXTRA_TEXT, link);
            } else if (packageName.contains("tencent.mm")) //wechat
            {
                /*
                 * wechat appears to do this similar to Facebook
                 */
                intent.putExtra(Intent.EXTRA_TEXT, link);
            } else if (packageName.contains("android.gm")) {
                // If Gmail shows up twice, try removing this else-if clause and the reference to "android.gm" above
                intent.putExtra(Intent.EXTRA_SUBJECT, emailSubject);
                intent.putExtra(Intent.EXTRA_TEXT, emailText);
                //intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(resources.getString(R.string.share_email_gmail)));
                intent.setType("message/rfc822");
            } else if (packageName.contains("android.apps.docs")) {
                /*
                 * google drive - no reason to send link to it
                 */
                continue;
            } else {
                intent.putExtra(Intent.EXTRA_TEXT, emailText);
            }

            intentList.add(new LabeledIntent(intent, packageName, ri.loadLabel(pm), ri.icon));
        }
    }

    /*
     *  create "Copy Link To Clipboard" Intent
     */
    Intent clipboardIntent = new Intent(this, CopyToClipboardActivity.class);
    clipboardIntent.setData(Uri.parse(link));
    intentList.add(new LabeledIntent(clipboardIntent, getPackageName(),
            getResources().getString(R.string.clipboard_activity_name), R.drawable.ic_copy_link));

    // convert intentList to array
    LabeledIntent[] extraIntents = intentList.toArray(new LabeledIntent[intentList.size()]);

    openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
    startActivity(openInChooser);
}

From source file:air.com.snagfilms.cast.chromecast.VideoChromeCastManager.java

@SuppressLint("InlinedApi")
private void setUpRemoteControl(final MediaInfo info) {
    if (!isFeatureEnabled(BaseChromeCastManager.FEATURE_LOCKSCREEN)) {
        return;/* ww w. ja v a2  s.c  om*/
    }
    Log.d(TAG, "setupRemoteControl() was called");
    mAudioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);

    ComponentName eventReceiver = new ComponentName(mContext, VideoIntentReceiver.class.getName());
    mAudioManager.registerMediaButtonEventReceiver(eventReceiver);

    if (mRemoteControlClientCompat == null) {
        Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        intent.setComponent(mMediaButtonReceiverComponent);
        mRemoteControlClientCompat = new RemoteControlClientCompat(
                PendingIntent.getBroadcast(mContext, 0, intent, 0));
        RemoteControlHelper.registerRemoteControlClient(mAudioManager, mRemoteControlClientCompat);
    }
    mRemoteControlClientCompat.addToMediaRouter(mMediaRouter);
    mRemoteControlClientCompat.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE);
    if (null == info) {
        mRemoteControlClientCompat.setPlaybackState(RemoteControlClient.PLAYSTATE_PAUSED);
        return;
    } else {
        mRemoteControlClientCompat.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING);
    }

    // Update the remote control's image
    updateLockScreenImage(info);

    // update the remote control's metadata
    updateLockScreenMetadata();
}

From source file:com.android.leanlauncher.LauncherModel.java

/**
 * Make an ShortcutInfo object for a shortcut that is an application.
 *///from w ww.  j a  v  a 2s.co  m
public ShortcutInfo getShortcutInfo(Intent intent, UserHandleCompat user, int titleIndex,
        Map<Object, CharSequence> labelCache, boolean allowMissingTarget) {
    if (user == null) {
        Log.d(TAG, "Null user found in getShortcutInfo");
        return null;
    }

    ComponentName componentName = intent.getComponent();
    if (componentName == null) {
        Log.d(TAG, "Missing component found in getShortcutInfo");
        return null;
    }

    Intent newIntent = new Intent(intent.getAction(), null);
    newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    newIntent.setComponent(componentName);
    LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
    if ((lai == null) && !allowMissingTarget) {
        Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
        return null;
    }

    final ShortcutInfo info = new ShortcutInfo();

    // From the cache.
    if (labelCache != null) {
        info.title = labelCache.get(componentName);
    }

    // from the resource
    if (info.title == null && lai != null) {
        info.title = lai.getLabel();
        if (labelCache != null) {
            labelCache.put(componentName, info.title);
        }
    }
    // from the db
    if (info.title == null) {
        if (mApp.getContext() != null) {
            info.title = mApp.getContext().getString(titleIndex);
        }
    }
    // fall back to the class name of the activity
    if (info.title == null) {
        info.title = componentName.getClassName();
    }
    info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
    info.user = user;
    info.contentDescription = mUserManager.getBadgedLabelForUser(info.title.toString(), info.user);
    return info;
}

From source file:br.com.viniciuscr.notification2android.mediaPlayer.MediaPlaybackService.java

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

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    ComponentName rec = new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName());
    mAudioManager.registerMediaButtonEventReceiver(rec);

    Intent i = new Intent(Intent.ACTION_MEDIA_BUTTON);
    i.setComponent(rec);
    PendingIntent pi = PendingIntent.getBroadcast(this /*context*/, 0 /*requestCode, ignored*/, i /*intent*/,
            0 /*flags*/);
    mRemoteControlClient = new RemoteControlClient(pi);
    mAudioManager.registerRemoteControlClient(mRemoteControlClient);

    int flags = RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_NEXT
            | RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
            | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_STOP;
    mRemoteControlClient.setTransportControlFlags(flags);

    mPreferences = getSharedPreferences("Music", MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE);
    mCardId = MusicUtils.getCardId(this);

    registerExternalStorageListener();/*from   ww  w. java 2 s  .c  o m*/

    // Needs to be done in this thread, since otherwise ApplicationContext.getPowerManager() crashes.
    mPlayer = new MultiPlayer();
    mPlayer.setHandler(mMediaplayerHandler);

    reloadQueue();
    notifyChange(QUEUE_CHANGED);
    notifyChange(META_CHANGED);

    IntentFilter commandFilter = new IntentFilter();
    commandFilter.addAction(SERVICECMD);
    commandFilter.addAction(TOGGLEPAUSE_ACTION);
    commandFilter.addAction(PAUSE_ACTION);
    commandFilter.addAction(NEXT_ACTION);
    commandFilter.addAction(PREVIOUS_ACTION);
    registerReceiver(mIntentReceiver, commandFilter);

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    mWakeLock.setReferenceCounted(false);

    // If the service was idle, but got killed before it stopped itself, the
    // system will relaunch it. Make sure it gets stopped again in that case.
    Message msg = mDelayedStopHandler.obtainMessage();
    mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}

From source file:br.com.imovelhunter.imovelhunterwebmobile.GcmBroadcastReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    // Explicitly specify that GcmIntentService will handle the intent.
    ComponentName comp = new ComponentName(context.getPackageName(), GcmIntentService.class.getName());

    if (SessionUtilJson.getInstance(context).containsName(ParametrosSessaoJson.USUARIO_LOGADO)) {
        usuarioLogado = (Usuario) SessionUtilJson.getInstance(context)
                .getJsonObject(ParametrosSessaoJson.USUARIO_LOGADO, Usuario.class);
    }/*w w  w  . ja  v  a 2  s .  c o  m*/

    if (mensagemDAO == null) {
        mensagemDAO = new MensagemDAO(context);
    }

    if (notificacaoDAO == null) {
        notificacaoDAO = new NotificacaoDAO(context);
    }

    if (escutadorDeMensagem != null) {
        Bundle bundle = intent.getExtras();

        String mensagemS = bundle.getString("mensagem");

        if (!mensagemS.contains("idImovel")) { // uma mensagem do chat
            Mensagem m = new Mensagem();
            m.parse(mensagemS);
            m.setLida(false);
            if (usuarioLogado != null
                    && m.getUsuariosDestino().get(0).getIdUsuario() == usuarioLogado.getIdUsuario()) {
                escutadorDeMensagem.recebeuAlgo(bundle);
            } else {
                mensagemDAO.inserirMensagem(m);
            }

        } else { // um perfil de imvel

            Notificacao not = new Notificacao();
            Imovel imovel = new Imovel();
            imovel.parse(mensagemS);

            this.parseNotificacao(not, imovel);
            not.setDataNotificacao(new Date());
            notificacaoDAO.inserir(not);

            if (usuarioLogado != null && usuarioLogado.getIdUsuario() == imovel.getIdUsuarioNotificacao()) {
                if (onRecebeuNotificacao != null) {
                    onRecebeuNotificacao.recebeuNotificacao();
                } else {
                    // Start the service, keeping the device awake while it is launching.
                    startWakefulService(context, (intent.setComponent(comp)));
                }

            }

        }

    } else {

        String mensagem = intent.getExtras().getString("mensagem");

        boolean notificar = true;

        if (!mensagem.contains("idImovel")) { //  mensagem de chat
            Mensagem mensagemO = new Mensagem();

            mensagemO.parse(mensagem);

            mensagemO.setLida(false);

            mensagemDAO.inserirMensagem(mensagemO);

            if (onMessageListener != null && usuarioLogado != null
                    && usuarioLogado.getIdUsuario() == mensagemO.getUsuariosDestino().get(0).getIdUsuario()) {
                onMessageListener.atualizar();
            }

            if (usuarioLogado == null
                    || mensagemO.getUsuariosDestino().get(0).getIdUsuario() != usuarioLogado.getIdUsuario()) {
                notificar = false;
            }

        } else { // imvel

            Notificacao not = new Notificacao();
            Imovel imovel = new Imovel();
            imovel.parse(mensagem);
            this.parseNotificacao(not, imovel);
            not.setDataNotificacao(new Date());
            notificacaoDAO.inserir(not);

            if (usuarioLogado != null && usuarioLogado.getIdUsuario() == imovel.getIdUsuarioNotificacao()) {
                if (onRecebeuNotificacao != null) {
                    notificar = false;
                    onRecebeuNotificacao.recebeuNotificacao();
                }

            } else {
                notificar = false;
            }

        }

        if (notificar) {
            // Start the service, keeping the device awake while it is launching.
            startWakefulService(context, (intent.setComponent(comp)));
        }
    }
    setResultCode(Activity.RESULT_OK);
}

From source file:mp.teardrop.PlaybackService.java

/**
 * Create a song notification. Call through the NotificationManager to
 * display it.// w w w  . j av  a  2s .  c o m
 *
 * @param song The Song to display information about.
 * @param state The state. Determines whether to show paused or playing icon.
 */
public Notification createNotification(Song song, int state) {
    boolean playing = (state & FLAG_PLAYING) != 0;

    RemoteViews views = new RemoteViews(getPackageName(), R.layout.notification);
    RemoteViews expanded = new RemoteViews(getPackageName(), R.layout.notification_expanded);

    Bitmap cover = song.getCover(this);
    if (cover == null) {
        views.setImageViewResource(R.id.cover, R.drawable.fallback_cover);
        expanded.setImageViewResource(R.id.cover, R.drawable.fallback_cover);
    } else {
        views.setImageViewBitmap(R.id.cover, cover);
        expanded.setImageViewBitmap(R.id.cover, cover);
    }

    int playButton = getPlayButtonResource(playing);

    views.setImageViewResource(R.id.play_pause, playButton);
    expanded.setImageViewResource(R.id.play_pause, playButton);

    ComponentName service = new ComponentName(this, PlaybackService.class);

    Intent previous = new Intent(PlaybackService.ACTION_PREVIOUS_SONG);
    previous.setComponent(service);
    expanded.setOnClickPendingIntent(R.id.previous, PendingIntent.getService(this, 0, previous, 0));

    Intent playPause = new Intent(PlaybackService.ACTION_TOGGLE_PLAYBACK_NOTIFICATION);
    playPause.setComponent(service);
    views.setOnClickPendingIntent(R.id.play_pause, PendingIntent.getService(this, 0, playPause, 0));
    expanded.setOnClickPendingIntent(R.id.play_pause, PendingIntent.getService(this, 0, playPause, 0));

    Intent next = new Intent(PlaybackService.ACTION_NEXT_SONG);
    next.setComponent(service);
    views.setOnClickPendingIntent(R.id.next, PendingIntent.getService(this, 0, next, 0));
    expanded.setOnClickPendingIntent(R.id.next, PendingIntent.getService(this, 0, next, 0));

    Intent close = new Intent(PlaybackService.ACTION_CLOSE_NOTIFICATION);
    close.setComponent(service);
    views.setOnClickPendingIntent(R.id.close, PendingIntent.getService(this, 0, close, 0));
    expanded.setOnClickPendingIntent(R.id.close, PendingIntent.getService(this, 0, close, 0));

    views.setTextViewText(R.id.title, song.title);
    views.setTextViewText(R.id.artist, song.artist);
    expanded.setTextViewText(R.id.title, song.title);
    expanded.setTextViewText(R.id.album, song.album);
    expanded.setTextViewText(R.id.artist, song.artist);

    Notification notification = new Notification();
    notification.contentView = views;
    notification.icon = R.drawable.status_icon;
    notification.flags |= Notification.FLAG_ONGOING_EVENT;
    notification.contentIntent = mNotificationAction;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        // expanded view is available since 4.1
        notification.bigContentView = expanded;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        notification.visibility = Notification.VISIBILITY_PUBLIC;
    }

    //        if(mNotificationNag) {
    //            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    //                notification.priority = Notification.PRIORITY_MAX;
    //                notification.vibrate = new long[0]; // needed to get headsup
    //            } else {
    //                notification.tickerText = song.title + " - " + song.artist;
    //            }
    //        }

    return notification;
}

From source file:com.tandong.sa.sherlock.widget.SearchView.java

/**
 * Create and return an Intent that can launch the voice search activity,
 * perform a specific voice transcription, and forward the results to the
 * searchable activity./*  ww  w  .  jav  a2s  .  c  o  m*/
 * 
 * @param baseIntent
 *            The voice app search intent to start from
 * @return A completely-configured intent ready to send to the voice search
 *         activity
 */
private Intent createVoiceAppSearchIntent(Intent baseIntent, SearchableInfo searchable) {
    ComponentName searchActivity = searchable.getSearchActivity();

    // create the necessary intent to set up a search-and-forward operation
    // in the voice search system. We have to keep the bundle separate,
    // because it becomes immutable once it enters the PendingIntent
    Intent queryIntent = new Intent(Intent.ACTION_SEARCH);
    queryIntent.setComponent(searchActivity);
    PendingIntent pending = PendingIntent.getActivity(getContext(), 0, queryIntent,
            PendingIntent.FLAG_ONE_SHOT);

    // Now set up the bundle that will be inserted into the pending intent
    // when it's time to do the search. We always build it here (even if
    // empty)
    // because the voice search activity will always need to insert "QUERY"
    // into
    // it anyway.
    Bundle queryExtras = new Bundle();

    // Now build the intent to launch the voice search. Add all necessary
    // extras to launch the voice recognizer, and then all the necessary
    // extras
    // to forward the results to the searchable activity
    Intent voiceIntent = new Intent(baseIntent);

    // Add all of the configuration options supplied by the searchable's
    // metadata
    String languageModel = RecognizerIntent.LANGUAGE_MODEL_FREE_FORM;
    String prompt = null;
    String language = null;
    int maxResults = 1;

    Resources resources = getResources();
    if (searchable.getVoiceLanguageModeId() != 0) {
        languageModel = resources.getString(searchable.getVoiceLanguageModeId());
    }
    if (searchable.getVoicePromptTextId() != 0) {
        prompt = resources.getString(searchable.getVoicePromptTextId());
    }
    if (searchable.getVoiceLanguageId() != 0) {
        language = resources.getString(searchable.getVoiceLanguageId());
    }
    if (searchable.getVoiceMaxResults() != 0) {
        maxResults = searchable.getVoiceMaxResults();
    }
    voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, languageModel);
    voiceIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt);
    voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language);
    voiceIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxResults);
    voiceIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
            searchActivity == null ? null : searchActivity.flattenToShortString());

    // Add the values that configure forwarding the results
    voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, pending);
    voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT_BUNDLE, queryExtras);

    return voiceIntent;
}

From source file:net.sourceforge.servestream.service.MediaPlaybackService.java

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

    int imageThumbSize = getResources().getDimensionPixelSize(R.dimen.image_notification_size);

    ImageCache.ImageCacheParams cacheParams = new ImageCache.ImageCacheParams(this,
            NOTIFICATION_IMAGE_CACHE_DIR);

    cacheParams.setMemCacheSizePercent(0.25f); // Set memory cache to 25% of app memory

    mNotificationImageFetcher = new DatabaseImageResizer(this, imageThumbSize);
    mNotificationImageFetcher.addImageCache(cacheParams);

    cacheParams = new ImageCache.ImageCacheParams(this, LOCK_SCREEN_IMAGE_CACHE_DIR);

    cacheParams.setMemCacheSizePercent(0.25f); // Set memory cache to 25% of app memory

    mLockScreenImageFetcher = new DatabaseImageResizer(this, 600);
    mLockScreenImageFetcher.addImageCache(cacheParams);

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mMediaButtonReceiverComponent = new ComponentName(this, MediaButtonIntentReceiver.class);
    mAudioManager.registerMediaButtonEventReceiver(mMediaButtonReceiverComponent);

    // Use the remote control APIs (if available) to set the playback state
    if (mRemoteControlClientCompat == null) {
        Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        intent.setComponent(mMediaButtonReceiverComponent);
        mRemoteControlClientCompat = new RemoteControlClientCompat(PendingIntent.getBroadcast(this /*context*/,
                0 /*requestCode, ignored*/, intent /*intent*/, 0 /*flags*/));
        RemoteControlHelper.registerRemoteControlClient(mAudioManager, mRemoteControlClientCompat);
    }/*  ww w  . j  a  va 2s .  co  m*/

    mRemoteControlClientCompat.setTransportControlFlags(RemoteControlClientCompat.FLAG_KEY_MEDIA_PREVIOUS
            | RemoteControlClientCompat.FLAG_KEY_MEDIA_PLAY | RemoteControlClientCompat.FLAG_KEY_MEDIA_PAUSE
            | RemoteControlClientCompat.FLAG_KEY_MEDIA_NEXT | RemoteControlClientCompat.FLAG_KEY_MEDIA_STOP);

    mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    mPreferences.registerOnSharedPreferenceChangeListener(this);

    final boolean lockingWifi = mPreferences.getBoolean(PreferenceConstants.WIFI_LOCK, true);
    mConnectivityManager = new ConnectivityReceiver(this, lockingWifi);

    mRetrieveShoutCastMetadata = mPreferences.getBoolean(PreferenceConstants.RETRIEVE_SHOUTCAST_METADATA,
            false);

    mMediaButtonReceiverComponent = new ComponentName(this, MediaButtonIntentReceiver.class);

    mCardId = MusicUtils.getCardId(this);

    registerExternalStorageListener();

    // Needs to be done in this thread, since otherwise ApplicationContext.getPowerManager() crashes.
    mPlayer = new MultiPlayer(this);
    mPlayer.setHandler(mMediaplayerHandler);

    reloadQueue();
    notifyChange(QUEUE_CHANGED);
    notifyChange(META_CHANGED);

    IntentFilter commandFilter = new IntentFilter();
    commandFilter.addAction(SERVICECMD);
    commandFilter.addAction(TOGGLEPAUSE_ACTION);
    commandFilter.addAction(PAUSE_ACTION);
    commandFilter.addAction(NEXT_ACTION);
    commandFilter.addAction(PREVIOUS_ACTION);
    registerReceiver(mIntentReceiver, commandFilter);

    // If the service was idle, but got killed before it stopped itself, the
    // system will relaunch it. Make sure it gets stopped again in that case.
    Message msg = mDelayedStopHandler.obtainMessage();
    mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}

From source file:com.saphion.stencilweather.activities.MainActivity.java

public void share(String packageName, String className) {
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);

    String name = drawerItems.get(navSpinner.getSelectedItemPosition()).getName();
    if (name.contains(",")) {
        name = name.split(",")[0];
    }/*from   w  w  w .  java 2  s .  c  o  m*/

    try {

        shareContainer.setDrawingCacheEnabled(true);
        shareContainer.buildDrawingCache();
        Bitmap icon = shareContainer.getDrawingCache();
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        File f = new File(getExternalCacheDir() + File.separator + "shared" + File.separator + name
                + "_weather_" + System.currentTimeMillis() + ".jpg");
        try {
            f.getParentFile().mkdirs();
            f.createNewFile();
            FileOutputStream fo = new FileOutputStream(f);
            fo.write(bytes.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
        sendIntent.putExtra(Intent.EXTRA_TEXT, name + " Weather shared by Stencil Weather");

        Log.d("Stencil Weather", "tmp file URI " + f.getAbsolutePath());
        sendIntent.setComponent(new ComponentName(packageName, className));
        sendIntent.setType("image/jpeg");
        startActivity(sendIntent);
        shareContainer = null;
        mShareDialog.dismiss();
        mShareDialog = null;
    } catch (Exception ignored) {
    }

}