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:com.irccloud.android.data.collection.NotificationsList.java

@SuppressLint("NewApi")
private android.app.Notification buildNotification(String ticker, int cid, int bid, long[] eids, String title,
        String text, int count, Intent replyIntent, String network, ArrayList<Notification> messages,
        NotificationCompat.Action otherAction, Bitmap largeIcon, Bitmap wearBackground) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel c = new NotificationChannel(String.valueOf(bid), title,
                NotificationManager.IMPORTANCE_HIGH);
        c.setGroup(String.valueOf(cid));
        ((NotificationManager) IRCCloudApplication.getInstance().getApplicationContext()
                .getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(c);
    }/*w  ww  . j av a 2 s.  c  o  m*/
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());
    int defaults = 0;
    NotificationCompat.Builder builder = new NotificationCompat.Builder(
            IRCCloudApplication.getInstance().getApplicationContext(), String.valueOf(bid))
                    .setContentTitle(
                            title + ((network != null && !network.equals(title)) ? (" (" + network + ")") : ""))
                    .setContentText(Html.fromHtml(text)).setAutoCancel(true).setTicker(ticker)
                    .setWhen(eids[0] / 1000).setSmallIcon(R.drawable.ic_stat_notify).setLargeIcon(largeIcon)
                    .setColor(IRCCloudApplication.getInstance().getApplicationContext().getResources()
                            .getColor(R.color.ic_background))
                    .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
                    .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                    .setPriority(hasTouchWiz() ? NotificationCompat.PRIORITY_DEFAULT
                            : NotificationCompat.PRIORITY_HIGH)
                    .setOnlyAlertOnce(false);

    if (ticker != null && (System.currentTimeMillis() - prefs.getLong("lastNotificationTime", 0)) > 2000) {
        String ringtone = prefs.getString("notify_ringtone",
                "android.resource://"
                        + IRCCloudApplication.getInstance().getApplicationContext().getPackageName() + "/"
                        + R.raw.digit);
        if (ringtone.length() > 0)
            builder.setSound(Uri.parse(ringtone));
    }

    int led_color = Integer.parseInt(prefs.getString("notify_led_color", "1"));
    if (led_color == 1) {
        defaults = android.app.Notification.DEFAULT_LIGHTS;
    } else if (led_color == 2) {
        builder.setLights(0xFF0000FF, 500, 500);
    }

    if (prefs.getBoolean("notify_vibrate", true) && ticker != null
            && (System.currentTimeMillis() - prefs.getLong("lastNotificationTime", 0)) > 2000)
        defaults |= android.app.Notification.DEFAULT_VIBRATE;
    else
        builder.setVibrate(new long[] { 0L });

    builder.setDefaults(defaults);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putLong("lastNotificationTime", System.currentTimeMillis());
    editor.commit();

    Intent i = new Intent();
    i.setComponent(new ComponentName(IRCCloudApplication.getInstance().getApplicationContext().getPackageName(),
            "com.irccloud.android.MainActivity"));
    i.putExtra("bid", bid);
    i.setData(Uri.parse("bid://" + bid));
    Intent dismiss = new Intent(IRCCloudApplication.getInstance().getApplicationContext().getResources()
            .getString(R.string.DISMISS_NOTIFICATION));
    dismiss.setData(Uri.parse("irccloud-dismiss://" + bid));
    dismiss.putExtra("bid", bid);
    dismiss.putExtra("eids", eids);

    PendingIntent dismissPendingIntent = PendingIntent.getBroadcast(
            IRCCloudApplication.getInstance().getApplicationContext(), 0, dismiss,
            PendingIntent.FLAG_UPDATE_CURRENT);

    builder.setContentIntent(
            PendingIntent.getActivity(IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                    PendingIntent.FLAG_UPDATE_CURRENT));
    builder.setDeleteIntent(dismissPendingIntent);

    WearableExtender wearableExtender = new WearableExtender();
    wearableExtender.setBackground(wearBackground);
    if (messages != null && messages.size() > 0) {
        StringBuilder weartext = new StringBuilder();
        String servernick = getServerNick(messages.get(0).cid);
        NotificationCompat.MessagingStyle style = new NotificationCompat.MessagingStyle(servernick);
        style.setConversationTitle(title + ((network != null) ? (" (" + network + ")") : ""));
        for (Notification n : messages) {
            if (n != null && n.message != null && n.message.length() > 0) {
                if (weartext.length() > 0)
                    weartext.append("<br/>");
                if (n.message_type.equals("buffer_me_msg")) {
                    style.addMessage(Html.fromHtml(n.message).toString(), n.eid / 1000,
                            " " + ((n.nick == null) ? servernick : n.nick));
                    weartext.append("<b> ").append((n.nick == null) ? servernick : n.nick).append("</b> ")
                            .append(n.message);
                } else {
                    style.addMessage(Html.fromHtml(n.message).toString(), n.eid / 1000, n.nick);
                    weartext.append("<b>&lt;").append((n.nick == null) ? servernick : n.nick)
                            .append("&gt;</b> ").append(n.message);
                }
            }
        }

        ArrayList<String> history = new ArrayList<>(messages.size());
        for (int j = messages.size() - 1; j >= 0; j--) {
            Notification n = messages.get(j);
            if (n != null) {
                if (n.nick == null)
                    history.add(Html.fromHtml(n.message).toString());
                else
                    break;
            }
        }
        builder.setRemoteInputHistory(history.toArray(new String[history.size()]));
        builder.setStyle(style);

        if (messages.size() > 1) {
            wearableExtender.addPage(
                    new NotificationCompat.Builder(IRCCloudApplication.getInstance().getApplicationContext())
                            .setContentText(Html.fromHtml(weartext.toString()))
                            .extend(new WearableExtender().setStartScrollBottom(true)).build());
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
                && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            weartext.setLength(0);
            int j = 0;
            for (Notification n : messages) {
                if (messages.size() - ++j < 3) {
                    if (n != null && n.message != null && n.message.length() > 0) {
                        if (weartext.length() > 0)
                            weartext.append("<br/>");
                        if (n.message_type.equals("buffer_me_msg")) {
                            weartext.append("<b> ").append((n.nick == null) ? servernick : n.nick)
                                    .append("</b> ").append(n.message);
                        } else {
                            weartext.append("<b>&lt;").append((n.nick == null) ? servernick : n.nick)
                                    .append("&gt;</b> ").append(n.message);
                        }
                    }
                }
            }

            RemoteViews bigContentView = new RemoteViews(
                    IRCCloudApplication.getInstance().getApplicationContext().getPackageName(),
                    R.layout.notification_expanded);
            bigContentView.setTextViewText(R.id.title,
                    title + (!title.equals(network) ? (" (" + network + ")") : ""));
            bigContentView.setTextViewText(R.id.text, Html.fromHtml(weartext.toString()));
            bigContentView.setImageViewBitmap(R.id.image, largeIcon);
            bigContentView.setLong(R.id.time, "setTime", eids[0] / 1000);
            if (count > 3) {
                bigContentView.setViewVisibility(R.id.more, View.VISIBLE);
                bigContentView.setTextViewText(R.id.more, "+" + (count - 3) + " more");
            } else {
                bigContentView.setViewVisibility(R.id.more, View.GONE);
            }
            if (replyIntent != null && prefs.getBoolean("notify_quickreply", true)) {
                bigContentView.setViewVisibility(R.id.actions, View.VISIBLE);
                bigContentView.setViewVisibility(R.id.action_divider, View.VISIBLE);
                i = new Intent(IRCCloudApplication.getInstance().getApplicationContext(),
                        QuickReplyActivity.class);
                i.setData(Uri.parse("irccloud-bid://" + bid));
                i.putExtras(replyIntent);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                PendingIntent quickReplyIntent = PendingIntent.getActivity(
                        IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                        PendingIntent.FLAG_UPDATE_CURRENT);
                bigContentView.setOnClickPendingIntent(R.id.action_reply, quickReplyIntent);
            }
            builder.setCustomBigContentView(bigContentView);
        }
    }

    if (replyIntent != null) {
        PendingIntent replyPendingIntent = PendingIntent.getService(
                IRCCloudApplication.getInstance().getApplicationContext(), bid + 1, replyIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            builder.addAction(new NotificationCompat.Action.Builder(0, "Reply", replyPendingIntent)
                    .setAllowGeneratedReplies(true)
                    .addRemoteInput(
                            new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build())
                    .build());
        }

        NotificationCompat.Action.Builder actionBuilder = new NotificationCompat.Action.Builder(
                R.drawable.ic_wearable_reply, "Reply", replyPendingIntent).setAllowGeneratedReplies(true)
                        .addRemoteInput(
                                new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build());

        NotificationCompat.Action.WearableExtender actionExtender = new NotificationCompat.Action.WearableExtender()
                .setHintLaunchesActivity(true).setHintDisplayActionInline(true);

        wearableExtender.addAction(actionBuilder.extend(actionExtender).build());

        NotificationCompat.CarExtender.UnreadConversation.Builder unreadConvBuilder = new NotificationCompat.CarExtender.UnreadConversation.Builder(
                title + ((network != null) ? (" (" + network + ")") : ""))
                        .setReadPendingIntent(dismissPendingIntent).setReplyAction(replyPendingIntent,
                                new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build());

        if (messages != null) {
            for (Notification n : messages) {
                if (n != null && n.nick != null && n.message != null && n.message.length() > 0) {
                    if (n.buffer_type.equals("conversation")) {
                        if (n.message_type.equals("buffer_me_msg"))
                            unreadConvBuilder
                                    .addMessage(" " + n.nick + " " + Html.fromHtml(n.message).toString());
                        else
                            unreadConvBuilder.addMessage(Html.fromHtml(n.message).toString());
                    } else {
                        if (n.message_type.equals("buffer_me_msg"))
                            unreadConvBuilder
                                    .addMessage(" " + n.nick + " " + Html.fromHtml(n.message).toString());
                        else
                            unreadConvBuilder
                                    .addMessage(n.nick + " said: " + Html.fromHtml(n.message).toString());
                    }
                }
            }
        } else {
            unreadConvBuilder.addMessage(text);
        }
        unreadConvBuilder.setLatestTimestamp(eids[count - 1] / 1000);

        builder.extend(new NotificationCompat.CarExtender().setUnreadConversation(unreadConvBuilder.build()));
    }

    if (replyIntent != null && prefs.getBoolean("notify_quickreply", true)
            && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
        i = new Intent(IRCCloudApplication.getInstance().getApplicationContext(), QuickReplyActivity.class);
        i.setData(Uri.parse("irccloud-bid://" + bid));
        i.putExtras(replyIntent);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent quickReplyIntent = PendingIntent.getActivity(
                IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.addAction(R.drawable.ic_action_reply, "Quick Reply", quickReplyIntent);
    }

    if (otherAction != null) {
        int drawable = 0;
        if (otherAction.getIcon() == R.drawable.ic_wearable_add)
            drawable = R.drawable.ic_action_add;
        else if (otherAction.getIcon() == R.drawable.ic_wearable_reply)
            drawable = R.drawable.ic_action_reply;
        builder.addAction(
                new NotificationCompat.Action(drawable, otherAction.getTitle(), otherAction.getActionIntent()));
        wearableExtender.addAction(otherAction);
    }

    builder.extend(wearableExtender);

    return builder.build();
}

From source file:org.chromium.chrome.browser.download.DownloadNotificationService.java

/**
 * Add a download successful notification.
 * @param downloadGuid GUID of the download.
 * @param filePath Full path to the download.
 * @param fileName Filename of the download.
 * @param systemDownloadId Download ID assigned by system DownloadManager.
 * @param isOfflinePage Whether the download is for offline page.
 * @param isSupportedMimeType Whether the MIME type can be viewed inside browser.
 * @return ID of the successful download notification. Used for removing the notification when
 *         user click on the snackbar./*from   ww  w.j  a v  a  2  s  . c  o m*/
 */
public int notifyDownloadSuccessful(String downloadGuid, String filePath, String fileName,
        long systemDownloadId, boolean isOfflinePage, boolean isSupportedMimeType) {
    int notificationId = getNotificationId(downloadGuid);
    NotificationCompat.Builder builder = buildNotification(R.drawable.offline_pin, fileName,
            mContext.getResources().getString(R.string.download_notification_completed));
    ComponentName component = new ComponentName(mContext.getPackageName(),
            DownloadBroadcastReceiver.class.getName());
    Intent intent;
    if (isOfflinePage) {
        intent = buildActionIntent(ACTION_DOWNLOAD_OPEN, notificationId, downloadGuid, fileName, isOfflinePage);
    } else {
        intent = new Intent(DownloadManager.ACTION_NOTIFICATION_CLICKED);
        long[] idArray = { systemDownloadId };
        intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, idArray);
        intent.putExtra(EXTRA_DOWNLOAD_FILE_PATH, filePath);
        intent.putExtra(EXTRA_IS_SUPPORTED_MIME_TYPE, isSupportedMimeType);
    }
    intent.setComponent(component);
    builder.setContentIntent(
            PendingIntent.getBroadcast(mContext, notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT));
    if (mDownloadSuccessLargeIcon == null) {
        Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.offline_pin);
        mDownloadSuccessLargeIcon = getLargeNotificationIcon(bitmap);
    }
    builder.setLargeIcon(mDownloadSuccessLargeIcon);
    updateNotification(notificationId, builder.build());
    removeSharedPreferenceEntry(downloadGuid);
    mDownloadsInProgress.remove(downloadGuid);
    return notificationId;
}

From source file:com.apexlabs.alarm.AlarmService.java

private Intent getClockIntent() {
    PackageManager packageManager = getPackageManager();
    Intent alarmClockIntent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);

    // Verify clock implementation
    String clockImpls[][] = {//ww  w . j  a v a 2 s  .co m
            { "HTC", "com.htc.android.worldclock", "com.htc.android.worldclock.WorldClockTabControl" },
            { "Standard", "com.android.deskclock", "com.android.deskclock.AlarmClock" },
            { "Froyo", "com.google.android.deskclock", "com.android.deskclock.DeskClock" },
            { "Motorola", "com.motorola.blur.alarmclock", "com.motorola.blur.alarmclock.AlarmClock" },
            { "Sony Ericsson", "com.sonyericsson.alarm", "com.sonyericsson.alarm.Alarm" }, { "Samsung",
                    "com.sec.android.app.clockpackage", "com.sec.android.app.clockpackage.ClockPackage" } };

    boolean foundClockImpl = false;

    for (int i = 0; i < clockImpls.length; i++) {
        String packageName = clockImpls[i][1];
        String className = clockImpls[i][2];
        try {
            ComponentName cn = new ComponentName(packageName, className);
            packageManager.getActivityInfo(cn, PackageManager.GET_META_DATA);
            alarmClockIntent.setComponent(cn);
            foundClockImpl = true;
            break;
        } catch (NameNotFoundException e) {
            Log.d(TAG, "Alarm clock " + clockImpls[i][0] + " not found");
        }
    }

    if (foundClockImpl) {
        alarmClockIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }
    return alarmClockIntent;
}

From source file:cn.edu.wyu.documentviewer.DocumentsActivity.java

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

    mRoots = DocumentsApplication.getRootsCache(this);

    virtualIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    virtualIntent.addCategory(Intent.CATEGORY_OPENABLE);
    virtualIntent.setType("*/*");
    virtualIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);

    setResult(Activity.RESULT_CANCELED);
    setContentView(R.layout.activity);/* ww  w.j  a  v  a  2 s  .c o  m*/

    final Resources res = getResources();
    mShowAsDialog = res.getBoolean(R.bool.show_as_dialog);

    if (mShowAsDialog) {
        // backgroundDimAmount from theme isn't applied; do it manually
        final WindowManager.LayoutParams a = getWindow().getAttributes();
        a.dimAmount = 0.6f;
        getWindow().setAttributes(a);

        getWindow().setFlags(0, WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
        getWindow().setFlags(~0, WindowManager.LayoutParams.FLAG_DIM_BEHIND);

        // Inset ourselves to look like a dialog
        final Point size = new Point();
        getWindowManager().getDefaultDisplay().getSize(size);

        final int width = (int) res.getFraction(R.dimen.dialog_width, size.x, size.x);
        final int height = (int) res.getFraction(R.dimen.dialog_height, size.y, size.y);
        final int insetX = (size.x - width) / 2;
        final int insetY = (size.y - height) / 2;

        final Drawable before = getWindow().getDecorView().getBackground();
        final Drawable after = new InsetDrawable(before, insetX, insetY, insetX, insetY);
        getWindow().getDecorView().setBackground(after);

        // Dismiss when touch down in the dimmed inset area
        getWindow().getDecorView().setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    final float x = event.getX();
                    final float y = event.getY();
                    if (x < insetX || x > v.getWidth() - insetX || y < insetY || y > v.getHeight() - insetY) {
                        finish();
                        return true;
                    }
                }
                return false;
            }
        });

    } else {
        // Non-dialog means we have a drawer
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer_glyph,
                R.string.drawer_open, R.string.drawer_close);

        mDrawerLayout.setDrawerListener(mDrawerListener);
        mDrawerLayout.setDrawerShadow(R.drawable.ic_drawer_shadow, GravityCompat.START);

        mRootsContainer = findViewById(R.id.container_roots);
    }

    mDirectoryContainer = (DirectoryContainerView) findViewById(R.id.container_directory);

    if (icicle != null) {
        mState = icicle.getParcelable(EXTRA_STATE);
    } else {
        if (DEBUG) {
            Log.i(TAG, "mState");
        }
        buildDefaultState();
    }

    // Hide roots when we're managing a specific root
    if (mState.action == ACTION_MANAGE) {
        if (mShowAsDialog) {
            findViewById(R.id.dialog_roots).setVisibility(View.GONE);
        } else {
            mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        }
    }

    if (mState.action == ACTION_CREATE) {
        final String mimeType = virtualIntent.getType();
        final String title = virtualIntent.getStringExtra(Intent.EXTRA_TITLE);
        SaveFragment.show(getFragmentManager(), mimeType, title);
    }

    if (mState.action == ACTION_GET_CONTENT) {
        final Intent moreApps = new Intent(virtualIntent);
        moreApps.setComponent(null);
        moreApps.setPackage(null);
        RootsFragment.show(getFragmentManager(), moreApps);
    } else if (mState.action == ACTION_OPEN || mState.action == ACTION_CREATE) {
        RootsFragment.show(getFragmentManager(), null);
    }

    if (!mState.restored) {
        if (mState.action == ACTION_MANAGE) {
            final Uri rootUri = virtualIntent.getData();
            new RestoreRootTask(rootUri).executeOnExecutor(getCurrentExecutor());
        } else {
            new RestoreStackTask().execute();
        }
    } else {
        onCurrentDirectoryChanged(ANIM_NONE);
    }
}

From source file:com.actionbarsherlock.internal.view.menu.MenuBuilder.java

public int addIntentOptions(int group, int id, int categoryOrder, ComponentName caller, Intent[] specifics,
        Intent intent, int flags, android.view.MenuItem[] outSpecificItems) {
    PackageManager pm = mContext.getPackageManager();
    final List<ResolveInfo> lri = pm.queryIntentActivityOptions(caller, specifics, intent, 0);
    final int N = lri != null ? lri.size() : 0;

    if ((flags & FLAG_APPEND_TO_GROUP) == 0) {
        removeGroup(group);/*from   w w  w.  ja  v  a 2s  .  c  om*/
    }

    for (int i = 0; i < N; i++) {
        final ResolveInfo ri = lri.get(i);
        Intent rintent = new Intent(ri.specificIndex < 0 ? intent : specifics[ri.specificIndex]);
        rintent.setComponent(
                new ComponentName(ri.activityInfo.applicationInfo.packageName, ri.activityInfo.name));
        final MenuItem item = add(group, id, categoryOrder, ri.loadLabel(pm)).setIcon(ri.loadIcon(pm))
                .setIntent(rintent);
        if (outSpecificItems != null && ri.specificIndex >= 0) {
            outSpecificItems[ri.specificIndex] = item;
        }
    }

    return N;
}

From source file:org.opensilk.music.iab.IabHelper.java

/**
 * Starts the setup process. This will start up the setup process asynchronously.
 * You will be notified through the listener when the setup process is complete.
 * This method is safe to call from a UI thread.
 *
 * @param listener The listener to notify when the setup process is complete.
 *//*w  w  w  . ja  v  a 2  s.  c om*/
public void startSetup(final OnIabSetupFinishedListener listener) {
    // If already set up, can't do it again.
    checkNotDisposed();
    if (mSetupDone)
        throw new IllegalStateException("IAB helper is already set up.");

    // Connection to IAB service
    logDebug("Starting in-app billing setup.");
    mServiceConn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            logDebug("Billing service disconnected.");
            mService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            if (mDisposed)
                return;
            logDebug("Billing service connected.");
            mService = IInAppBillingService.Stub.asInterface(service);
            String packageName = mContext.getPackageName();
            try {
                logDebug("Checking for in-app billing 3 support.");

                // check for in-app billing v3 support
                int response = mService.isBillingSupported(3, packageName, ITEM_TYPE_INAPP);
                if (response != BILLING_RESPONSE_RESULT_OK) {
                    if (listener != null)
                        listener.onIabSetupFinished(
                                new IabResult(response, "Error checking for billing v3 support."));

                    // if in-app purchases aren't supported, neither are subscriptions.
                    mSubscriptionsSupported = false;
                    return;
                }
                logDebug("In-app billing version 3 supported for " + packageName);

                // check for v3 subscriptions support
                response = mService.isBillingSupported(3, packageName, ITEM_TYPE_SUBS);
                if (response == BILLING_RESPONSE_RESULT_OK) {
                    logDebug("Subscriptions AVAILABLE.");
                    mSubscriptionsSupported = true;
                } else {
                    logDebug("Subscriptions NOT AVAILABLE. Response: " + response);
                }

                mSetupDone = true;
            } catch (RemoteException e) {
                if (listener != null) {
                    listener.onIabSetupFinished(new IabResult(IABHELPER_REMOTE_EXCEPTION,
                            "RemoteException while setting up in-app billing."));
                }
                e.printStackTrace();
                return;
            }

            if (listener != null) {
                listener.onIabSetupFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Setup successful."));
            }
        }
    };

    Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
    serviceIntent.setPackage("com.android.vending");
    List<ResolveInfo> infos = mContext.getPackageManager().queryIntentServices(serviceIntent, 0);
    if (infos != null && !infos.isEmpty() && infos.get(0).serviceInfo != null) {
        ServiceInfo si = infos.get(0).serviceInfo;
        serviceIntent.setComponent(new ComponentName(si.packageName, si.name));
        // service available to handle that Intent
        mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
    } else {
        // no service available to handle that Intent
        if (listener != null) {
            listener.onIabSetupFinished(new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE,
                    "Billing service unavailable on device."));
        }
    }
}

From source file:android.support.v7.internal.view.menu.MenuBuilder.java

@Override
public int addIntentOptions(int group, int id, int categoryOrder, ComponentName caller, Intent[] specifics,
        Intent intent, int flags, MenuItem[] outSpecificItems) {
    PackageManager pm = mContext.getPackageManager();
    final List<ResolveInfo> lri = pm.queryIntentActivityOptions(caller, specifics, intent, 0);
    final int N = lri != null ? lri.size() : 0;

    if ((flags & FLAG_APPEND_TO_GROUP) == 0) {
        removeGroup(group);/*w w w.  jav  a2 s  .  com*/
    }

    for (int i = 0; i < N; i++) {
        final ResolveInfo ri = lri.get(i);
        Intent rintent = new Intent(ri.specificIndex < 0 ? intent : specifics[ri.specificIndex]);
        rintent.setComponent(
                new ComponentName(ri.activityInfo.applicationInfo.packageName, ri.activityInfo.name));
        final MenuItem item = add(group, id, categoryOrder, ri.loadLabel(pm)).setIcon(ri.loadIcon(pm))
                .setIntent(rintent);
        if (outSpecificItems != null && ri.specificIndex >= 0) {
            outSpecificItems[ri.specificIndex] = item;
        }
    }

    return N;
}

From source file:com.mediatek.systemupdate.HttpManager.java

private boolean doBindService(Context context) {

    if (context != null) {
        // mIsBound = context.bindService(new Intent(SYS_OPER_INTENT),
        // mConnection, Context.BIND_AUTO_CREATE);
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.mediatek.systemupdate.sysoper",
                "com.mediatek.systemupdate.sysoper.SysOperService"));
        mIsBound = context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }//ww w  .  j av  a2  s . c  om
    Xlog.i(TAG, "dobindService, isbound=" + mIsBound);
    return mIsBound;
}

From source file:org.tomahawk.tomahawk_android.services.PlaybackService.java

/**
 * Update the playback controls/views which are being shown on the lockscreen
 *///from  w  ww.j  a  v  a 2  s  .co m
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void updateLockscreenControls() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        Log.d(TAG, "updateLockscreenControls()");
        // Use the media button APIs (if available) to register ourselves for media button
        // events
        MediaButtonHelper.registerMediaButtonEventReceiverCompat(mAudioManager, mMediaButtonReceiverComponent);

        if (mRemoteControlClientCompat == null) {
            Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
            intent.setComponent(mMediaButtonReceiverComponent);
            mRemoteControlClientCompat = new RemoteControlClientCompat(
                    PendingIntent.getBroadcast(PlaybackService.this /*context*/, 0 /*requestCode, ignored*/,
                            intent /*intent*/, 0 /*flags*/));
            RemoteControlHelper.registerRemoteControlClient(mAudioManager, mRemoteControlClientCompat);
        }

        // Use the remote control APIs (if available) to set the playback state
        if (isPlaying()) {
            mRemoteControlClientCompat.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING);
        } else {
            mRemoteControlClientCompat.setPlaybackState(RemoteControlClient.PLAYSTATE_STOPPED);
        }

        int flags = RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE;
        if (hasNextEntry()) {
            flags |= RemoteControlClient.FLAG_KEY_MEDIA_NEXT;
        }
        if (hasPreviousEntry()) {
            flags |= RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS;
        }
        mRemoteControlClientCompat.setTransportControlFlags(flags);

        // Update the remote controls
        synchronized (this) {
            RemoteControlClientCompat.MetadataEditorCompat editor = mRemoteControlClientCompat
                    .editMetadata(true);
            editor.putString(MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST,
                    getCurrentQuery().getArtist().getPrettyName())
                    .putString(MediaMetadataRetriever.METADATA_KEY_ARTIST,
                            getCurrentQuery().getArtist().getPrettyName())
                    .putString(MediaMetadataRetriever.METADATA_KEY_TITLE, getCurrentQuery().getPrettyName())
                    .putLong(MediaMetadataRetriever.METADATA_KEY_DURATION,
                            getCurrentQuery().getPreferredTrack().getDuration());
            if (!TextUtils.isEmpty(getCurrentQuery().getAlbum().getPrettyName())) {
                editor.putString(MediaMetadataRetriever.METADATA_KEY_ALBUM,
                        getCurrentQuery().getAlbum().getPrettyName());
            }
            editor.apply();
            Log.d(TAG, "Setting lockscreen metadata to: " + getCurrentQuery().getArtist().getPrettyName() + ", "
                    + getCurrentQuery().getPrettyName());
        }

        Picasso.with(TomahawkApp.getContext()).cancelRequest(mLockscreenTarget);
        ImageUtils.loadImageIntoBitmap(TomahawkApp.getContext(), getCurrentQuery().getImage(),
                mLockscreenTarget, Image.getLargeImageSize(), getCurrentQuery().hasArtistImage());
    }
}

From source file:com.partypoker.poker.engagement.reach.EngagementReachAgent.java

/**
 * Filter the intent to a single activity so a chooser won't pop up. Do not handle fall back here.
 * @param intent intent to filter.//from   w  w  w . j a v  a  2s .  co  m
 */
private void filterIntent(Intent intent) {
    for (ResolveInfo resolveInfo : mContext.getPackageManager().queryIntentActivities(intent, 0)) {
        ActivityInfo activityInfo = resolveInfo.activityInfo;
        String packageName = mContext.getPackageName();
        if (activityInfo.packageName.equals(packageName)) {
            intent.setComponent(new ComponentName(packageName, activityInfo.name));
            break;
        }
    }
}