Example usage for android.content Intent setPackage

List of usage examples for android.content Intent setPackage

Introduction

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

Prototype

public @NonNull Intent setPackage(@Nullable String packageName) 

Source Link

Document

(Usually optional) Set an explicit application package name that limits the components this Intent will resolve to.

Usage

From source file:org.familab.app.supportfiles.IntentIntegrator.java

/**
 * Shares the given text by encoding it as a barcode, such that another user can
 * scan the text off the screen of the device.
 *
 * @param text the text string to encode as a barcode
 * @param type type of data to encode. See {@code com.google.zxing.client.android.Contents.Type} constants.
 * @return the {@link android.app.AlertDialog} that was shown to the user prompting them to download the app
 *   if a prompt was needed, or null otherwise
 *//*  w  w  w.j a  v a2 s.  c om*/
public final AlertDialog shareText(CharSequence text, CharSequence type) {
    Intent intent = new Intent();
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    intent.setAction(BS_PACKAGE + ".ENCODE");
    intent.putExtra("ENCODE_TYPE", type);
    intent.putExtra("ENCODE_DATA", text);
    String targetAppPackage = findTargetAppPackage(intent);
    if (targetAppPackage == null) {
        return showDownloadDialog();
    }
    intent.setPackage(targetAppPackage);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
    attachMoreExtras(intent);
    activity.startActivity(intent);
    return null;
}

From source file:biz.wiz.android.wallet.service.BlockchainServiceImpl.java

private void broadcastPeerState(final int numPeers) {
    final Intent broadcast = new Intent(ACTION_PEER_STATE);
    broadcast.setPackage(getPackageName());
    broadcast.putExtra(ACTION_PEER_STATE_NUM_PEERS, numPeers);

    LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast);
}

From source file:biz.wiz.android.wallet.service.BlockchainServiceImpl.java

private void broadcastBlockchainState() {
    final Intent broadcast = new Intent(ACTION_BLOCKCHAIN_STATE);
    broadcast.setPackage(getPackageName());
    getBlockchainState().putExtras(broadcast);
    LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast);
}

From source file:org.bobstuff.bobball.ActivityStateEnum.java

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

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.main);//from   w w w. j  av  a  2  s  . c  om

    SurfaceView surfaceView = (SurfaceView) findViewById(R.id.surface_view);
    surfaceView.setOnTouchListener(this);
    surfaceHolder = surfaceView.getHolder();
    surfaceHolder.setFormat(PixelFormat.RGB_565);
    surfaceHolder.addCallback(this);

    messageView = (TextView) findViewById(R.id.message_label);
    percentageCleared = (TextView) findViewById(R.id.percentageCleared);
    totalPercentageCleared = (TextView) findViewById(R.id.totalPercentageCleared);
    bonusPoints = (TextView) findViewById(R.id.bonusPoints);

    button = (Button) findViewById(R.id.continue_button);
    button.setOnClickListener(this);

    retryButton = (Button) findViewById(R.id.retryButton);
    backToLevelSelectButton = (Button) findViewById(R.id.backToLevelSelectButton);

    statusTopleft = (TextView) findViewById(R.id.status_topleft);
    statusTopright = (TextView) findViewById(R.id.status_topright);
    statusBotleft = (TextView) findViewById(R.id.status_botleft);
    statusBotright = (TextView) findViewById(R.id.status_botright);

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            if (gameManager.isPaused()) {
                gameManager.togglePauseGameLoop();
            }
            changeToPauseScreen();
            onClick(drawerView);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            if (activityState == ActivityStateEnum.GAMERUNNING) {
                if (!gameManager.isPaused()) {
                    gameManager.togglePauseGameLoop();
                }
                showPauseScreen();
            }
        }
    });

    drawerLayout.setFocusableInTouchMode(false); // if set to false, the drawer doesn't react to pressing the back key by default

    statusTopright.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            statusTopright.setTextColor(0xffCCCCFF);
            secretHandshake += 1;
        }
    });

    statusBotright.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (secretHandshake > 4) {
                statusBotright.setTextColor(0xffCCCCFF);
                //request a hidden service
                Intent intent = new Intent("org.torproject.android.REQUEST_HS_PORT");
                intent.setPackage("org.torproject.android");
                intent.putExtra("hs_port", 8477);
                startActivityForResult(intent, 9999);
            }
        }
    });

    Bundle extras = getIntent().getExtras();
    level = extras.getInt("level");
    numPlayers = extras.getInt("numPlayers");

    scores = new Scores(numPlayers);
    scores.loadScores();
}

From source file:com.android.contacts.common.vcard.NotificationImportExportListener.java

@Override
public void onImportFinished(ImportRequest request, int jobId, Uri createdUri) {
    final String description = mContext.getString(R.string.importing_vcard_finished_title, request.displayName);
    final Intent intent;
    if (createdUri != null) {
        final long rawContactId = ContentUris.parseId(createdUri);
        final Uri contactUri = RawContacts.getContactLookupUri(mContext.getContentResolver(),
                ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId));
        intent = new Intent(Intent.ACTION_VIEW, contactUri);
    } else {//w w w. j  a  v a  2 s  . co m
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
    }
    intent.setPackage(mContext.getPackageName());
    final Notification notification = NotificationImportExportListener.constructFinishNotification(mContext,
            description, null, intent);
    mNotificationManager.notify(NotificationImportExportListener.DEFAULT_NOTIFICATION_TAG, jobId, notification);
}

From source file:com.z3r0byte.magistify.DashboardActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dashboard);

    mToolbar = (Toolbar) findViewById(R.id.Toolbar);
    mToolbar.setTitle(R.string.title_dashboard);
    setSupportActionBar(mToolbar);// www.j  a v a 2s . c o  m

    configUtil = new ConfigUtil(this);

    User user = new Gson().fromJson(configUtil.getString("User"), User.class);
    Profile profile = new Gson().fromJson(configUtil.getString("Profile"), Profile.class);

    NavigationDrawer navigationDrawer = new NavigationDrawer(this, mToolbar, profile, user, "Dashboard");
    navigationDrawer.SetupNavigationDrawer();

    mSwipeRefreshLayout = (ScrollRefreshLayout) findViewById(R.id.layout_refresh);
    mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary, R.color.setup_color_3,
            R.color.setup_color_5);
    mSwipeRefreshLayout.setSwipeableChildren(R.id.card_layout);
    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            Log.d(TAG, "onRefresh: Refreshing!");
            mSwipeRefreshLayout.setVisibility(View.GONE);
            mSwipeRefreshLayout.setVisibility(View.VISIBLE);
            setupAppointmentCard();
            setupChangeCard();
            retrieveGrades();
        }
    });

    if (!configUtil.getBoolean("disable_ads")) {
        MobileAds.initialize(getApplicationContext(), getString(R.string.app_ad_id));
        AdView mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().addTestDevice("BEF9819F219452AE8661484A2AA03C59").build();
        mAdView.loadAd(adRequest);
    } else {
        findViewById(R.id.adView).setVisibility(View.GONE);
    }

    if (configUtil.getInteger("failed_auth") >= 2) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage(R.string.dialog_login_failed_desc);
        alertDialogBuilder.setPositiveButton(R.string.msg_relogin, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                relogin();
            }
        });
        alertDialogBuilder.setNegativeButton(R.string.msg_later, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

    Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
    serviceIntent.setPackage("com.android.vending");
    bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);

    appointmentMain = (CardView) findViewById(R.id.card_next_appointment);
    scheduleChangeMain = (CardView) findViewById(R.id.card_schedulechanges);

    gradeMain = (CardView) findViewById(R.id.card_new_grade);
    gradeMain.setVisibility(View.GONE);

    setupAppointmentCard();
    setupChangeCard();
    retrieveGrades();

    getPurchases();
    showUpdateMessage();
}

From source file:com.feathercoin.wallet.feathercoin.service.BlockchainServiceImpl.java

private void sendBroadcastBlockchainState(final Date chainDate, final int chainHeight, final boolean replaying,
        final int download) {
    final Intent broadcast = new Intent(ACTION_BLOCKCHAIN_STATE);
    broadcast.setPackage(getPackageName());
    broadcast.putExtra(ACTION_BLOCKCHAIN_STATE_BEST_CHAIN_DATE, chainDate);
    broadcast.putExtra(ACTION_BLOCKCHAIN_STATE_BEST_CHAIN_HEIGHT, chainHeight);
    broadcast.putExtra(ACTION_BLOCKCHAIN_STATE_REPLAYING, replaying);
    broadcast.putExtra(ACTION_BLOCKCHAIN_STATE_DOWNLOAD, download);

    sendStickyBroadcast(broadcast);/*from  ww w. ja  v  a 2  s  .c om*/
}

From source file:com.chen.mail.utils.NotificationUtils.java

/**
 * Validate the notifications notification.
 *///w  w  w. j  ava2 s. c o m
private static void validateNotifications(Context context, final Folder folder, final Account account,
        boolean getAttention, boolean ignoreUnobtrusiveSetting, NotificationKey key) {

    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    final NotificationMap notificationMap = getNotificationMap(context);
    if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
        LogUtils.i(LOG_TAG, "Validating Notification: %s mapSize: %d " + "folder: %s getAttention: %b",
                createNotificationString(notificationMap), notificationMap.size(), folder.name, getAttention);
    } else {
        LogUtils.i(LOG_TAG, "Validating Notification, mapSize: %d " + "getAttention: %b",
                notificationMap.size(), getAttention);
    }
    // The number of unread messages for this account and label.
    final Integer unread = notificationMap.getUnread(key);
    final int unreadCount = unread != null ? unread.intValue() : 0;
    final Integer unseen = notificationMap.getUnseen(key);
    int unseenCount = unseen != null ? unseen.intValue() : 0;

    Cursor cursor = null;

    try {
        final Uri.Builder uriBuilder = folder.conversationListUri.buildUpon();
        uriBuilder.appendQueryParameter(UIProvider.SEEN_QUERY_PARAMETER, Boolean.FALSE.toString());
        // Do not allow this quick check to disrupt any active network-enabled conversation
        // cursor.
        uriBuilder.appendQueryParameter(UIProvider.ConversationListQueryParameters.USE_NETWORK,
                Boolean.FALSE.toString());
        cursor = context.getContentResolver().query(uriBuilder.build(), UIProvider.CONVERSATION_PROJECTION,
                null, null, null);
        if (cursor == null) {
            // This folder doesn't exist.
            LogUtils.i(LOG_TAG, "The cursor is null, so the specified folder probably does not exist");
            clearFolderNotification(context, account, folder, false);
            return;
        }
        final int cursorUnseenCount = cursor.getCount();

        // Make sure the unseen count matches the number of items in the cursor.  But, we don't
        // want to overwrite a 0 unseen count that was specified in the intent
        if (unseenCount != 0 && unseenCount != cursorUnseenCount) {
            LogUtils.i(LOG_TAG, "Unseen count doesn't match cursor count.  unseen: %d cursor count: %d",
                    unseenCount, cursorUnseenCount);
            unseenCount = cursorUnseenCount;
        }

        // For the purpose of the notifications, the unseen count should be capped at the num of
        // unread conversations.
        if (unseenCount > unreadCount) {
            unseenCount = unreadCount;
        }

        final int notificationId = getNotificationId(account.getAccountManagerAccount(), folder);

        if (unseenCount == 0) {
            LogUtils.i(LOG_TAG, "validateNotifications - cancelling account %s / folder %s",
                    LogUtils.sanitizeName(LOG_TAG, account.name),
                    LogUtils.sanitizeName(LOG_TAG, folder.persistentId));
            nm.cancel(notificationId);
            return;
        }

        // We now have all we need to create the notification and the pending intent
        PendingIntent clickIntent;

        NotificationCompat.Builder notification = new NotificationCompat.Builder(context);
        notification.setSmallIcon(R.drawable.stat_notify_email);
        notification.setTicker(account.name);

        final long when;

        final long oldWhen = NotificationActionUtils.sNotificationTimestamps.get(notificationId);
        if (oldWhen != 0) {
            when = oldWhen;
        } else {
            when = System.currentTimeMillis();
        }

        notification.setWhen(when);

        // The timestamp is now stored in the notification, so we can remove it from here
        NotificationActionUtils.sNotificationTimestamps.delete(notificationId);

        // Dispatch a CLEAR_NEW_MAIL_NOTIFICATIONS intent if the user taps the "X" next to a
        // notification.  Also this intent gets fired when the user taps on a notification as
        // the AutoCancel flag has been set
        final Intent cancelNotificationIntent = new Intent(
                MailIntentService.ACTION_CLEAR_NEW_MAIL_NOTIFICATIONS);
        cancelNotificationIntent.setPackage(context.getPackageName());
        cancelNotificationIntent.setData(Utils.appendVersionQueryParameter(context, folder.folderUri.fullUri));
        cancelNotificationIntent.putExtra(Utils.EXTRA_ACCOUNT, account);
        cancelNotificationIntent.putExtra(Utils.EXTRA_FOLDER, folder);

        notification.setDeleteIntent(
                PendingIntent.getService(context, notificationId, cancelNotificationIntent, 0));

        // Ensure that the notification is cleared when the user selects it
        notification.setAutoCancel(true);

        boolean eventInfoConfigured = false;

        final boolean isInbox = folder.folderUri.equals(account.settings.defaultInbox);
        final FolderPreferences folderPreferences = new FolderPreferences(context, account.getEmailAddress(),
                folder, isInbox);

        if (isInbox) {
            final AccountPreferences accountPreferences = new AccountPreferences(context,
                    account.getEmailAddress());
            moveNotificationSetting(accountPreferences, folderPreferences);
        }

        if (!folderPreferences.areNotificationsEnabled()) {
            LogUtils.i(LOG_TAG, "Notifications are disabled for this folder; not notifying");
            // Don't notify
            return;
        }

        if (unreadCount > 0) {
            // How can I order this properly?
            if (cursor.moveToNext()) {
                final Intent notificationIntent;

                // Launch directly to the conversation, if there is only 1 unseen conversation
                final boolean launchConversationMode = (unseenCount == 1);
                if (launchConversationMode) {
                    notificationIntent = createViewConversationIntent(context, account, folder, cursor);
                } else {
                    notificationIntent = createViewConversationIntent(context, account, folder, null);
                }

                Analytics.getInstance().sendEvent("notification_create",
                        launchConversationMode ? "conversation" : "conversation_list",
                        folder.getTypeDescription(), unseenCount);

                if (notificationIntent == null) {
                    LogUtils.e(LOG_TAG, "Null intent when building notification");
                    return;
                }

                // Amend the click intent with a hint that its source was a notification,
                // but remove the hint before it's used to generate notification action
                // intents. This prevents the following sequence:
                // 1. generate single notification
                // 2. user clicks reply, then completes Compose activity
                // 3. main activity launches, gets FROM_NOTIFICATION hint in intent
                notificationIntent.putExtra(Utils.EXTRA_FROM_NOTIFICATION, true);
                clickIntent = PendingIntent.getActivity(context, -1, notificationIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT);
                notificationIntent.removeExtra(Utils.EXTRA_FROM_NOTIFICATION);

                configureLatestEventInfoFromConversation(context, account, folderPreferences, notification,
                        cursor, clickIntent, notificationIntent, unreadCount, unseenCount, folder, when);
                eventInfoConfigured = true;
            }
        }

        final boolean vibrate = folderPreferences.isNotificationVibrateEnabled();
        final String ringtoneUri = folderPreferences.getNotificationRingtoneUri();
        final boolean notifyOnce = !folderPreferences.isEveryMessageNotificationEnabled();

        if (!ignoreUnobtrusiveSetting && notifyOnce) {
            // If the user has "unobtrusive notifications" enabled, only alert the first time
            // new mail is received in this account.  This is the default behavior.  See
            // bugs 2412348 and 2413490.
            notification.setOnlyAlertOnce(true);
        }

        LogUtils.i(LOG_TAG, "Account: %s vibrate: %s", LogUtils.sanitizeName(LOG_TAG, account.name),
                Boolean.toString(folderPreferences.isNotificationVibrateEnabled()));

        int defaults = 0;

        /*
         * We do not want to notify if this is coming back from an Undo notification, hence the
         * oldWhen check.
         */
        if (getAttention && oldWhen == 0) {
            final AccountPreferences accountPreferences = new AccountPreferences(context, account.name);
            if (accountPreferences.areNotificationsEnabled()) {
                if (vibrate) {
                    defaults |= Notification.DEFAULT_VIBRATE;
                }

                notification.setSound(TextUtils.isEmpty(ringtoneUri) ? null : Uri.parse(ringtoneUri));
                LogUtils.i(LOG_TAG, "New email in %s vibrateWhen: %s, playing notification: %s",
                        LogUtils.sanitizeName(LOG_TAG, account.name), vibrate, ringtoneUri);
            }
        }

        // TODO(skennedy) Why do we do any of the above if we're just going to bail here?
        if (eventInfoConfigured) {
            defaults |= Notification.DEFAULT_LIGHTS;
            notification.setDefaults(defaults);

            if (oldWhen != 0) {
                // We do not want to display the ticker again if we are re-displaying this
                // notification (like from an Undo notification)
                notification.setTicker(null);
            }

            nm.notify(notificationId, notification.build());
        } else {
            LogUtils.i(LOG_TAG, "event info not configured - not notifying");
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:de.schildbach.wallet.elysium.service.BlockchainServiceImpl.java

private void sendBroadcastPeerState(final int numPeers) {

    final Intent broadcast = new Intent(ACTION_PEER_STATE);
    broadcast.setPackage(getPackageName());
    broadcast.putExtra(ACTION_PEER_STATE_NUM_PEERS, numPeers);
    sendStickyBroadcast(broadcast);/*from   www  .jav a2 s. c  o m*/
}