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:edu.stanford.mobisocial.dungbeetle.feed.objects.AppReferenceObj.java

@Override
public void handleDirectMessage(Context context, Contact from, JSONObject obj) {
    String packageName = obj.optString(PACKAGE_NAME);
    String arg = obj.optString(ARG);
    Intent launch = new Intent();
    launch.setAction(Intent.ACTION_MAIN);
    launch.addCategory(Intent.CATEGORY_LAUNCHER);
    launch.putExtra(AppState.EXTRA_APPLICATION_ARGUMENT, arg);
    launch.putExtra("creator", false);
    launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    launch.setPackage(packageName);/*w  w w  .  j  a va 2s .c o  m*/
    final PackageManager mgr = context.getPackageManager();
    List<ResolveInfo> resolved = mgr.queryIntentActivities(launch, 0);
    if (resolved == null || resolved.size() == 0) {
        Toast.makeText(context, "Could not find application to handle invite", Toast.LENGTH_SHORT).show();
        return;
    }
    ActivityInfo info = resolved.get(0).activityInfo;
    launch.setComponent(new ComponentName(info.packageName, info.name));
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, launch,
            PendingIntent.FLAG_CANCEL_CURRENT);

    (new PresenceAwareNotify(context)).notify("New Invitation", "Invitation received from " + from.name,
            "Click to launch application.", contentIntent);
}

From source file:org.opendatakit.tables.utils.CollectUtil.java

/**
 * Return an intent that can be used to edit a row.
 * <p>//from   www  .  jav  a  2 s . c o  m
 * The idea here is that we might want to edit a row of the table using a
 * pre-set Collect form. This form would be user-defined and would be a more
 * user-friendly thing that would display only the pertinent information for a
 * particular user.
 *
 * @param context
 * @param tp
 * @param elementKeyToValue
 * @param params
 * @return
 */
private static Intent getIntentForOdkCollectEditRow(Context context, String appName, String tableId,
        ArrayList<ColumnDefinition> orderedDefns, Map<String, String> elementKeyToValue,
        CollectFormParameters params, String rowId) {
    // Check if there is a custom form. If there is not, we want to delete
    // the old form and write the new form.
    if (!params.isCustom()) {
        boolean formIsReady = CollectUtil.deleteWriteAndInsertFormIntoCollect(context, appName, tableId,
                orderedDefns, params);
        if (!formIsReady) {
            WebLogger.getLogger(appName).e(TAG, "could not delete, write, or insert a generated form");
            return null;
        }
    }
    boolean shouldUpdate = CollectUtil.isExistingCollectInstanceForRowData(context, appName, tableId, rowId);

    boolean writeDataSuccessful = CollectUtil.writeRowDataToBeEdited(context, appName, tableId, orderedDefns,
            elementKeyToValue, params, rowId);
    if (!writeDataSuccessful) {
        WebLogger.getLogger(appName).e(TAG, "could not write instance file successfully!");
    }
    Uri insertUri = CollectUtil.getUriForCollectInstanceForRowData(context, appName, tableId, params, rowId,
            shouldUpdate);

    // Copied the below from getIntentForOdkCollectEditRow().
    Intent intent = new Intent();
    intent.setComponent(new ComponentName("org.odk.collect.android",
            "org.odk.collect.android.activities.FormEntryActivity"));
    intent.setAction(Intent.ACTION_EDIT);
    intent.setData(insertUri);
    // intent.putExtra("start", true); // jump right into form
    return intent;
}

From source file:com.farmerbb.taskbar.activity.ContextMenuActivity.java

@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.N_MR1)/*from w w  w  .  j  av  a 2 s  .c  om*/
@Override
public boolean onPreferenceClick(Preference p) {
    UserManager userManager = (UserManager) getSystemService(USER_SERVICE);
    LauncherApps launcherApps = (LauncherApps) getSystemService(LAUNCHER_APPS_SERVICE);
    boolean appIsValid = isStartButton || isOverflowMenu
            || !launcherApps.getActivityList(getIntent().getStringExtra("package_name"),
                    userManager.getUserForSerialNumber(userId)).isEmpty();

    if (appIsValid)
        switch (p.getKey()) {
        case "app_info":
            startFreeformActivity();
            launcherApps.startAppDetailsActivity(ComponentName.unflattenFromString(componentName),
                    userManager.getUserForSerialNumber(userId), null, null);

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "uninstall":
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && isInMultiWindowMode()) {
                Intent intent2 = new Intent(ContextMenuActivity.this, DummyActivity.class);
                intent2.putExtra("uninstall", packageName);
                intent2.putExtra("user_id", userId);

                startFreeformActivity();
                startActivity(intent2);
            } else {
                startFreeformActivity();

                Intent intent2 = new Intent(Intent.ACTION_DELETE, Uri.parse("package:" + packageName));
                intent2.putExtra(Intent.EXTRA_USER, userManager.getUserForSerialNumber(userId));

                try {
                    startActivity(intent2);
                } catch (ActivityNotFoundException e) {
                    /* Gracefully fail */ }
            }

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "open_taskbar_settings":
            startFreeformActivity();

            Intent intent2 = new Intent(this, MainActivity.class);
            intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent2);

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "quit_taskbar":
            Intent quitIntent = new Intent("com.farmerbb.taskbar.QUIT");
            quitIntent.setPackage(BuildConfig.APPLICATION_ID);
            sendBroadcast(quitIntent);

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "pin_app":
            PinnedBlockedApps pba = PinnedBlockedApps.getInstance(this);
            if (pba.isPinned(componentName))
                pba.removePinnedApp(this, componentName);
            else {
                Intent intent = new Intent();
                intent.setComponent(ComponentName.unflattenFromString(componentName));

                LauncherActivityInfo appInfo = launcherApps.resolveActivity(intent,
                        userManager.getUserForSerialNumber(userId));
                if (appInfo != null) {
                    AppEntry newEntry = new AppEntry(packageName, componentName, appName,
                            IconCache.getInstance(this).getIcon(this, getPackageManager(), appInfo), true);

                    newEntry.setUserId(userId);
                    pba.addPinnedApp(this, newEntry);
                }
            }
            break;
        case "block_app":
            PinnedBlockedApps pba2 = PinnedBlockedApps.getInstance(this);
            if (pba2.isBlocked(componentName))
                pba2.removeBlockedApp(this, componentName);
            else {
                pba2.addBlockedApp(this, new AppEntry(packageName, componentName, appName, null, false));
            }
            break;
        case "show_window_sizes":
            getPreferenceScreen().removeAll();

            addPreferencesFromResource(R.xml.pref_context_menu_window_size_list);
            findPreference("window_size_standard").setOnPreferenceClickListener(this);
            findPreference("window_size_large").setOnPreferenceClickListener(this);
            findPreference("window_size_fullscreen").setOnPreferenceClickListener(this);
            findPreference("window_size_half_left").setOnPreferenceClickListener(this);
            findPreference("window_size_half_right").setOnPreferenceClickListener(this);
            findPreference("window_size_phone_size").setOnPreferenceClickListener(this);

            SharedPreferences pref = U.getSharedPreferences(this);
            if (pref.getBoolean("save_window_sizes", true)) {
                String windowSizePref = SavedWindowSizes.getInstance(this).getWindowSize(this, packageName);
                CharSequence title = findPreference("window_size_" + windowSizePref).getTitle();
                findPreference("window_size_" + windowSizePref).setTitle('\u2713' + " " + title);
            }

            if (U.isOPreview()) {
                U.showToast(this, R.string.window_sizes_not_available);
            }

            secondaryMenu = true;
            break;
        case "window_size_standard":
        case "window_size_large":
        case "window_size_fullscreen":
        case "window_size_half_left":
        case "window_size_half_right":
        case "window_size_phone_size":
            String windowSize = p.getKey().replace("window_size_", "");

            SharedPreferences pref2 = U.getSharedPreferences(this);
            if (pref2.getBoolean("save_window_sizes", true)) {
                SavedWindowSizes.getInstance(this).setWindowSize(this, packageName, windowSize);
            }

            startFreeformActivity();
            U.launchApp(getApplicationContext(), packageName, componentName, userId, windowSize, false, true);

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "app_shortcuts":
            getPreferenceScreen().removeAll();
            generateShortcuts();

            secondaryMenu = true;
            break;
        case "shortcut_1":
        case "shortcut_2":
        case "shortcut_3":
        case "shortcut_4":
        case "shortcut_5":
            U.startShortcut(getApplicationContext(), packageName, componentName,
                    shortcuts.get(Integer.parseInt(p.getKey().replace("shortcut_", "")) - 1));

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "start_menu_apps":
            startFreeformActivity();

            Intent intent = null;

            SharedPreferences pref3 = U.getSharedPreferences(this);
            switch (pref3.getString("theme", "light")) {
            case "light":
                intent = new Intent(this, SelectAppActivity.class);
                break;
            case "dark":
                intent = new Intent(this, SelectAppActivityDark.class);
                break;
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && pref3.getBoolean("freeform_hack", false)
                    && intent != null && isInMultiWindowMode()) {
                intent.putExtra("no_shadow", true);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT);

                U.launchAppMaximized(getApplicationContext(), intent);
            } else
                startActivity(intent);

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "volume":
            AudioManager audio = (AudioManager) getSystemService(AUDIO_SERVICE);
            audio.adjustSuggestedStreamVolume(AudioManager.ADJUST_SAME, AudioManager.USE_DEFAULT_STREAM_TYPE,
                    AudioManager.FLAG_SHOW_UI);

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "file_manager":
            Intent fileManagerIntent;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                startFreeformActivity();
                fileManagerIntent = new Intent("android.provider.action.BROWSE");
            } else {
                fileManagerIntent = new Intent("android.provider.action.BROWSE_DOCUMENT_ROOT");
                fileManagerIntent.setComponent(
                        ComponentName.unflattenFromString("com.android.documentsui/.DocumentsActivity"));
            }

            fileManagerIntent.addCategory(Intent.CATEGORY_DEFAULT);
            fileManagerIntent
                    .setData(Uri.parse("content://com.android.externalstorage.documents/root/primary"));

            try {
                startActivity(fileManagerIntent);
            } catch (ActivityNotFoundException e) {
                U.showToast(this, R.string.lock_device_not_supported);
            }

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "system_settings":
            startFreeformActivity();

            Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);

            try {
                startActivity(settingsIntent);
            } catch (ActivityNotFoundException e) {
                U.showToast(this, R.string.lock_device_not_supported);
            }

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "lock_device":
            U.lockDevice(this);

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "power_menu":
            U.sendAccessibilityAction(this, AccessibilityService.GLOBAL_ACTION_POWER_DIALOG);

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "change_wallpaper":
            Intent intent3 = Intent.createChooser(new Intent(Intent.ACTION_SET_WALLPAPER),
                    getString(R.string.set_wallpaper));
            intent3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            U.launchAppMaximized(getApplicationContext(), intent3);

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        }

    if (!secondaryMenu)
        finish();
    return true;
}

From source file:org.ohthehumanity.carrie.CarrieActivity.java

/** Called when the activity is first created. */
@Override//from  ww  w  . j  a va 2  s  . com
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mServerName = "";
    setContentView(R.layout.main);

    // instantiate our preferences backend
    mPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    // set callback function when settings change
    mPreferences.registerOnSharedPreferenceChangeListener(this);

    if (mPreferences.getString("server", null) == null) {
        setStatus("Server not set");
    } else if (mPreferences.getString("port", null) == null) {
        setStatus("Port not configured");
    }

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm.getActiveNetworkInfo().getType() != ConnectivityManager.TYPE_WIFI) {

        AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
        dlgAlert.setTitle("WiFi not active");
        dlgAlert.setMessage(
                "This application is usually used on a local network over a WiFi. Open WiFi settings?");
        dlgAlert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                case DialogInterface.BUTTON_POSITIVE:
                    //Yes button clicked
                    final Intent intent = new Intent(Intent.ACTION_MAIN, null);
                    intent.addCategory(Intent.CATEGORY_LAUNCHER);
                    final ComponentName cn = new ComponentName("com.android.settings",
                            "com.android.settings.wifi.WifiSettings");
                    intent.setComponent(cn);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    break;

                case DialogInterface.BUTTON_NEGATIVE:
                    //Log.i(TAG, "Not opening wifi");
                    //No button clicked
                    break;
                }
            }
        });

        dlgAlert.setNegativeButton("No", null);
        dlgAlert.setCancelable(true);
        dlgAlert.create().show();
    }

    updateTitle();
    updateSkipLabels();
    updateServerName();
}

From source file:com.nd.android.u.square.service.MusicPlaybackService.java

/**
 * Starts playing the next song. If manualUrl is null, the next song will be randomly selected
 * from our Media Retriever (that is, it will be a random song in the user's device). If
 * manualUrl is non-null, then it specifies the URL or path to the song that will be played
 * next.//from   w ww.  j  a  v  a  2 s  .  c  o m
 */
void playNextSong(Item playingItem) {
    mState = State.Stopped;
    relaxResources(false); // release everything except MediaPlayer

    try {
        if (null == playingItem) {
            playingItem = pollNextSong(mPlayingItem);
            if (null == playingItem) {
                if (sOnStateChangedListener != null) {
                    sOnStateChangedListener.onPlayListIsEmpty();
                }
                return;
            }
            mPlayingItem = playingItem;

            if (null != sOnStateChangedListener)
                sOnStateChangedListener.onCurrentPlayingItemChanged(mPlayingItem);
        }

        // set the source of the media player a a content URI
        createMediaPlayerIfNeeded();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mPlayer.setDataSource(playingItem.getUrl());
        mIsStreaming = true;
        mSongTitle = playingItem.title;
        mState = State.Preparing;
        setUpAsForeground(mSongTitle + "");

        // Use the media button APIs (if available) to register ourselves for media button
        // events

        MediaButtonHelper.registerMediaButtonEventReceiverCompat(mAudioManager, 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);
        }

        mRemoteControlClientCompat.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING);

        mRemoteControlClientCompat.setTransportControlFlags(
                RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
                        | RemoteControlClient.FLAG_KEY_MEDIA_NEXT | RemoteControlClient.FLAG_KEY_MEDIA_STOP);

        // Update the remote controls
        mRemoteControlClientCompat.editMetadata(true)
                .putString(MediaMetadataRetriever.METADATA_KEY_TITLE, playingItem.title)
                .putLong(MediaMetadataRetriever.METADATA_KEY_DURATION, playingItem.duration)
                // TODO: fetch real item artwork
                .putBitmap(RemoteControlClientCompat.MetadataEditorCompat.METADATA_KEY_ARTWORK, mDummyAlbumArt)
                .apply();

        // starts preparing the media player in the background. When it's done, it will call
        // our OnPreparedListener (that is, the onPrepared() method on this class, since we set
        // the listener to 'this').
        //
        // Until the media player is prepared, we *cannot* call start() on it!
        mPlayingItem.bufferedPercent = 0;
        mPlayer.prepareAsync();

        if (null != sOnStateChangedListener)
            sOnStateChangedListener.onPlayerPreparing(mPlayingItem);

        // If we are streaming from the internet, we want to hold a Wifi lock, which prevents
        // the Wifi radio from going to sleep while the song is playing. If, on the other hand,
        // we are *not* streaming, we want to release the lock if we were holding it before.
        if (mIsStreaming)
            mWifiLock.acquire();
        else if (mWifiLock.isHeld())
            mWifiLock.release();
    } catch (IOException ex) {
        Log.e(TAG, "IOException playing next song: " + ex.getMessage(), ex);
    }
}

From source file:org.opendatakit.tables.utils.CollectUtil.java

/**
 * Return an intent that can be launched to add a row.
 *
 * @param context/*from  w  w  w.ja  va  2s.  c  om*/
 * @param tp
 * @param params
 * @param elementKeyToValue
 *          values with which you want to prepopulate the add row form.
 * @return
 */
public static Intent getIntentForOdkCollectAddRow(Context context, String appName, String tableId,
        ArrayList<ColumnDefinition> orderedDefns, CollectFormParameters params,
        Map<String, String> elementKeyToValue) {
    /*
     * So, there are several things to check here. The first thing we want to do
     * is see if a custom form has been defined for this table. If there is not,
     * then we will need to write a custom one. When we do this, we will then
     * have to call delete on Collect to remove the old form, which may have
     * used the same id. This will not fail if a form has not been already been
     * written--delete will simply return 0.
     */
    // Check if there is a custom form. If there is not, we want to delete
    // the old form and write the new form.
    if (!params.isCustom()) {
        boolean formIsReady = CollectUtil.deleteWriteAndInsertFormIntoCollect(context, appName, tableId,
                orderedDefns, params);
        if (!formIsReady) {
            WebLogger.getLogger(appName).e(TAG, "could not delete, write, or insert a generated form");
            return null;
        }
    }
    // manufacture a rowId for this record...
    String rowId = "uuid:" + UUID.randomUUID().toString();

    boolean shouldUpdate = CollectUtil.isExistingCollectInstanceForRowData(context, appName, tableId, rowId);

    // emit the empty or partially-populated instance
    // we've received some values to prepopulate the add row with.
    boolean writeDataSuccessful = CollectUtil.writeRowDataToBeEdited(context, appName, tableId, orderedDefns,
            elementKeyToValue, params, rowId);
    if (!writeDataSuccessful) {
        WebLogger.getLogger(appName).e(TAG, "could not write instance file successfully!");
    }
    // Here we'll just act as if we're inserting 0, which
    // really doesn't matter?
    Uri formToLaunch = CollectUtil.getUriForCollectInstanceForRowData(context, appName, tableId, params, rowId,
            shouldUpdate);

    // And now finally create the intent.
    Intent intent = new Intent();
    intent.setComponent(new ComponentName("org.odk.collect.android",
            "org.odk.collect.android.activities.FormEntryActivity"));
    intent.setAction(Intent.ACTION_EDIT);
    intent.setData(formToLaunch);
    intent.putExtra("start", true); // jump right into form
    return intent;
}

From source file:org.alfresco.mobile.android.application.fragments.user.UserProfileFragment.java

public void actionSkype(FragmentActivity activity, int skypeAction, String personId) {
    // Make sure the Skype for Android client is installed
    if (!isSkypeClientInstalled(activity)) {
        goToMarket(activity);/*from  w w w.j  a v a 2s  .  c om*/
        return;
    }

    String mySkypeUri = "skype:";
    switch (skypeAction) {
    case ACTION_CALL:
        mySkypeUri += personId + "?call";
        break;
    case ACTION_CHAT:
        mySkypeUri += personId + "?chat";
        break;
    case ACTION_VIDEO_CALL:
        mySkypeUri += personId + "?call&video=true";
        break;
    default:
        break;
    }

    // Create the Intent from our Skype URI
    Uri skypeUri = Uri.parse(mySkypeUri);
    Intent myIntent = new Intent(Intent.ACTION_VIEW, skypeUri);

    // Restrict the Intent to being handled by the Skype for Android client
    // only
    myIntent.setComponent(new ComponentName("com.skype.raider", "com.skype.raider.Main"));
    myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    // Initiate the Intent. It should never fail since we've already
    // established the
    // presence of its handler (although there is an extremely minute window
    // where that
    // handler can go away...)
    if (myIntent.resolveActivity(activity.getPackageManager()) == null) {
        AlfrescoNotificationManager.getInstance(activity).showAlertCrouton((FragmentActivity) activity,
                activity.getString(R.string.feature_disable));
        return;
    }
    activity.startActivity(myIntent);
}

From source file:com.iamplus.musicplayer.MusicService.java

private void startPlayback() {
    try {// www .  j av  a 2  s . co m
        MediaItem playingItem = null;
        mIsStreaming = false; // playing a locally available song

        playingItem = MusicRetriever.getInstance().getCurrentSong();
        if (playingItem == null) {
            //Get all songs if the current list is empty
            MusicRetriever.getInstance().setSonglist(getAllSongs(), 0);
            MusicRetriever.getInstance().setPlayMode(e_play_mode.e_play_mode_shuffle);

            playingItem = MusicRetriever.getInstance().getCurrentSong();

            if (playingItem == null) {
                processStopRequest(true); // stop everything!
                return;
            }
        }
        mCurrentPlayingItem = playingItem;

        // set the source of the media player a a content URI
        createMediaPlayerIfNeeded();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mPlayer.setDataSource(getApplicationContext(), playingItem.getURI());

        // starts preparing the media player in the background. When it's done, it will call
        // our OnPreparedListener (that is, the onPrepared() method on this class, since we set
        // the listener to 'this').
        //
        // Until the media player is prepared, we *cannot* call start() on it!
        mPlayer.prepareAsync();

        // If we are streaming from the internet, we want to hold a Wifi lock, which prevents
        // the Wifi radio from going to sleep while the song is playing. If, on the other hand,
        // we are *not* streaming, we want to release the lock if we were holding it before.
        //         if (mIsStreaming) mWifiLock.acquire();
        //         else if (mWifiLock.isHeld()) mWifiLock.release();
    } catch (IOException ex) {
        Log.e(TAG, "IOException playing first song: " + ex.getMessage());
        //ex.printStackTrace();
        Toast.makeText(getApplicationContext(), R.string.invalid_file_track, Toast.LENGTH_LONG).show();
        //Stop Playback
        processStopRequest();
        return;
    }
    //mSongTitle = mCurrentPlayingItem.getTitle();

    //setUpAsForeground(mSongTitle + " (loading)");

    // Use the media button APIs (if available) to register ourselves for media button
    // events

    MediaButtonHelper.registerMediaButtonEventReceiverCompat(mAudioManager, 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);
    }

    mRemoteControlClientCompat.setTransportControlFlags(
            RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
                    | RemoteControlClient.FLAG_KEY_MEDIA_NEXT | RemoteControlClient.FLAG_KEY_MEDIA_STOP);

    updateRemoteControlPlayingState();
}

From source file:com.torrenttunes.android.MusicService.java

@Override
public void onCreate() {
    super.onCreate();
    LogHelper.d(TAG, "onCreate");

    mPlayingQueue = new ArrayList<>();
    mMusicProvider = new MusicProvider();
    mPackageValidator = new PackageValidator(this);

    mEventReceiver = new ComponentName(getPackageName(), MediaButtonReceiver.class.getName());

    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(mEventReceiver);
    mMediaPendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, 0);

    // Start a new MediaSession
    mSession = new MediaSessionCompat(this, "MusicService", mEventReceiver, mMediaPendingIntent);

    final MediaSessionCallback cb = new MediaSessionCallback();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // Shouldn't really have to do this but the MediaSessionCompat method uses
        // an internal proxy class, which doesn't forward events such as
        // onPlayFromMediaId when running on Lollipop.
        final MediaSession session = (MediaSession) mSession.getMediaSession();
        // session.setCallback(new MediaSessionCallbackProxy(cb));
    } else {/* ww w .  j  a  v  a 2  s . co  m*/
        mSession.setCallback(cb);
    }

    setSessionToken(mSession.getSessionToken());
    mSession.setFlags(
            MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);

    mPlayback = new LocalPlayback(this, mMusicProvider);
    mPlayback.setState(PlaybackStateCompat.STATE_NONE);
    mPlayback.setCallback(this);
    mPlayback.start();

    Context context = getApplicationContext();
    Intent intent = new Intent(context, NowPlayingActivity.class);
    PendingIntent pi = PendingIntent.getActivity(context, 99 /*request code*/, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    mSession.setSessionActivity(pi);

    mSessionExtras = new Bundle();
    CarHelper.setSlotReservationFlags(mSessionExtras, true, true, true);
    mSession.setExtras(mSessionExtras);

    updatePlaybackState(null);

    mMediaNotificationManager = new MediaNotificationManager(this);
    mCastManager = VideoCastManager.getInstance();
    mCastManager.addVideoCastConsumer(mCastConsumer);

    mMediaRouter = MediaRouter.getInstance(getApplicationContext());
}

From source file:de.sitewaerts.cordova.documentviewer.DocumentViewerPlugin.java

private void _open(String url, String contentType, String packageId, String activity,
        CallbackContext callbackContext, Bundle viewerOptions) throws JSONException {
    clearTempFiles();//  w w w . j  a v  a  2s.c o m

    File file = getAccessibleFile(url);

    if (file != null && file.exists() && file.isFile()) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri path = Uri.fromFile(file);

            // @see http://stackoverflow.com/questions/2780102/open-another-application-from-your-own-intent
            intent.addCategory(Intent.CATEGORY_EMBED);
            intent.setDataAndType(path, contentType);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra(this.getClass().getName(), viewerOptions);
            //activity needs fully qualified name here
            intent.setComponent(new ComponentName(packageId, packageId + "." + activity));

            this.callbackContext = callbackContext;
            this.cordova.startActivityForResult(this, intent, REQUEST_CODE_OPEN);

            // send shown event
            JSONObject successObj = new JSONObject();
            successObj.put(Result.STATUS, PluginResult.Status.OK.ordinal());
            PluginResult result = new PluginResult(PluginResult.Status.OK, successObj);
            // need to keep callback for close event
            result.setKeepCallback(true);
            callbackContext.sendPluginResult(result);
        } catch (android.content.ActivityNotFoundException e) {
            JSONObject errorObj = new JSONObject();
            errorObj.put(Result.STATUS, PluginResult.Status.ERROR.ordinal());
            errorObj.put(Result.MESSAGE, "Activity not found: " + e.getMessage());
            callbackContext.error(errorObj);
        }
    } else {
        JSONObject errorObj = new JSONObject();
        errorObj.put(Result.STATUS, PluginResult.Status.ERROR.ordinal());
        errorObj.put(Result.MESSAGE, "File not found");
        callbackContext.error(errorObj);
    }
}