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:com.mikhaellopez.saveinsta.activity.MainActivity.java

@OnClick({ R.id.text_user_name, R.id.icon_profile })
protected void onClickUserName() {
    Uri uri = Uri.parse("http://instagram.com/_u/" + mUserName);
    Intent likeIng = new Intent(Intent.ACTION_VIEW, uri);
    likeIng.setPackage("com.instagram.android");
    try {/*from w ww .j av  a  2  s . co  m*/
        startActivity(likeIng);
    } catch (ActivityNotFoundException e) {
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://instagram.com/" + mUserName)));
    }
}

From source file:it.scoppelletti.mobilepower.app.CommonMenuFragment.java

/**
 * Gestione della selezione di una voce di menù.
 * //from www. j av a 2  s .  com
 * @param  item Voce di menù
 * @return      Indicatore di evento gestito.
 */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int itemId = item.getItemId();
    String action = null;
    Intent intent = null;
    Context ctx = getActivity();

    if (itemId == R.id.cmd_settings) {
        action = CommonMenuFragment.ACTION_SETTINGS;
    } else if (itemId == R.id.cmd_help) {
        action = CommonMenuFragment.ACTION_HELP;
    } else if (itemId == R.id.cmd_about) {
        action = CommonMenuFragment.ACTION_ABOUT;
    } else if (itemId == R.id.cmd_buy) {
        intent = AppUtils.newBuyIntent(ctx);
    }
    if (action != null) {
        intent = new Intent(action);
        intent.setPackage(ctx.getPackageName());
    }
    if (intent != null) {
        ctx.startActivity(intent);
        return true;
    }

    return super.onOptionsItemSelected(item);
}

From source file:kr.go.hf.hfappandroid.app.intro.IntroActivity.java

/**
 * push id ?// w w  w.j  av  a  2 s.  c  om
 */
private void initPush() {
    Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
    Parcelable value = PendingIntent.getBroadcast(this, 0, new Intent(), 0);
    registrationIntent.setPackage("com.google.android");
    registrationIntent.putExtra("app", value);
    registrationIntent.putExtra("sender", Constants.PROJECT_NUMBER);
    startService(registrationIntent);
}

From source file:com.ibm.mf.geofence.MFGeofencingManager.java

/**
 * Load a set of geofences from a reosurce file.
 * @param resource the path to the resource to load the geofences from.
 *//*from w  ww .  j  ava 2 s  . c  o  m*/
public void loadGeofencesFromResource(final String resource) {
    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        private GeofenceList geofenceList;
        private HttpRequestError error;

        @Override
        protected Void doInBackground(Void... params) {
            ZipInputStream zis = null;
            try {
                InputStream is = getClass().getClassLoader().getResourceAsStream(resource);
                zis = new ZipInputStream(is);
                ZipEntry entry;
                Map<String, PersistentGeofence> allGeofences = new HashMap<>();
                while ((entry = zis.getNextEntry()) != null) {
                    byte[] bytes = GeofencingUtils.loadBytes(zis);
                    if (bytes != null) {
                        int fileSize = bytes.length;
                        JSONObject json = new JSONObject(new String(bytes, "UTF-8"));
                        bytes = null; // the byte[] may be large, we make sure it can be GC-ed ASAP
                        GeofenceList list = GeofencingJSONUtils.parseGeofences(json);
                        List<PersistentGeofence> geofences = list.getGeofences();
                        if ((geofences != null) && !geofences.isEmpty()) {
                            PersistentGeofence.saveInTx(geofences);
                            log.debug(String.format(Locale.US,
                                    "loaded %,d geofences from resource '[%s]/%s' (%,d bytes)",
                                    geofences.size(), resource, entry.getName(), fileSize));
                        }

                        for (PersistentGeofence pg : list.getGeofences()) {
                            allGeofences.put(pg.getCode(), pg);
                        }
                    } else {
                        log.debug(String.format("the zip entry [%s]/%s is empty", resource, entry.getName()));
                    }
                }
                geofenceList = new GeofenceList(new ArrayList<>(allGeofences.values()));
                log.debug(String.format(Locale.US, "loaded %,d geofences from resource '[%s]'",
                        allGeofences.size(), resource));
            } catch (Exception e) {
                error = new HttpRequestError(-1, e, String.format("error loading resource '%s'", resource));
            } finally {
                try {
                    zis.close();
                } catch (Exception e) {
                    log.error(String.format("error closing zip input stream for resource %s", resource), e);
                    if (error == null) {
                        error = new HttpRequestError(-1, e,
                                String.format("error loading resource '%s'", resource));
                    }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            if (error != null) {
                log.error(String.format("error loading resource %s : %s", resource, error));
            } else {
                try {
                    Intent broadcastIntent = new Intent(MFGeofenceEvent.ACTION_GEOFENCE_EVENT);
                    broadcastIntent.setPackage(mContext.getPackageName());
                    MFGeofenceEvent.toIntent(broadcastIntent, MFGeofenceEvent.Type.SERVER_SYNC,
                            geofenceList.getGeofences(), null);
                    mContext.sendBroadcast(broadcastIntent);
                } catch (Exception e) {
                    log.error("error sending broadcast event", e);
                }
            }
        }
    };
    task.execute();
}

From source file:com.linkbubble.MainApplication.java

public static boolean loadIntent(Context context, String packageName, String className, String urlAsString,
        long urlLoadStartTime, boolean toastOnError) {

    Intent openIntent = new Intent(Intent.ACTION_VIEW);

    try {/*  w  ww.  j av a 2  s.co  m*/
        openIntent.setClassName(packageName, className);
        openIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        openIntent.setData(Uri.parse(urlAsString));
        context.startActivity(openIntent);
        //Log.d(TAG, "redirect to app: " + resolveInfo.loadLabel(context.getPackageManager()) + ", url:" + url);
        if (urlLoadStartTime > -1) {
            Settings.get().trackLinkLoadTime(System.currentTimeMillis() - urlLoadStartTime,
                    Settings.LinkLoadType.AppRedirectBrowser, urlAsString);
        }
        CrashTracking.log("MainApplication.loadIntent()");
        return true;
    } catch (Exception ex) {
        // We want to catch SecurityException || ActivityNotFoundException
        openIntent = new Intent(Intent.ACTION_VIEW);
        openIntent.setPackage(packageName);
        openIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        openIntent.setData(Uri.parse(urlAsString));
        try {
            context.startActivity(openIntent);
            if (urlLoadStartTime > -1) {
                Settings.get().trackLinkLoadTime(System.currentTimeMillis() - urlLoadStartTime,
                        Settings.LinkLoadType.AppRedirectBrowser, urlAsString);
            }
            CrashTracking.log("MainApplication.loadIntent() [2]");
            return true;
        } catch (SecurityException ex2) {
            if (toastOnError) {
                Toast.makeText(context, R.string.unable_to_launch_app, Toast.LENGTH_SHORT).show();
            }
            return false;
        } catch (ActivityNotFoundException activityNotFoundException) {
            if (toastOnError) {
                Toast.makeText(context, R.string.unable_to_launch_app, Toast.LENGTH_SHORT).show();
            }
            return false;
        }
    }
}

From source file:bolts.AppLinkNavigation.java

/**
 * Performs the navigation.//w w w  .jav  a  2 s . c  o m
 *
 * @param context the Context from which the navigation should be performed.
 * @return the {@link NavigationResult} performed by navigating.
 */
public NavigationResult navigate(Context context) {
    PackageManager pm = context.getPackageManager();
    Bundle finalAppLinkData = buildAppLinkDataForNavigation(context);

    Intent eligibleTargetIntent = null;
    for (AppLink.Target target : getAppLink().getTargets()) {
        Intent targetIntent = new Intent(Intent.ACTION_VIEW);
        if (target.getUrl() != null) {
            targetIntent.setData(target.getUrl());
        } else {
            targetIntent.setData(appLink.getSourceUrl());
        }
        targetIntent.setPackage(target.getPackageName());
        if (target.getClassName() != null) {
            targetIntent.setClassName(target.getPackageName(), target.getClassName());
        }
        targetIntent.putExtra(AppLinks.KEY_NAME_APPLINK_DATA, finalAppLinkData);

        ResolveInfo resolved = pm.resolveActivity(targetIntent, PackageManager.MATCH_DEFAULT_ONLY);
        if (resolved != null) {
            eligibleTargetIntent = targetIntent;
            break;
        }
    }

    Intent outIntent = null;
    NavigationResult result = NavigationResult.FAILED;
    if (eligibleTargetIntent != null) {
        outIntent = eligibleTargetIntent;
        result = NavigationResult.APP;
    } else {
        // Fall back to the web if it's available
        Uri webUrl = getAppLink().getWebUrl();
        if (webUrl != null) {
            JSONObject appLinkDataJson;
            try {
                appLinkDataJson = getJSONForBundle(finalAppLinkData);
            } catch (JSONException e) {
                sendAppLinkNavigateEventBroadcast(context, eligibleTargetIntent, NavigationResult.FAILED, e);
                throw new RuntimeException(e);
            }
            webUrl = webUrl.buildUpon()
                    .appendQueryParameter(AppLinks.KEY_NAME_APPLINK_DATA, appLinkDataJson.toString()).build();
            outIntent = new Intent(Intent.ACTION_VIEW, webUrl);
            result = NavigationResult.WEB;
        }
    }

    sendAppLinkNavigateEventBroadcast(context, outIntent, result, null);
    if (outIntent != null) {
        context.startActivity(outIntent);
    }
    return result;
}

From source file:com.kanedias.vanilla.audiotag.PluginService.java

/**
 * This plugin also has P2P functionality with others. It provides generic way to
 * read and write tags for the file./* ww w  .ja  v a  2 s. c  om*/
 * <br/>
 * If intent is passed with EXTRA_PARAM_P2P and READ then EXTRA_PARAM_P2P_KEY is considered
 * as an array of field keys to retrieve from file. The values read are written in the same order
 * into answer intent into EXTRA_PARAM_P2P_VAL.
 * <br/>
 * If intent is passed with EXTRA_PARAM_P2P and WRITE then EXTRA_PARAM_P2P_KEY is considered
 * as an array of field keys to write to file. EXTRA_PARAM_P2P_VAL represents values to be written in
 * the same order.
 *
 */
private void handleP2pIntent() {
    String request = mLaunchIntent.getStringExtra(EXTRA_PARAM_P2P);
    switch (request) {
    case P2P_WRITE_TAG: {
        String[] fields = mLaunchIntent.getStringArrayExtra(EXTRA_PARAM_P2P_KEY);
        String[] values = mLaunchIntent.getStringArrayExtra(EXTRA_PARAM_P2P_VAL);
        for (int i = 0; i < fields.length; ++i) {
            try {
                FieldKey key = FieldKey.valueOf(fields[i]);
                mTag.setField(key, values[i]);
            } catch (IllegalArgumentException iae) {
                Log.e(LOG_TAG, "Invalid tag requested: " + fields[i], iae);
                Toast.makeText(this, R.string.invalid_tag_requested, Toast.LENGTH_SHORT).show();
            } catch (FieldDataInvalidException e) {
                // should not happen
                Log.e(LOG_TAG, "Error writing tag", e);
            }
        }
        writeFile();
        break;
    }
    case P2P_READ_TAG: {
        String[] fields = mLaunchIntent.getStringArrayExtra(EXTRA_PARAM_P2P_KEY);
        ApplicationInfo responseApp = mLaunchIntent.getParcelableExtra(EXTRA_PARAM_PLUGIN_APP);

        String[] values = new String[fields.length];
        for (int i = 0; i < fields.length; ++i) {
            try {
                FieldKey key = FieldKey.valueOf(fields[i]);
                values[i] = mTag.getFirst(key);
            } catch (IllegalArgumentException iae) {
                Log.e(LOG_TAG, "Invalid tag requested: " + fields[i], iae);
                Toast.makeText(this, R.string.invalid_tag_requested, Toast.LENGTH_SHORT).show();
            }
        }

        Intent response = new Intent(ACTION_LAUNCH_PLUGIN);
        response.putExtra(EXTRA_PARAM_P2P, P2P_READ_TAG);
        response.setPackage(responseApp.packageName);
        response.putExtra(EXTRA_PARAM_P2P_VAL, values);
        startService(response);
        break;
    }
    case P2P_READ_ART: {
        ApplicationInfo responseApp = mLaunchIntent.getParcelableExtra(EXTRA_PARAM_PLUGIN_APP);
        Artwork cover = mTag.getFirstArtwork();
        Uri uri = null;
        try {
            if (cover == null) {
                Log.w(LOG_TAG, "Artwork is not present for file " + mAudioFile.getFile().getName());
                break;
            }

            File coversDir = new File(getCacheDir(), "covers");
            if (!coversDir.exists() && !coversDir.mkdir()) {
                Log.e(LOG_TAG, "Couldn't create dir for covers! Path " + getCacheDir());
                break;
            }

            // cleanup old images
            for (File oldImg : coversDir.listFiles()) {
                if (!oldImg.delete()) {
                    Log.w(LOG_TAG, "Couldn't delete old image file! Path " + oldImg);
                }
            }

            // write artwork to file
            File coverTmpFile = new File(coversDir, UUID.randomUUID().toString());
            FileOutputStream fos = new FileOutputStream(coverTmpFile);
            fos.write(cover.getBinaryData());
            fos.close();

            // create sharable uri
            uri = FileProvider.getUriForFile(this, "com.kanedias.vanilla.audiotag.fileprovider", coverTmpFile);
        } catch (IOException e) {
            Log.e(LOG_TAG, "Couldn't write to cache file", e);
            Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
        } finally {
            // share uri if created successfully
            Intent response = new Intent(ACTION_LAUNCH_PLUGIN);
            response.putExtra(EXTRA_PARAM_P2P, P2P_READ_ART);
            response.setPackage(responseApp.packageName);
            if (uri != null) {
                grantUriPermission(responseApp.packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                response.putExtra(EXTRA_PARAM_P2P_VAL, uri);
            }
            startService(response);
        }
        break;
    }
    case P2P_WRITE_ART: {
        Uri imgLink = mLaunchIntent.getParcelableExtra(EXTRA_PARAM_P2P_VAL);

        try {
            ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(imgLink, "r");
            if (pfd == null) {
                return;
            }

            FileInputStream fis = new FileInputStream(pfd.getFileDescriptor());
            byte[] imgBytes = TagEditorUtils.readFully(fis);

            Artwork cover = new AndroidArtwork();
            cover.setBinaryData(imgBytes);
            cover.setMimeType(ImageFormats.getMimeTypeForBinarySignature(imgBytes));
            cover.setDescription("");
            cover.setPictureType(PictureTypes.DEFAULT_ID);

            mTag.deleteArtworkField();
            mTag.setField(cover);
        } catch (IOException | IllegalArgumentException | FieldDataInvalidException e) {
            Log.e(LOG_TAG, "Invalid artwork!", e);
            Toast.makeText(this, R.string.invalid_artwork_provided, Toast.LENGTH_SHORT).show();
        }

        writeFile();
        break;
    }
    }

}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.InviteToSharedAppFeedObj.java

public void handleDirectMessage(Context context, Contact from, JSONObject obj) {
    try {//from   w ww.  java2  s. c o  m
        String packageName = obj.getString(PACKAGE_NAME);
        String feedName = obj.getString("sharedFeedName");
        JSONArray ids = obj.getJSONArray(PARTICIPANTS);
        Intent launch = new Intent();
        launch.setAction(Intent.ACTION_MAIN);
        launch.addCategory(Intent.CATEGORY_LAUNCHER);
        launch.putExtra("type", "invite_app_feed");
        launch.putExtra("creator", false);
        launch.putExtra("sender", from.id);
        launch.putExtra("sharedFeedName", feedName);
        launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        long[] idArray = new long[ids.length()];
        for (int i = 0; i < ids.length(); i++) {
            idArray[i] = ids.getLong(i);
        }
        launch.putExtra("participants", idArray);
        launch.setPackage(packageName);
        final PackageManager mgr = context.getPackageManager();
        List<ResolveInfo> resolved = mgr.queryIntentActivities(launch, 0);
        if (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 from " + from.name,
                "Invitation received from " + from.name, "Click to launch application: " + packageName,
                contentIntent);
    } catch (JSONException e) {
        Log.e(TAG, e.getMessage());
    }
}

From source file:com.vladstirbu.cordova.CDVInstagramVideoPlugin.java

private void share(String videoUrl, String captionString) {
    if (videoUrl != null && videoUrl.length() > 0) {

        this.webView.loadUrl("javascript:console.log('processing " + videoUrl + "');");

        byte[] videoData = null;

        try {/*from w w w  . j  a  v  a  2 s. com*/

            URL url = new URL(videoUrl);

            URLConnection ucon = url.openConnection();
            InputStream is = ucon.getInputStream();
            videoData = new byte[is.available()];
            is.read(videoData);
            is.close();
        } catch (Exception e) {
            this.webView.loadUrl("javascript:console.log('" + e.getMessage() + "');");
            e.printStackTrace();
        }

        File file = null;
        FileOutputStream os = null;

        File parentDir = this.webView.getContext().getExternalFilesDir(null);
        File[] oldVideos = parentDir.listFiles(OLD_IMAGE_FILTER);
        for (File oldVideo : oldVideos) {
            oldVideo.delete();
        }

        try {
            file = File.createTempFile("instagram_video", ".mp4", parentDir);
            os = new FileOutputStream(file, true);
        } catch (Exception e) {
            this.webView.loadUrl("javascript:console.log('" + e.getMessage() + "');");
            e.printStackTrace();
        }

        try {
            os.write(videoData);
            os.flush();
            os.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("video/mp4");

        //File media = new File(file);
        //Uri uri = Uri.fromFile(media);

        // Add the URI to the Intent.
        //share.putExtra(Intent.EXTRA_STREAM, uri);

        // Broadcast the Intent.
        //startActivity(Intent.createChooser(share, "Share to"));

        shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + file));
        shareIntent.putExtra(Intent.EXTRA_TEXT, captionString);
        shareIntent.setPackage("com.instagram.android");

        this.cordova.startActivityForResult((CordovaPlugin) this, shareIntent, 12345);

    } else {
        this.cbContext.error("Expected one non-empty string argument.");
    }
}

From source file:com.appsimobile.appsii.module.weather.WeatherLoadingService.java

void onWeatherDataLoaded(@Nullable CircularArray<WeatherData> weatherDataList, String unit) {

    int N = weatherDataList == null ? 0 : weatherDataList.size();
    for (int i1 = 0; i1 < N; i1++) {
        WeatherData weatherData = weatherDataList.get(i1);

        ContentValues weatherValues = new ContentValues();

        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_LAST_UPDATED, System.currentTimeMillis());
        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_WOEID, weatherData.woeid);

        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_ATMOSPHERE_HUMIDITY,
                weatherData.atmosphereHumidity);
        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_ATMOSPHERE_PRESSURE,
                weatherData.atmospherePressure);
        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_ATMOSPHERE_RISING,
                weatherData.atmosphereRising);
        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_ATMOSPHERE_VISIBILITY,
                weatherData.atmosphereVisible);

        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_NOW_CONDITION_CODE,
                weatherData.nowConditionCode);
        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_NOW_TEMPERATURE,
                weatherData.nowTemperature);

        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_SUNRISE, weatherData.sunrise);
        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_SUNSET, weatherData.sunset);

        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_WIND_CHILL, weatherData.windChill);
        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_WIND_DIRECTION, weatherData.windDirection);
        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_WIND_SPEED, weatherData.windSpeed);
        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_CITY, weatherData.location);
        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_UNIT, unit);

        ContentResolver contentResolver = mContext.getContentResolver();
        contentResolver.insert(WeatherContract.WeatherColumns.CONTENT_URI, weatherValues);

        List<WeatherData.Forecast> forecasts = weatherData.forecasts;
        if (!forecasts.isEmpty()) {

            int count = forecasts.size();
            ContentValues[] forecastValues = new ContentValues[count];

            for (int i = 0; i < count; i++) {
                WeatherData.Forecast forecast = forecasts.get(i);

                ContentValues contentValues = new ContentValues();
                contentValues.put(WeatherContract.ForecastColumns.COLUMN_NAME_FORECAST_DAY, forecast.julianDay);
                contentValues.put(WeatherContract.ForecastColumns.COLUMN_NAME_LAST_UPDATED,
                        System.currentTimeMillis());
                contentValues.put(WeatherContract.ForecastColumns.COLUMN_NAME_LOCATION_WOEID,
                        weatherData.woeid);
                contentValues.put(WeatherContract.ForecastColumns.COLUMN_NAME_CONDITION_CODE,
                        forecast.conditionCode);
                contentValues.put(WeatherContract.ForecastColumns.COLUMN_NAME_TEMPERATURE_HIGH, forecast.high);
                contentValues.put(WeatherContract.ForecastColumns.COLUMN_NAME_TEMPERATURE_LOW, forecast.low);
                contentValues.put(WeatherContract.ForecastColumns.COLUMN_NAME_UNIT, unit);
                forecastValues[i] = contentValues;
            }/*from   w  ww.  j  av a 2 s  .com*/
            Uri uri = WeatherContract.ForecastColumns.CONTENT_URI;
            contentResolver.bulkInsert(uri, forecastValues);
        }
    }

    Intent i = new Intent(ACTION_WEATHER_UPDATED);
    i.setPackage(mContext.getPackageName());
    mContext.sendBroadcast(i);
}